feat(ui): redesigned book card and menu (#2396)
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import {formatFileSizeKb} from '../../../../shared/util/file-size';
|
||||
import {type BookFileResponse} from '../../data/book-response.models';
|
||||
|
||||
export interface BookFileLabelParts {
|
||||
base: string;
|
||||
suffix: string;
|
||||
full: string;
|
||||
}
|
||||
|
||||
export function bookFileLabelParts(file: BookFileResponse): BookFileLabelParts {
|
||||
const name = file.fileName ?? file.bookType ?? '';
|
||||
const ext = (file.extension ?? '').trim();
|
||||
const size = file.fileSizeKb == null ? null : formatFileSizeKb(file.fileSizeKb);
|
||||
|
||||
let base = name;
|
||||
if (ext && base.toLowerCase().endsWith(`.${ext.toLowerCase()}`)) {
|
||||
base = base.slice(0, -(ext.length + 1));
|
||||
}
|
||||
|
||||
const extensionSuffix = ext ? `.${ext}` : '';
|
||||
const sizeSuffix = size ? ` (${size})` : '';
|
||||
const suffix = `${extensionSuffix}${sizeSuffix}`;
|
||||
const full = `${base}${suffix}`.trim();
|
||||
return {base: base || name, suffix, full: full || name};
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<app-menu [ariaLabel]="'book.menu.label' | transloco" (closed)="clearOpenBook()">
|
||||
@if (readable() && readLabelKey(); as labelKey) {
|
||||
<app-menu-item value="read" [trailingIcon]="readIcon()" [trailingText]="readProgress()" (selected)="onRead()">{{ labelKey | transloco }}</app-menu-item>
|
||||
<app-menu-separator />
|
||||
}
|
||||
@if (openInNewTab() && book(); as menuBook) {
|
||||
<app-menu-item value="open-details-new-tab" [link]="['/book', menuBook.id]" target="_blank" [trailingIcon]="newTabIcon">{{ 'book.menu.openInNewTab' | transloco }}</app-menu-item>
|
||||
<app-menu-separator />
|
||||
}
|
||||
<app-menu-item value="add-to-shelf" [submenu]="shelfMenu.ariaMenu()">{{ 'book.menu.addToShelf' | transloco }}</app-menu-item>
|
||||
<app-menu-item value="mark-as" [submenu]="markAsMenu">{{ 'book.menu.markAs' | transloco }}</app-menu-item>
|
||||
@if (actionPermissions().canEmailBook && digital()) {
|
||||
<app-menu-item value="send" [submenu]="sendMenu">{{ 'book.menu.send' | transloco }}</app-menu-item>
|
||||
}
|
||||
@if (actionPermissions().canDownload && digital()) {
|
||||
@if (additionalFiles().length > 0) {
|
||||
<app-menu-item value="download" [submenu]="downloadMenu">{{ 'book.menu.download' | transloco }}</app-menu-item>
|
||||
} @else {
|
||||
<app-menu-item value="download" (selected)="onDownload()">{{ 'book.menu.download' | transloco }}</app-menu-item>
|
||||
}
|
||||
}
|
||||
@if (actionPermissions().canEditMetadata) {
|
||||
<app-menu-item value="metadata" [submenu]="metadataMenu">{{ 'book.menu.metadata' | transloco }}</app-menu-item>
|
||||
}
|
||||
@if (hasMoreActions()) {
|
||||
<app-menu-item value="more" [submenu]="moreMenu">{{ 'book.menu.more' | transloco }}</app-menu-item>
|
||||
}
|
||||
@if (actionPermissions().canDeleteBook) {
|
||||
<app-menu-separator />
|
||||
@if (additionalFiles().length > 0) {
|
||||
<app-menu-item value="delete" variant="destructive" [submenu]="deleteMenu">{{ 'common.delete' | transloco }}</app-menu-item>
|
||||
} @else {
|
||||
<app-menu-item value="delete" variant="destructive" (selected)="onDeleteRequested()">{{ 'common.delete' | transloco }}</app-menu-item>
|
||||
}
|
||||
}
|
||||
</app-menu>
|
||||
|
||||
<app-shelf-membership-menu
|
||||
#shelfMenu
|
||||
[shelves]="shelves()"
|
||||
(toggleShelf)="onToggleShelf($event.shelfId, $event.checked)"
|
||||
(createShelf)="onCreateShelf()"
|
||||
(removeFromAllShelves)="onRemoveFromAllShelves()" />
|
||||
|
||||
<app-menu #markAsMenu="ngMenu" [ariaLabel]="'book.menu.markAs' | transloco">
|
||||
<app-menu-radio-group [value]="book()?.readStatus ?? null">
|
||||
@for (status of readStatusTargets; track status) {
|
||||
<app-menu-radio [value]="status" (selected)="onSetReadStatus(status)">{{ statusLabelKey(status) | transloco }}</app-menu-radio>
|
||||
}
|
||||
</app-menu-radio-group>
|
||||
<app-menu-separator />
|
||||
<app-menu-item value="clear-read-status" (selected)="onSetReadStatus(clearReadStatus)">
|
||||
{{ clearReadStatusLabelKey | transloco }}
|
||||
</app-menu-item>
|
||||
</app-menu>
|
||||
|
||||
<app-menu #moreMenu="ngMenu" [ariaLabel]="'book.menu.more' | transloco">
|
||||
@if (canOrganizeFile()) {
|
||||
<app-menu-item value="organize-file" (selected)="onOrganizeFile()">{{ 'book.menu.organizeFile' | transloco }}</app-menu-item>
|
||||
}
|
||||
@if (actionPermissions().canResetGrimmoryProgress) {
|
||||
<app-menu-item value="reset-grimmory-progress" (selected)="onResetProgress('GRIMMORY')">{{ 'book.menu.resetGrimmoryProgress' | transloco }}</app-menu-item>
|
||||
}
|
||||
@if (actionPermissions().canResetKoreaderProgress) {
|
||||
<app-menu-item value="reset-koreader-progress" (selected)="onResetProgress('KOREADER')">{{ 'book.menu.resetKoreaderProgress' | transloco }}</app-menu-item>
|
||||
}
|
||||
</app-menu>
|
||||
|
||||
<ng-template #fileLabel let-file>
|
||||
@let parts = fileLabelParts(file);
|
||||
<span class="flex w-full min-w-0 items-baseline" [attr.title]="parts.full">
|
||||
<span class="min-w-0 truncate">{{ parts.base }}</span>
|
||||
<span class="shrink-0">{{ parts.suffix }}</span>
|
||||
</span>
|
||||
</ng-template>
|
||||
|
||||
<app-menu #downloadMenu="ngMenu" [ariaLabel]="'book.menu.download' | transloco">
|
||||
@if (book()?.primaryFile; as primaryFile) {
|
||||
<app-menu-item value="download-primary-file" (selected)="onDownload()">
|
||||
<ng-container [ngTemplateOutlet]="fileLabel" [ngTemplateOutletContext]="{$implicit: primaryFile}" />
|
||||
</app-menu-item>
|
||||
<app-menu-separator />
|
||||
}
|
||||
@for (file of additionalFiles(); track file.id) {
|
||||
<app-menu-item [value]="'download-file-' + file.id" (selected)="onDownloadFile(file)">
|
||||
<ng-container [ngTemplateOutlet]="fileLabel" [ngTemplateOutletContext]="{$implicit: file}" />
|
||||
</app-menu-item>
|
||||
}
|
||||
</app-menu>
|
||||
|
||||
<app-menu #deleteMenu="ngMenu" [ariaLabel]="'common.delete' | transloco">
|
||||
<app-menu-item value="delete-entire-book" variant="destructive" (selected)="onDeleteRequested()">{{ 'book.menu.deleteEntireBook' | transloco }}</app-menu-item>
|
||||
<app-menu-separator />
|
||||
@for (file of additionalFiles(); track file.id) {
|
||||
<app-menu-item [value]="'delete-file-' + file.id" variant="destructive" (selected)="onDeleteFileRequested(file)">
|
||||
<ng-container [ngTemplateOutlet]="fileLabel" [ngTemplateOutletContext]="{$implicit: file}" />
|
||||
</app-menu-item>
|
||||
}
|
||||
</app-menu>
|
||||
|
||||
<app-menu #sendMenu="ngMenu" [ariaLabel]="'book.menu.send' | transloco">
|
||||
@if (quickSendAvailable()) {
|
||||
<app-menu-item value="quick-send" (selected)="onQuickSend()">{{ 'book.menu.quickSend' | transloco }}</app-menu-item>
|
||||
}
|
||||
<app-menu-item value="custom-send" (selected)="onCustomSend()">{{ 'book.menu.customSend' | transloco }}</app-menu-item>
|
||||
</app-menu>
|
||||
|
||||
<app-menu #metadataMenu="ngMenu" [ariaLabel]="'book.menu.metadata' | transloco">
|
||||
<app-menu-item value="edit-metadata" (selected)="onEditMetadata()">{{ 'book.menu.editMetadata' | transloco }}</app-menu-item>
|
||||
<app-menu-separator />
|
||||
<app-menu-item value="refresh-metadata" (selected)="onFetchMetadata()">{{ 'book.menu.fetchMetadata' | transloco }}</app-menu-item>
|
||||
<app-menu-item value="refresh-metadata-with-options" (selected)="onFetchMetadataWithOptions()">{{ 'book.menu.fetchMetadataWithOptions' | transloco }}</app-menu-item>
|
||||
<app-menu-item value="search-providers" (selected)="onSearchMetadata()">{{ 'book.menu.searchProviders' | transloco }}</app-menu-item>
|
||||
<app-menu-separator />
|
||||
<app-menu-item value="restore-cover" (selected)="onChangeCovers('regenerate')">{{ 'book.menu.restoreCover' | transloco }}</app-menu-item>
|
||||
<app-menu-item value="generate-cover" (selected)="onChangeCovers('generate')">{{ 'book.menu.generateCover' | transloco }}</app-menu-item>
|
||||
<app-menu-separator />
|
||||
<app-menu-checkbox
|
||||
value="lock-metadata"
|
||||
[(checked)]="metadataLocked"
|
||||
[disabled]="metadataLockPending()"
|
||||
(selected)="onMetadataLockChange($event)">
|
||||
{{ 'book.menu.lockMetadata' | transloco }}
|
||||
</app-menu-checkbox>
|
||||
</app-menu>
|
||||
@@ -0,0 +1,232 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {provideRouter} from '@angular/router';
|
||||
import {ConfirmationService} from '@openng/optimus-ui/api';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {signal, type WritableSignal} from '@angular/core';
|
||||
|
||||
import {createQueryClientHarness} from '../../../../core/testing/query-testing';
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {MetadataRefreshSubmissionService} from '../../../metadata/data/metadata-refresh-submission.service';
|
||||
import {BookBackgroundSubmissionService} from '../../data/book-background-submission.service';
|
||||
import {BookCommandService} from '../../data/book-command.service';
|
||||
import {BookShelfCommandService} from '../../data/book-shelf-command.service';
|
||||
import {ShelfDefinitionQueryService} from '../../data/shelf-definition-query.service';
|
||||
import {BookSummary} from '../../data/book-response.models';
|
||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {FileDownloadService} from '../../../../shared/service/file-download.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {BookMenuComponent} from './book-menu.component';
|
||||
|
||||
type Permissions = Record<string, boolean>;
|
||||
|
||||
const NO_PERMISSIONS: Permissions = {};
|
||||
const ALL_PERMISSIONS: Permissions = {
|
||||
canDownload: true,
|
||||
canEmailBook: true,
|
||||
canEditMetadata: true,
|
||||
canDeleteBook: true,
|
||||
canBulkResetGrimmoryReadProgress: true,
|
||||
canBulkResetKoReaderReadProgress: true,
|
||||
canMoveOrganizeFiles: true,
|
||||
};
|
||||
|
||||
function makeBook(overrides: Partial<BookSummary> = {}): BookSummary {
|
||||
return {
|
||||
id: 1,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: 1, title: 'The Warden', allMetadataLocked: false},
|
||||
primaryFile: {id: 10, bookId: 1, book: true, folderBased: false, bookType: 'EPUB'},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookMenuComponent row gating', () => {
|
||||
let fixture: ComponentFixture<BookMenuComponent>;
|
||||
let element: HTMLElement;
|
||||
let permissions: WritableSignal<Permissions>;
|
||||
let diskType: WritableSignal<string>;
|
||||
|
||||
beforeEach(() => {
|
||||
permissions = signal(NO_PERMISSIONS);
|
||||
diskType = signal('LOCAL');
|
||||
const harness = createQueryClientHarness();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookMenuComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
...harness.providers,
|
||||
provideRouter([{path: '**', children: []}]),
|
||||
{provide: UserService, useValue: {currentUser: () => ({id: 1, permissions: permissions()})}},
|
||||
{provide: ShelfDefinitionQueryService, useValue: {definitions: () => ({queryKey: ['shelves'], queryFn: () => []})}},
|
||||
{provide: MetadataRefreshSubmissionService, useValue: {refreshMetadata: () => ({mutationFn: () => Promise.resolve()})}},
|
||||
{provide: BookBackgroundSubmissionService, useValue: {
|
||||
changeCovers: () => ({mutationFn: () => Promise.resolve()}),
|
||||
quickSend: () => ({mutationFn: () => Promise.resolve()}),
|
||||
}},
|
||||
{provide: BookCommandService, useValue: {
|
||||
setReadStatus: () => ({mutationFn: () => Promise.resolve([])}),
|
||||
deleteBooks: () => ({mutationFn: () => Promise.resolve({removedBookIds: []})}),
|
||||
deleteAdditionalFile: () => ({mutationFn: () => Promise.resolve({bookId: 1, fileId: 10})}),
|
||||
setAllMetadataLocks: () => ({mutationFn: () => Promise.reject(new Error('failed'))}),
|
||||
resetProgress: () => ({mutationFn: () => Promise.resolve([])}),
|
||||
}},
|
||||
{provide: BookShelfCommandService, useValue: {
|
||||
updateMembership: () => ({
|
||||
mutationKey: ['test', 'shelf-membership'],
|
||||
mutationFn: () => Promise.resolve({
|
||||
confirmedBookIds: [1],
|
||||
updatedBookShelves: [{bookId: 1, shelves: []}],
|
||||
}),
|
||||
}),
|
||||
}},
|
||||
{provide: BookDialogHelperService, useValue: {}},
|
||||
{provide: AppSettingsService, useValue: {appSettings: () => ({diskType: diskType()})}},
|
||||
{provide: FileDownloadService, useValue: {downloadFile: () => undefined}},
|
||||
{provide: BookNavigationService, useValue: {readBook: () => undefined}},
|
||||
{provide: ConfirmationService, useValue: {confirm: () => undefined}},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(BookMenuComponent);
|
||||
element = fixture.nativeElement as HTMLElement;
|
||||
fixture.componentRef.setInput('openInNewTab', true);
|
||||
showBook(makeBook());
|
||||
});
|
||||
|
||||
function showBook(book: BookSummary | null): void {
|
||||
(fixture.componentInstance as unknown as {bookSnapshot: {set(value: BookSummary | null): void}})
|
||||
.bookSnapshot.set(book);
|
||||
}
|
||||
|
||||
function rowLabels(): string[] {
|
||||
fixture.detectChanges();
|
||||
const root = element.querySelector('app-menu') as HTMLElement;
|
||||
return Array.from(root.querySelectorAll(':scope > app-menu-item, :scope > div > app-menu-item')).map(
|
||||
el => el.textContent?.trim() ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
function row(label: string): HTMLElement {
|
||||
fixture.detectChanges();
|
||||
const root = element.querySelector('app-menu') as HTMLElement;
|
||||
return Array.from(root.querySelectorAll('app-menu-item'))
|
||||
.find(el => el.textContent?.trim() === label) as HTMLElement;
|
||||
}
|
||||
|
||||
function hasSubmenu(label: string): boolean {
|
||||
return row(label).getAttribute('aria-haspopup') === 'true';
|
||||
}
|
||||
|
||||
function submenuLabels(label: string): string[] {
|
||||
fixture.detectChanges();
|
||||
const panel = element.querySelector(`app-menu[aria-label="${label}"]`) as HTMLElement;
|
||||
return Array.from(panel.querySelectorAll('app-menu-item')).map(el => el.textContent?.trim() ?? '');
|
||||
}
|
||||
|
||||
it('gates each row on permissions', () => {
|
||||
expect(rowLabels()).toEqual(['Read Book', 'Open Details in New Tab', 'Add to Shelf', 'Mark as']);
|
||||
|
||||
permissions.set(ALL_PERMISSIONS);
|
||||
expect(rowLabels()).toEqual([
|
||||
'Read Book',
|
||||
'Open Details in New Tab',
|
||||
'Add to Shelf',
|
||||
'Mark as',
|
||||
'Send',
|
||||
'Download',
|
||||
'Metadata',
|
||||
'More',
|
||||
'Delete',
|
||||
]);
|
||||
|
||||
permissions.set({...ALL_PERMISSIONS, canBulkResetGrimmoryReadProgress: false, canBulkResetKoReaderReadProgress: false, canMoveOrganizeFiles: false});
|
||||
fixture.componentRef.setInput('openInNewTab', false);
|
||||
expect(rowLabels()).toEqual(['Read Book', 'Add to Shelf', 'Mark as', 'Send', 'Download', 'Metadata', 'Delete']);
|
||||
});
|
||||
|
||||
it('drops Send and Download without a digital file, keeping them for any format', () => {
|
||||
permissions.set(ALL_PERMISSIONS);
|
||||
|
||||
showBook(makeBook({primaryFile: undefined}));
|
||||
expect(rowLabels()).toEqual(['Open Details in New Tab', 'Add to Shelf', 'Mark as', 'Metadata', 'More', 'Delete']);
|
||||
|
||||
showBook(makeBook({
|
||||
primaryFile: undefined,
|
||||
alternativeFormats: [{id: 11, bookId: 1, book: true, folderBased: false, bookType: 'AUDIOBOOK'}],
|
||||
}));
|
||||
expect(rowLabels()).toEqual([
|
||||
'Open Details in New Tab',
|
||||
'Add to Shelf',
|
||||
'Mark as',
|
||||
'Send',
|
||||
'Download',
|
||||
'Metadata',
|
||||
'More',
|
||||
'Delete',
|
||||
]);
|
||||
expect(submenuLabels('Send')).toEqual(['Custom Send']);
|
||||
|
||||
showBook(null);
|
||||
expect(rowLabels()).toEqual(['Add to Shelf', 'Mark as', 'Metadata', 'More', 'Delete']);
|
||||
});
|
||||
|
||||
it('hides Organize File on a non-local disk', () => {
|
||||
permissions.set(ALL_PERMISSIONS);
|
||||
expect(submenuLabels('More')).toContain('Organize File');
|
||||
|
||||
diskType.set('REMOTE');
|
||||
expect(submenuLabels('More')).not.toContain('Organize File');
|
||||
});
|
||||
|
||||
it('keeps confirmed shelf state when the book leaves the current result page', async () => {
|
||||
showBook(makeBook({
|
||||
shelves: [{id: 7, name: 'Reading List', publicShelf: false, bookCount: 1}],
|
||||
}));
|
||||
fixture.componentRef.setInput('books', []);
|
||||
|
||||
(fixture.componentInstance as unknown as {
|
||||
onToggleShelf(shelfId: number, checked: boolean): void;
|
||||
}).onToggleShelf(7, false);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const book = (fixture.componentInstance as unknown as {book(): BookSummary | null}).book();
|
||||
expect(book?.shelves).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('restores the confirmed metadata-lock state after a failed command', async () => {
|
||||
const component = fixture.componentInstance as unknown as {
|
||||
metadataLocked: WritableSignal<boolean>;
|
||||
onMetadataLockChange(locked: boolean): void;
|
||||
};
|
||||
component.metadataLocked.set(true);
|
||||
component.onMetadataLockChange(true);
|
||||
|
||||
await vi.waitFor(() => expect(component.metadataLocked()).toBe(false));
|
||||
});
|
||||
|
||||
it('opens a file submenu only when the book has more than its primary file', () => {
|
||||
permissions.set(ALL_PERMISSIONS);
|
||||
|
||||
expect(hasSubmenu('Download')).toBe(false);
|
||||
expect(hasSubmenu('Delete')).toBe(false);
|
||||
|
||||
showBook(makeBook({
|
||||
primaryFile: {id: 10, bookId: 1, book: true, folderBased: false, fileName: 'warden.epub', fileSizeKb: 2048},
|
||||
alternativeFormats: [
|
||||
{id: 11, bookId: 1, book: true, folderBased: false, fileName: 'warden.pdf', fileSizeKb: 30720},
|
||||
],
|
||||
supplementaryFiles: [
|
||||
{id: 12, bookId: 1, book: false, folderBased: false, fileName: 'warden.opf'},
|
||||
],
|
||||
}));
|
||||
|
||||
expect(hasSubmenu('Download')).toBe(true);
|
||||
expect(hasSubmenu('Delete')).toBe(true);
|
||||
expect(submenuLabels('Download')).toEqual(['warden.epub (2.00 MB)', 'warden.pdf (30.0 MB)', 'warden.opf']);
|
||||
expect(submenuLabels('Delete')).toEqual(['Book & all files', 'warden.pdf (30.0 MB)', 'warden.opf']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,428 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
linkedSignal,
|
||||
output,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import {NgTemplateOutlet} from '@angular/common';
|
||||
import {Router} from '@angular/router';
|
||||
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {ConfirmationService} from '@openng/optimus-ui/api';
|
||||
import {
|
||||
LucideBookOpen,
|
||||
LucidePlay,
|
||||
LucideSquareArrowOutUpRight,
|
||||
type LucideIconData,
|
||||
} from '@lucide/angular';
|
||||
import {injectMutation, injectQuery} from '@tanstack/angular-query-experimental';
|
||||
import {API_CONFIG} from '../../../../core/config/api-config';
|
||||
|
||||
import {AppMenuComponent, type ContextMenuRequest} from '../../../../shared/ui/menu/app-menu.component';
|
||||
import {AppMenuCheckboxComponent} from '../../../../shared/ui/menu/app-menu-checkbox.component';
|
||||
import {AppMenuItemComponent} from '../../../../shared/ui/menu/app-menu-item.component';
|
||||
import {AppMenuRadioGroupComponent} from '../../../../shared/ui/menu/app-menu-radio-group.component';
|
||||
import {AppMenuRadioComponent} from '../../../../shared/ui/menu/app-menu-radio.component';
|
||||
import {AppMenuSeparatorComponent} from '../../../../shared/ui/menu/app-menu-separator.component';
|
||||
import {
|
||||
ShelfMembershipMenuComponent,
|
||||
type ShelfMembershipItem,
|
||||
} from '../../../../shared/components/shelf-menu/shelf-membership-menu.component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {MetadataRefreshSubmissionService} from '../../../metadata/data/metadata-refresh-submission.service';
|
||||
import {BookBackgroundSubmissionService} from '../../data/book-background-submission.service';
|
||||
import {BookCommandService} from '../../data/book-command.service';
|
||||
import {BookShelfCommandService} from '../../data/book-shelf-command.service';
|
||||
import {type UpdateBookShelfMembershipResult} from '../../data/book-shelf-command.models';
|
||||
import {
|
||||
injectPendingBookShelfMembership,
|
||||
overlayShelfIds,
|
||||
} from '../../data/book-command-pending-state';
|
||||
import {type BookProgressSource} from '../../data/book-command.models';
|
||||
import {
|
||||
bookActionPermissions,
|
||||
bookProgressPercentage,
|
||||
bookReadAction,
|
||||
type BookReadAction,
|
||||
} from '../../data/book-actions';
|
||||
import {
|
||||
BOOK_READ_STATUS_LABEL_KEYS,
|
||||
BOOK_READ_STATUS_TARGETS,
|
||||
CLEAR_BOOK_READ_STATUS,
|
||||
CLEAR_BOOK_READ_STATUS_LABEL_KEY,
|
||||
type BookReadStatusTarget,
|
||||
} from '../book-read-status-options';
|
||||
import {
|
||||
type BookFileResponse,
|
||||
type BookSummary,
|
||||
type KnownBookReadStatus,
|
||||
} from '../../data/book-response.models';
|
||||
import {ShelfDefinitionQueryService} from '../../data/shelf-definition-query.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {legacyBookCachePatches, withLegacyBookCache} from '../../service/book-command-legacy-adapter';
|
||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||
import {FileDownloadService} from '../../../../shared/service/file-download.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {
|
||||
bookFileLabelParts,
|
||||
type BookFileLabelParts,
|
||||
} from './book-menu-file-label';
|
||||
|
||||
const LARGE_EMAIL_FILE_KB = 25 * 1024;
|
||||
const BOOKS_API_URL = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
const BOOK_MENU_READ_ACTION_LABEL_KEYS: Readonly<Record<BookReadAction, string>> = {
|
||||
read: 'book.readAction.read.long',
|
||||
continueReading: 'book.readAction.continueReading.long',
|
||||
play: 'book.readAction.play.long',
|
||||
continueListening: 'book.readAction.continueListening.long',
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-menu',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: {class: 'contents'},
|
||||
imports: [
|
||||
NgTemplateOutlet,
|
||||
TranslocoPipe,
|
||||
AppMenuComponent,
|
||||
AppMenuCheckboxComponent,
|
||||
AppMenuItemComponent,
|
||||
AppMenuRadioGroupComponent,
|
||||
AppMenuRadioComponent,
|
||||
AppMenuSeparatorComponent,
|
||||
ShelfMembershipMenuComponent,
|
||||
],
|
||||
templateUrl: './book-menu.component.html',
|
||||
})
|
||||
export class BookMenuComponent {
|
||||
readonly books = input<readonly BookSummary[]>([]);
|
||||
readonly openInNewTab = input(false, {transform: booleanAttribute});
|
||||
|
||||
readonly deleted = output<readonly number[]>();
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
private readonly fileDownload = inject(FileDownloadService);
|
||||
private readonly bookNavigation = inject(BookNavigationService);
|
||||
private readonly dialogHelper = inject(BookDialogHelperService);
|
||||
private readonly metadataRefresh = inject(MetadataRefreshSubmissionService);
|
||||
private readonly backgroundSubmission = inject(BookBackgroundSubmissionService);
|
||||
private readonly bookCommands = inject(BookCommandService);
|
||||
private readonly shelfCommands = inject(BookShelfCommandService);
|
||||
private readonly shelfDefinitionQuery = inject(ShelfDefinitionQueryService);
|
||||
private readonly confirmationService = inject(ConfirmationService);
|
||||
private readonly transloco = inject(TranslocoService);
|
||||
private readonly router = inject(Router);
|
||||
|
||||
private readonly rootMenu = viewChild.required(AppMenuComponent);
|
||||
private readonly bookSnapshot = signal<BookSummary | null>(null);
|
||||
private readonly fileSnapshot = signal<BookFileResponse | undefined>(undefined);
|
||||
private readonly openMenuBookId = signal<number | null>(null);
|
||||
readonly openBookId = this.openMenuBookId.asReadonly();
|
||||
|
||||
private readonly shelfDefinitionsQuery = injectQuery(() => this.shelfDefinitionQuery.definitions());
|
||||
private readonly pendingShelfMembership = injectPendingBookShelfMembership();
|
||||
|
||||
private readonly shelfMembershipMutation = injectMutation(() => {
|
||||
const options = withLegacyBookCache(
|
||||
this.shelfCommands.updateMembership(), legacyBookCachePatches.shelfMembership);
|
||||
return {
|
||||
...options,
|
||||
onSuccess: async (data, variables, onMutateResult, context) => {
|
||||
await options.onSuccess?.(data, variables, onMutateResult, context);
|
||||
this.updateShelfSnapshot(data);
|
||||
},
|
||||
} satisfies typeof options;
|
||||
});
|
||||
private readonly readStatusMutation = injectMutation(() => withLegacyBookCache(
|
||||
this.bookCommands.setReadStatus(), legacyBookCachePatches.readStatus));
|
||||
private readonly refreshMetadataMutation = injectMutation(() => this.metadataRefresh.refreshMetadata());
|
||||
private readonly deleteBooksMutation = injectMutation(() => {
|
||||
const options = withLegacyBookCache(
|
||||
this.bookCommands.deleteBooks(), legacyBookCachePatches.deleteBooks);
|
||||
return {
|
||||
...options,
|
||||
onSuccess: async (data, variables, onMutateResult, context) => {
|
||||
await options.onSuccess?.(data, variables, onMutateResult, context);
|
||||
this.deleted.emit(data.removedBookIds);
|
||||
},
|
||||
} satisfies typeof options;
|
||||
});
|
||||
private readonly deleteAdditionalFileMutation = injectMutation(() => withLegacyBookCache(
|
||||
this.bookCommands.deleteAdditionalFile(), legacyBookCachePatches.deleteAdditionalFile));
|
||||
private readonly quickSendMutation = injectMutation(() => this.backgroundSubmission.quickSend());
|
||||
private readonly metadataLocksMutation = injectMutation(() => {
|
||||
const options = withLegacyBookCache(
|
||||
this.bookCommands.setAllMetadataLocks(), legacyBookCachePatches.metadataAllLocks);
|
||||
return {
|
||||
...options,
|
||||
onError: async (error, variables, onMutateResult, context) => {
|
||||
await options.onError?.(error, variables, onMutateResult, context);
|
||||
this.metadataLocked.set(this.book()?.metadata?.allMetadataLocked ?? false);
|
||||
},
|
||||
} satisfies typeof options;
|
||||
});
|
||||
private readonly resetProgressMutation = injectMutation(() => withLegacyBookCache(
|
||||
this.bookCommands.resetProgress(), legacyBookCachePatches.resetProgress));
|
||||
private readonly changeCoversMutation = injectMutation(() => this.backgroundSubmission.changeCovers());
|
||||
|
||||
protected readonly readStatusTargets = BOOK_READ_STATUS_TARGETS;
|
||||
protected readonly clearReadStatus = CLEAR_BOOK_READ_STATUS;
|
||||
protected readonly clearReadStatusLabelKey = CLEAR_BOOK_READ_STATUS_LABEL_KEY;
|
||||
|
||||
protected readonly book = computed<BookSummary | null>(() => {
|
||||
const snapshot = this.bookSnapshot();
|
||||
if (!snapshot) {
|
||||
return null;
|
||||
}
|
||||
return this.books().find(book => book.id === snapshot.id) ?? snapshot;
|
||||
});
|
||||
protected readonly actionPermissions = computed(() =>
|
||||
bookActionPermissions(this.userService.currentUser()?.permissions));
|
||||
protected readonly shelves = computed<ShelfMembershipItem[]>(() => {
|
||||
const book = this.book();
|
||||
if (!book) {
|
||||
return [];
|
||||
}
|
||||
const onShelfIds = overlayShelfIds(book, this.pendingShelfMembership().get(book.id));
|
||||
const currentUserId = this.userService.currentUser()?.id;
|
||||
return (this.shelfDefinitionsQuery.data() ?? [])
|
||||
.filter(shelf => shelf.userId === currentUserId)
|
||||
.map(shelf => ({id: shelf.id, name: shelf.name, checked: onShelfIds.has(shelf.id)}));
|
||||
});
|
||||
private readonly shownFile = computed(() => this.fileSnapshot() ?? this.book()?.primaryFile);
|
||||
protected readonly readable = computed(() => this.shownFile() != null);
|
||||
private readonly readAction = computed(() => {
|
||||
const book = this.book();
|
||||
return book ? bookReadAction(book, this.shownFile()) : null;
|
||||
});
|
||||
protected readonly readLabelKey = computed(() => {
|
||||
const action = this.readAction();
|
||||
return action ? BOOK_MENU_READ_ACTION_LABEL_KEYS[action] : null;
|
||||
});
|
||||
protected readonly readProgress = computed(() => {
|
||||
const book = this.book();
|
||||
const action = this.readAction();
|
||||
if (!book || (action !== 'continueReading' && action !== 'continueListening')) {
|
||||
return '';
|
||||
}
|
||||
return `${Math.max(1, Math.round(bookProgressPercentage(book, this.shownFile()) ?? 0))}%`;
|
||||
});
|
||||
protected readonly readIcon = computed<LucideIconData | undefined>(() => {
|
||||
switch (this.readAction()) {
|
||||
case 'read':
|
||||
return LucideBookOpen.icon;
|
||||
case 'play':
|
||||
return LucidePlay.icon;
|
||||
case 'continueReading':
|
||||
case 'continueListening':
|
||||
case null:
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
protected readonly newTabIcon: LucideIconData = LucideSquareArrowOutUpRight.icon;
|
||||
protected readonly digital = computed(() => {
|
||||
const book = this.book();
|
||||
return book != null
|
||||
&& (book.primaryFile != null || (book.alternativeFormats ?? []).length > 0);
|
||||
});
|
||||
protected readonly quickSendAvailable = computed(() => this.book()?.primaryFile != null);
|
||||
protected readonly additionalFiles = computed(() => {
|
||||
const book = this.book();
|
||||
return book
|
||||
? [...(book.alternativeFormats ?? []), ...(book.supplementaryFiles ?? [])]
|
||||
: [];
|
||||
});
|
||||
protected readonly canOrganizeFile = computed(() =>
|
||||
this.actionPermissions().canOrganizeFiles
|
||||
&& this.appSettingsService.appSettings()?.diskType === 'LOCAL');
|
||||
protected readonly hasMoreActions = computed(() => {
|
||||
const permissions = this.actionPermissions();
|
||||
return this.canOrganizeFile()
|
||||
|| permissions.canResetGrimmoryProgress
|
||||
|| permissions.canResetKoreaderProgress;
|
||||
});
|
||||
protected readonly metadataLocked = linkedSignal(
|
||||
() => this.book()?.metadata?.allMetadataLocked ?? false,
|
||||
);
|
||||
protected readonly metadataLockPending = computed(() => this.metadataLocksMutation.isPending());
|
||||
|
||||
openFor(book: BookSummary, request: ContextMenuRequest, file?: BookFileResponse): void {
|
||||
if (!request.contextmenu && this.openMenuBookId() === book.id) {
|
||||
this.rootMenu().close();
|
||||
return;
|
||||
}
|
||||
this.bookSnapshot.set(book);
|
||||
this.fileSnapshot.set(file);
|
||||
this.openMenuBookId.set(book.id);
|
||||
this.rootMenu().openFrom(request);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.rootMenu().close();
|
||||
}
|
||||
|
||||
protected statusLabelKey(status: BookReadStatusTarget): string {
|
||||
return BOOK_READ_STATUS_LABEL_KEYS[status];
|
||||
}
|
||||
|
||||
protected fileLabelParts(file: BookFileResponse): BookFileLabelParts {
|
||||
return bookFileLabelParts(file);
|
||||
}
|
||||
|
||||
protected clearOpenBook(): void {
|
||||
this.openMenuBookId.set(null);
|
||||
}
|
||||
|
||||
protected onRead(): void {
|
||||
this.bookNavigation.readBook(this.book()!, this.shownFile());
|
||||
}
|
||||
|
||||
protected onToggleShelf(shelfId: number, checked: boolean): void {
|
||||
this.shelfMembershipMutation.mutate({
|
||||
bookIds: [this.book()!.id],
|
||||
assignShelfIds: checked ? [shelfId] : [],
|
||||
unassignShelfIds: checked ? [] : [shelfId],
|
||||
});
|
||||
}
|
||||
|
||||
protected onRemoveFromAllShelves(): void {
|
||||
const shelfIds = this.shelves().filter(shelf => shelf.checked).map(shelf => shelf.id);
|
||||
if (shelfIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
this.shelfMembershipMutation.mutate({
|
||||
bookIds: [this.book()!.id],
|
||||
assignShelfIds: [],
|
||||
unassignShelfIds: shelfIds,
|
||||
});
|
||||
}
|
||||
|
||||
protected onCreateShelf(): void {
|
||||
void this.dialogHelper.openShelfCreatorDialog();
|
||||
}
|
||||
|
||||
protected onSetReadStatus(status: KnownBookReadStatus): void {
|
||||
this.readStatusMutation.mutate({bookIds: [this.book()!.id], status});
|
||||
}
|
||||
|
||||
protected onResetProgress(source: BookProgressSource): void {
|
||||
this.resetProgressMutation.mutate({bookIds: [this.book()!.id], source});
|
||||
}
|
||||
|
||||
protected onOrganizeFile(): void {
|
||||
void this.dialogHelper.openFileMoverDialog(new Set([this.book()!.id]));
|
||||
}
|
||||
|
||||
protected onSearchMetadata(): void {
|
||||
this.router.navigate(['/book', this.book()!.id], {queryParams: {tab: 'match'}});
|
||||
}
|
||||
|
||||
protected onFetchMetadata(): void {
|
||||
this.refreshMetadataMutation.mutate({bookIds: [this.book()!.id]});
|
||||
}
|
||||
|
||||
protected onFetchMetadataWithOptions(): void {
|
||||
void this.dialogHelper.openMetadataRefreshDialog(new Set([this.book()!.id]));
|
||||
}
|
||||
|
||||
protected onEditMetadata(): void {
|
||||
this.router.navigate(['/book', this.book()!.id], {queryParams: {tab: 'edit'}});
|
||||
}
|
||||
|
||||
protected onChangeCovers(kind: 'regenerate' | 'generate'): void {
|
||||
this.changeCoversMutation.mutate({kind, bookIds: [this.book()!.id]});
|
||||
}
|
||||
|
||||
protected onMetadataLockChange(locked: boolean): void {
|
||||
this.metadataLocksMutation.mutate({bookIds: [this.book()!.id], locked});
|
||||
}
|
||||
|
||||
protected onDownload(): void {
|
||||
const book = this.book()!;
|
||||
this.fileDownload.downloadFile(
|
||||
`${BOOKS_API_URL}/${book.id}/download`,
|
||||
book.primaryFile?.fileName ?? 'book',
|
||||
);
|
||||
}
|
||||
|
||||
protected onDownloadFile(file: BookFileResponse): void {
|
||||
this.fileDownload.downloadFile(
|
||||
`${BOOKS_API_URL}/${this.book()!.id}/files/${file.id}/download`,
|
||||
file.fileName ?? 'file',
|
||||
);
|
||||
}
|
||||
|
||||
protected onQuickSend(): void {
|
||||
const book = this.book()!;
|
||||
if ((book.primaryFile?.fileSizeKb ?? 0) <= LARGE_EMAIL_FILE_KB) {
|
||||
this.quickSend(book.id);
|
||||
return;
|
||||
}
|
||||
this.confirmationService.confirm({
|
||||
message: this.transloco.translate('book.menu.confirm.largeFileMessage'),
|
||||
header: this.transloco.translate('book.menu.confirm.largeFileHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.transloco.translate('book.menu.confirm.sendAnyway'),
|
||||
rejectLabel: this.transloco.translate('common.cancel'),
|
||||
acceptButtonProps: {severity: 'warn'},
|
||||
rejectButtonProps: {severity: 'secondary'},
|
||||
accept: () => this.quickSend(book.id),
|
||||
});
|
||||
}
|
||||
|
||||
protected onCustomSend(): void {
|
||||
void this.dialogHelper.openCustomSendDialog(this.book()!);
|
||||
}
|
||||
|
||||
protected onDeleteRequested(): void {
|
||||
const book = this.book()!;
|
||||
this.confirmationService.confirm({
|
||||
message: this.transloco.translate('book.menu.confirm.deleteBookMessage', {title: book.metadata?.title}),
|
||||
header: this.transloco.translate('book.menu.confirm.deleteBookHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptLabel: this.transloco.translate('common.delete'),
|
||||
rejectLabel: this.transloco.translate('common.cancel'),
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
rejectButtonStyleClass: 'p-button-outlined',
|
||||
accept: () => this.deleteBooksMutation.mutate({bookIds: [book.id]}),
|
||||
});
|
||||
}
|
||||
|
||||
protected onDeleteFileRequested(file: BookFileResponse): void {
|
||||
const book = this.book()!;
|
||||
const fileName = file.fileName ?? '';
|
||||
this.confirmationService.confirm({
|
||||
message: this.transloco.translate('book.menu.confirm.deleteFileMessage', {fileName}),
|
||||
header: this.transloco.translate('book.menu.confirm.deleteFileHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptLabel: this.transloco.translate('common.delete'),
|
||||
rejectLabel: this.transloco.translate('common.cancel'),
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
rejectButtonStyleClass: 'p-button-outlined',
|
||||
accept: () => this.deleteAdditionalFileMutation.mutate({bookId: book.id, fileId: file.id}),
|
||||
});
|
||||
}
|
||||
|
||||
private quickSend(bookId: number): void {
|
||||
this.quickSendMutation.mutate({bookId});
|
||||
}
|
||||
|
||||
private updateShelfSnapshot(result: UpdateBookShelfMembershipResult): void {
|
||||
const snapshot = this.bookSnapshot();
|
||||
const update = result.updatedBookShelves.find(item => item.bookId === snapshot?.id);
|
||||
if (snapshot && update) {
|
||||
this.bookSnapshot.set({...snapshot, shelves: [...update.shelves]});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {
|
||||
BOOK_READ_STATUSES,
|
||||
type KnownBookReadStatus,
|
||||
} from '../data/book-response.models';
|
||||
|
||||
export type BookReadStatusTarget = Exclude<KnownBookReadStatus, 'UNSET'>;
|
||||
|
||||
export const CLEAR_BOOK_READ_STATUS = 'UNSET' satisfies KnownBookReadStatus;
|
||||
export const CLEAR_BOOK_READ_STATUS_LABEL_KEY = 'book.filter.readStatus.unset';
|
||||
|
||||
export const BOOK_READ_STATUS_LABEL_KEYS: Readonly<Record<BookReadStatusTarget, string>> = {
|
||||
UNREAD: 'book.filter.readStatus.unread',
|
||||
READING: 'book.filter.readStatus.reading',
|
||||
RE_READING: 'book.filter.readStatus.reReading',
|
||||
PARTIALLY_READ: 'book.filter.readStatus.partiallyRead',
|
||||
PAUSED: 'book.filter.readStatus.paused',
|
||||
READ: 'book.filter.readStatus.read',
|
||||
WONT_READ: 'book.filter.readStatus.wontRead',
|
||||
ABANDONED: 'book.filter.readStatus.abandoned',
|
||||
};
|
||||
|
||||
export const BOOK_READ_STATUS_TARGETS: readonly BookReadStatusTarget[] =
|
||||
BOOK_READ_STATUSES.filter(status => status !== 'UNSET');
|
||||
@@ -0,0 +1,48 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {
|
||||
bookCardHeightForWidth,
|
||||
BOOK_CARD_META_PADDING_TOP,
|
||||
} from './book-card.layout';
|
||||
import {BookCardSkeletonComponent} from './book-card-skeleton.component';
|
||||
|
||||
describe('BookCardSkeletonComponent', () => {
|
||||
let fixture: ComponentFixture<BookCardSkeletonComponent>;
|
||||
let host: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({imports: [BookCardSkeletonComponent]});
|
||||
fixture = TestBed.createComponent(BookCardSkeletonComponent);
|
||||
host = fixture.nativeElement as HTMLElement;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
function rowHeights(): number[] {
|
||||
return Array.from(host.querySelectorAll<HTMLElement>('[data-testid="skeleton-row"]'))
|
||||
.map(row => Number.parseFloat(row.style.height));
|
||||
}
|
||||
|
||||
function metaPaddingTop(): number {
|
||||
const meta = host.querySelector<HTMLElement>('[data-testid="skeleton-meta"]');
|
||||
return Number.parseFloat(meta!.style.paddingTop);
|
||||
}
|
||||
|
||||
function setMetaLines(metaLines: 2 | 3): void {
|
||||
fixture.componentRef.setInput('metaLines', metaLines);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
it('adds up to the height the grid estimates, for both meta-line counts', () => {
|
||||
const width = 144;
|
||||
fixture.componentRef.setInput('squareCovers', true);
|
||||
|
||||
for (const metaLines of [2, 3] as const) {
|
||||
setMetaLines(metaLines);
|
||||
const rendered = width + metaPaddingTop() + rowHeights().reduce((sum, row) => sum + row, 0);
|
||||
|
||||
expect(metaPaddingTop()).toBe(BOOK_CARD_META_PADDING_TOP);
|
||||
expect(rendered).toBe(bookCardHeightForWidth(width, {square: true, metaLines}));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import {booleanAttribute, ChangeDetectionStrategy, Component, computed, input} from '@angular/core';
|
||||
|
||||
import {
|
||||
bookCardAspectClass,
|
||||
BOOK_CARD_META_ACCESSORY_HEIGHT,
|
||||
BOOK_CARD_META_AUTHOR_HEIGHT,
|
||||
BOOK_CARD_META_PADDING_TOP,
|
||||
BOOK_CARD_META_TITLE_HEIGHT,
|
||||
BOOK_CARD_RADIUS_CLASS,
|
||||
} from './book-card.layout';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card-skeleton',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: {class: 'block'},
|
||||
template: `
|
||||
<div class="w-full min-w-0" aria-hidden="true">
|
||||
<div [class]="coverClass()" data-testid="skeleton-cover"></div>
|
||||
<div class="px-0.5" [style.paddingTop.px]="metaPaddingTop" data-testid="skeleton-meta">
|
||||
<div class="flex items-center" [style.height.px]="titleHeight" data-testid="skeleton-row">
|
||||
<div [class]="barClass + ' h-[11px] w-3/4'"></div>
|
||||
</div>
|
||||
<div class="flex items-center" [style.height.px]="authorHeight" data-testid="skeleton-row">
|
||||
<div [class]="barClass + ' h-[9px] w-1/2'"></div>
|
||||
</div>
|
||||
@if (metaLines() === 3) {
|
||||
<div class="flex items-center" [style.height.px]="accessoryHeight" data-testid="skeleton-row">
|
||||
<div [class]="barClass + ' h-[9px] w-1/3'"></div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class BookCardSkeletonComponent {
|
||||
readonly squareCovers = input(false, {transform: booleanAttribute});
|
||||
readonly metaLines = input<2 | 3>(2);
|
||||
|
||||
protected readonly metaPaddingTop = BOOK_CARD_META_PADDING_TOP;
|
||||
protected readonly titleHeight = BOOK_CARD_META_TITLE_HEIGHT;
|
||||
protected readonly authorHeight = BOOK_CARD_META_AUTHOR_HEIGHT;
|
||||
protected readonly accessoryHeight = BOOK_CARD_META_ACCESSORY_HEIGHT;
|
||||
|
||||
protected readonly barClass = 'rounded bg-skeleton-base animate-skeleton motion-reduce:animate-none';
|
||||
protected readonly coverClass = computed(() =>
|
||||
`w-full ${BOOK_CARD_RADIUS_CLASS} bg-skeleton-base animate-skeleton motion-reduce:animate-none ${
|
||||
bookCardAspectClass(this.squareCovers())
|
||||
}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<div
|
||||
[class]="rootClass()"
|
||||
[attr.data-active]="menuPinned() ? 'true' : null"
|
||||
(contextmenu)="requestContextMenu($event)"
|
||||
(pointerdown)="startLongPress($event)"
|
||||
(pointerup)="endLongPress()"
|
||||
(pointercancel)="endLongPress()"
|
||||
>
|
||||
<div [class]="slotClass()" data-testid="slot">
|
||||
<div [class]="coverClass()" data-testid="cover">
|
||||
<app-cover
|
||||
class="absolute inset-0 h-full w-full"
|
||||
[src]="coverSrc()"
|
||||
[title]="title()"
|
||||
[authors]="authors()"
|
||||
[fit]="coverFit()"
|
||||
[alt]="'book.card.aria.coverAlt' | transloco: {title: title()}"
|
||||
/>
|
||||
|
||||
@if (badgeVisible()) {
|
||||
<span [class]="badgeClass" data-testid="badge">#{{ seriesNumber() }}</span>
|
||||
}
|
||||
|
||||
@if (formatPillVisible() && formatLabel(); as format) {
|
||||
<span [class]="formatPillClass()" data-testid="format-pill">{{ format }}</span>
|
||||
}
|
||||
|
||||
@if (selectable()) {
|
||||
<app-card-selection
|
||||
[selected]="selected()"
|
||||
[selectionMode]="selectionActive()"
|
||||
[ariaLabel]="'book.selectBook' | transloco: {title: title()}"
|
||||
(selectionToggled)="toggleSelect.emit($event)"
|
||||
/>
|
||||
}
|
||||
|
||||
@if (showProgress() && progressPercentage() !== null) {
|
||||
<span
|
||||
class="absolute inset-x-0 bottom-0 z-20 h-1 bg-black/45"
|
||||
[appTooltip]="progressTooltip()"
|
||||
data-testid="progress"
|
||||
>
|
||||
<progress
|
||||
class="sr-only"
|
||||
[value]="progressPercentage()!"
|
||||
max="100"
|
||||
[attr.aria-label]="progressTooltip()"
|
||||
></progress>
|
||||
<i
|
||||
class="block h-full rounded-r-sm bg-primary"
|
||||
[style.width.%]="progressPercentage()"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
</span>
|
||||
}
|
||||
|
||||
@if (overlays() && !selectionActive()) {
|
||||
<div [class]="overlayClass" data-testid="overlay">
|
||||
@if (hasPrimaryFile()) {
|
||||
<button
|
||||
type="button"
|
||||
[class]="actionClass + ' relative h-7 min-w-0 flex-1 flex-wrap content-start overflow-hidden px-1.5'"
|
||||
[attr.aria-label]="actionText()"
|
||||
(click)="onAction($event)"
|
||||
>
|
||||
<span class="flex h-7 shrink-0 items-center"><svg [lucideIcon]="actionIcon()" class="size-3.5"></svg></span>
|
||||
<span class="flex h-7 shrink-0 items-center whitespace-nowrap" aria-hidden="true">{{ actionText() }}</span>
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
[class]="actionClass + ' size-7 flex-none'"
|
||||
aria-haspopup="menu"
|
||||
[attr.aria-expanded]="menuOpen()"
|
||||
[attr.aria-label]="'book.card.aria.bookMenu' | transloco: {title: title()}"
|
||||
(click)="onMenu($event)"
|
||||
>
|
||||
<svg lucideEllipsisVertical class="size-3.5"></svg>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (showMeta()) {
|
||||
<div class="px-0.5 pt-2" data-testid="meta">
|
||||
<div [class]="metaTitleClass" [attr.title]="title()">{{ title() }}</div>
|
||||
<div [class]="metaSecondaryClass + ' mt-px'">{{ authorsLabel() }}</div>
|
||||
@if (detailLine() !== null) {
|
||||
<div [class]="metaSecondaryClass">{{ detailLine() }}</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!selectionActive()) {
|
||||
<a
|
||||
[class]="linkClass"
|
||||
[attr.href]="detailHref()"
|
||||
[attr.aria-label]="title()"
|
||||
(click)="openDetails($event)"
|
||||
></a>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
[class]="linkClass"
|
||||
[attr.aria-pressed]="selected()"
|
||||
[attr.aria-label]="'book.selectBook' | transloco: {title: title()}"
|
||||
data-testid="select-overlay"
|
||||
(click)="onSelectOverlay($event)"
|
||||
></button>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,117 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {provideRouter, Router} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {BookSummary} from '../../data/book-response.models';
|
||||
import {BookCardComponent, bookCardCoverSrc} from './book-card.component';
|
||||
|
||||
function makeBook(overrides: Partial<BookSummary> = {}): BookSummary {
|
||||
return {
|
||||
id: 1,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'The Warden',
|
||||
authors: ['Anthony Trollope'],
|
||||
allMetadataLocked: false,
|
||||
},
|
||||
primaryFile: {id: 10, bookId: 1, book: true, folderBased: false, bookType: 'EPUB'},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function audiobookFile() {
|
||||
return {id: 10, bookId: 1, book: true, folderBased: false, bookType: 'AUDIOBOOK' as const};
|
||||
}
|
||||
|
||||
describe('BookCardComponent', () => {
|
||||
let fixture: ComponentFixture<BookCardComponent>;
|
||||
let host: HTMLElement;
|
||||
let router: Router;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookCardComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
provideRouter([{path: '**', children: []}]),
|
||||
{
|
||||
provide: UrlHelperService,
|
||||
useValue: {
|
||||
getThumbnailUrl: (id: number) => `/thumb/${id}`,
|
||||
getAudiobookThumbnailUrl: (id: number) => `/audio-thumb/${id}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(BookCardComponent);
|
||||
host = fixture.nativeElement as HTMLElement;
|
||||
router = TestBed.inject(Router);
|
||||
});
|
||||
|
||||
function progressWidth(book: BookSummary): string | undefined {
|
||||
fixture.componentRef.setInput('book', book);
|
||||
fixture.detectChanges();
|
||||
return host.querySelector<HTMLElement>('[data-testid="progress"] i')?.style.width;
|
||||
}
|
||||
|
||||
it('shows the progress of the file it is showing', () => {
|
||||
expect(progressWidth(makeBook({
|
||||
epubProgress: {cfi: null, href: null, contentSourceProgressPercent: null, percentage: 30, ttsPositionCfi: null},
|
||||
pdfProgress: {page: 1, percentage: 50},
|
||||
koreaderProgress: {percentage: 42},
|
||||
}))).toBe('30%');
|
||||
expect(progressWidth(makeBook({
|
||||
primaryFile: audiobookFile(),
|
||||
audiobookProgress: {positionMs: 1000, trackIndex: null, trackPositionMs: null, percentage: 82},
|
||||
}))).toBe('82%');
|
||||
expect(progressWidth(makeBook({koreaderProgress: {percentage: 42}, koboProgress: {percentage: 12}}))).toBe('42%');
|
||||
expect(progressWidth(makeBook({primaryFile: audiobookFile(), koreaderProgress: {percentage: 42}})))
|
||||
.toBeUndefined();
|
||||
expect(progressWidth(makeBook())).toBeUndefined();
|
||||
});
|
||||
|
||||
it('uses client-side navigation for an ordinary link click', () => {
|
||||
fixture.componentRef.setInput('book', makeBook());
|
||||
const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
const event = new MouseEvent('click', {button: 0, cancelable: true});
|
||||
|
||||
(fixture.componentInstance as unknown as {openDetails(event: MouseEvent): void}).openDetails(event);
|
||||
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(navigate).toHaveBeenCalledWith(['/book', 1]);
|
||||
});
|
||||
|
||||
it('swallows the click generated after a long press', () => {
|
||||
fixture.componentRef.setInput('book', makeBook());
|
||||
const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
const component = fixture.componentInstance as unknown as {
|
||||
longPressFired: boolean;
|
||||
openDetails(event: MouseEvent): void;
|
||||
};
|
||||
component.longPressFired = true;
|
||||
const event = new MouseEvent('click', {button: 0, cancelable: true});
|
||||
|
||||
component.openDetails(event);
|
||||
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookCardCoverSrc', () => {
|
||||
const urlHelper = {
|
||||
getThumbnailUrl: (id: number) => `/thumb/${id}`,
|
||||
getAudiobookThumbnailUrl: (id: number) => `/audio-thumb/${id}`,
|
||||
} as UrlHelperService;
|
||||
|
||||
it('picks the artwork for the file it is given', () => {
|
||||
const book = makeBook();
|
||||
expect(bookCardCoverSrc(book, book.primaryFile, urlHelper)).toBe('/thumb/1');
|
||||
expect(bookCardCoverSrc(book, audiobookFile(), urlHelper)).toBe('/audio-thumb/1');
|
||||
expect(bookCardCoverSrc(book, undefined, urlHelper)).toBe('/thumb/1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
import {
|
||||
booleanAttribute,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
DestroyRef,
|
||||
inject,
|
||||
input,
|
||||
output,
|
||||
} from '@angular/core';
|
||||
import {toSignal} from '@angular/core/rxjs-interop';
|
||||
import {LocationStrategy} from '@angular/common';
|
||||
import {Router} from '@angular/router';
|
||||
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {
|
||||
LucideArrowRight,
|
||||
LucideBookOpen,
|
||||
LucideDynamicIcon,
|
||||
LucideEllipsisVertical,
|
||||
LucidePlay,
|
||||
} from '@lucide/angular';
|
||||
|
||||
import {type BookFileResponse, BookSummary} from '../../data/book-response.models';
|
||||
import {
|
||||
bookGrimmoryProgress,
|
||||
bookProgressPercentage,
|
||||
bookReadAction,
|
||||
type BookReadAction,
|
||||
} from '../../data/book-actions';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
|
||||
import {AppTooltipDirective} from '../../../../shared/ui/tooltip/app-tooltip.directive';
|
||||
import {cn} from '../../../../shared/ui/cn';
|
||||
import {contextMenuRequest, type ContextMenuRequest} from '../../../../shared/ui/menu/app-menu.component';
|
||||
import {isContextMenuGesture, isPlainLeftClick} from '../../../../shared/util/pointer-gestures';
|
||||
import {CardSelectionComponent} from './card-selection.component';
|
||||
import {bookCardAspectClass, BOOK_CARD_RADIUS_CLASS} from './book-card.layout';
|
||||
|
||||
const LONG_PRESS_MS = 500;
|
||||
const LONG_PRESS_TOLERANCE_PX = 10;
|
||||
const BOOK_CARD_READ_ACTION_LABEL_KEYS: Readonly<Record<BookReadAction, string>> = {
|
||||
read: 'book.readAction.read.short',
|
||||
continueReading: 'book.readAction.continueReading.short',
|
||||
play: 'book.readAction.play.short',
|
||||
continueListening: 'book.readAction.continueListening.short',
|
||||
};
|
||||
|
||||
export function bookCardCoverSrc(
|
||||
book: BookSummary,
|
||||
file: BookFileResponse | undefined,
|
||||
urlHelper: UrlHelperService,
|
||||
): string | null {
|
||||
return file?.bookType === 'AUDIOBOOK'
|
||||
? urlHelper.getAudiobookThumbnailUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)
|
||||
: urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn);
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
TranslocoPipe,
|
||||
CoverComponent,
|
||||
AppTooltipDirective,
|
||||
CardSelectionComponent,
|
||||
LucideDynamicIcon,
|
||||
LucideEllipsisVertical,
|
||||
],
|
||||
host: {class: 'block'},
|
||||
templateUrl: './book-card.component.html',
|
||||
})
|
||||
export class BookCardComponent {
|
||||
readonly book = input.required<BookSummary>();
|
||||
readonly squareCovers = input(false, {transform: booleanAttribute});
|
||||
readonly showBadge = input(true, {transform: booleanAttribute});
|
||||
readonly showFormatPill = input(false, {transform: booleanAttribute});
|
||||
readonly showProgress = input(true, {transform: booleanAttribute});
|
||||
readonly showMeta = input(true, {transform: booleanAttribute});
|
||||
readonly overlays = input(true, {transform: booleanAttribute});
|
||||
readonly detailLine = input<string | null>(null);
|
||||
readonly selectable = input(false, {transform: booleanAttribute});
|
||||
readonly selected = input(false, {transform: booleanAttribute});
|
||||
readonly selectionActive = input(false, {transform: booleanAttribute});
|
||||
readonly detailMode = input<'link' | 'request'>('link');
|
||||
readonly menuOpen = input(false, {transform: booleanAttribute});
|
||||
readonly file = input<BookFileResponse | null>(null);
|
||||
|
||||
readonly toggleSelect = output<{shiftKey: boolean}>();
|
||||
readonly action = output<void>();
|
||||
readonly menuRequested = output<ContextMenuRequest>();
|
||||
readonly detailRequested = output<void>();
|
||||
|
||||
private readonly urlHelper = inject(UrlHelperService);
|
||||
private readonly transloco = inject(TranslocoService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly locationStrategy = inject(LocationStrategy);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly activeLang = toSignal(this.transloco.langChanges$, {
|
||||
initialValue: this.transloco.getActiveLang(),
|
||||
});
|
||||
|
||||
protected readonly title = computed(() => {
|
||||
const title = this.book().metadata?.title?.trim();
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
this.activeLang();
|
||||
return this.transloco.translate('book.card.book.unknownTitle');
|
||||
});
|
||||
protected readonly authors = computed(() => this.book().metadata?.authors ?? []);
|
||||
protected readonly authorsLabel = computed(() => this.authors().join(', '));
|
||||
protected readonly seriesNumber = computed(() => this.book().metadata?.seriesNumber ?? null);
|
||||
|
||||
protected readonly shownFile = computed(() => this.file() ?? this.book().primaryFile);
|
||||
protected readonly isAudiobook = computed(() => this.shownFile()?.bookType === 'AUDIOBOOK');
|
||||
protected readonly coverSquare = computed(() => this.isAudiobook() || this.squareCovers());
|
||||
protected readonly coverFit = computed<'cover' | 'contain'>(() => (this.coverSquare() ? 'contain' : 'cover'));
|
||||
protected readonly coverSrc = computed(() =>
|
||||
bookCardCoverSrc(this.book(), this.shownFile(), this.urlHelper));
|
||||
|
||||
private readonly grimmoryProgress = computed(() => bookGrimmoryProgress(this.book(), this.shownFile()));
|
||||
|
||||
protected readonly progressPercentage = computed(() =>
|
||||
bookProgressPercentage(this.book(), this.shownFile()));
|
||||
|
||||
protected readonly progressTooltip = computed(() => {
|
||||
const book = this.book();
|
||||
const grimmory = this.grimmoryProgress();
|
||||
const parts: string[] = [];
|
||||
if (grimmory !== null) {
|
||||
parts.push(`${grimmory}% (Grimmory)`);
|
||||
}
|
||||
if (!this.isAudiobook()) {
|
||||
if (book.koreaderProgress?.percentage != null) {
|
||||
parts.push(`${book.koreaderProgress.percentage}% (KOReader)`);
|
||||
}
|
||||
if (book.koboProgress?.percentage != null) {
|
||||
parts.push(`${book.koboProgress.percentage}% (Kobo)`);
|
||||
}
|
||||
}
|
||||
return parts.join(' | ');
|
||||
});
|
||||
|
||||
protected readonly formatLabel = computed(() => {
|
||||
const file = this.shownFile();
|
||||
if (!file) {
|
||||
this.activeLang();
|
||||
return this.transloco.translate('book.card.book.physical');
|
||||
}
|
||||
return file.extension?.toUpperCase() ?? null;
|
||||
});
|
||||
|
||||
protected readonly hasPrimaryFile = computed(() => this.shownFile() != null);
|
||||
|
||||
private readonly readAction = computed(() => bookReadAction(this.book(), this.shownFile()));
|
||||
protected readonly actionIcon = computed(() => {
|
||||
switch (this.readAction()) {
|
||||
case 'read':
|
||||
return LucideBookOpen.icon;
|
||||
case 'continueReading':
|
||||
return LucideArrowRight.icon;
|
||||
case 'play':
|
||||
case 'continueListening':
|
||||
return LucidePlay.icon;
|
||||
}
|
||||
});
|
||||
private readonly verbKey = computed(() => BOOK_CARD_READ_ACTION_LABEL_KEYS[this.readAction()]);
|
||||
protected readonly actionText = computed(() => {
|
||||
this.activeLang();
|
||||
return this.transloco.translate(this.verbKey());
|
||||
});
|
||||
|
||||
protected readonly detailLink = computed(() => ['/book', this.book().id]);
|
||||
protected readonly detailHref = computed(() =>
|
||||
this.locationStrategy.prepareExternalUrl(
|
||||
this.router.serializeUrl(this.router.createUrlTree(this.detailLink())),
|
||||
),
|
||||
);
|
||||
|
||||
private readonly checkboxTakesOver = computed(
|
||||
() => this.selectable() && (this.selected() || this.selectionActive()),
|
||||
);
|
||||
protected readonly menuPinned = computed(() => this.menuOpen() && !this.selectionActive());
|
||||
protected readonly badgeVisible = computed(
|
||||
() => this.showBadge() && this.seriesNumber() !== null,
|
||||
);
|
||||
|
||||
private pressTimer: number | null = null;
|
||||
private pressOrigin: {x: number; y: number} | null = null;
|
||||
private pressTarget: HTMLElement | null = null;
|
||||
private readonly onPressMove = (event: PointerEvent): void => this.cancelLongPressAfterMove(event);
|
||||
private longPressFired = false;
|
||||
|
||||
constructor() {
|
||||
this.destroyRef.onDestroy(() => this.cancelLongPress());
|
||||
}
|
||||
|
||||
protected readonly rootClass = computed(() =>
|
||||
cn(
|
||||
`group/card relative block min-w-0 cursor-pointer ${BOOK_CARD_RADIUS_CLASS}`,
|
||||
'pointer-coarse:select-none pointer-coarse:[-webkit-touch-callout:none]',
|
||||
!this.selectionActive() && this.overlays() && 'group/lift',
|
||||
this.menuPinned() && 'cover-lifted',
|
||||
),
|
||||
);
|
||||
protected readonly linkClass =
|
||||
'absolute inset-0 z-10 rounded-[inherit] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
|
||||
protected readonly slotClass = computed(() =>
|
||||
cn('flex flex-col justify-end', bookCardAspectClass(this.squareCovers())),
|
||||
);
|
||||
protected readonly coverClass = computed(() =>
|
||||
cn(
|
||||
`relative w-full overflow-hidden ${BOOK_CARD_RADIUS_CLASS} transition-[box-shadow,scale] duration-100 ease-out motion-reduce:transition-none`,
|
||||
'shadow-card group-hover/card:shadow-card-hover group-data-[active=true]/card:shadow-card-hover',
|
||||
bookCardAspectClass(this.coverSquare()),
|
||||
this.selected() && 'scale-[0.93] outline-2 outline-offset-2 outline-primary',
|
||||
),
|
||||
);
|
||||
protected readonly badgeClass =
|
||||
'absolute right-2 top-2 z-10 rounded-md bg-black/55 px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white';
|
||||
protected readonly formatPillVisible = computed(
|
||||
() => this.showFormatPill() && !this.checkboxTakesOver(),
|
||||
);
|
||||
protected readonly formatPillClass = computed(() =>
|
||||
cn(
|
||||
'absolute left-2 top-2 z-10 rounded-md bg-black/55 px-1.5 py-0.5 text-[10px] font-semibold text-white',
|
||||
this.selectable() &&
|
||||
'transition-opacity group-hover/card:opacity-0 group-has-[:focus-visible]/card:opacity-0 group-data-[active=true]/card:opacity-0 motion-reduce:transition-none',
|
||||
),
|
||||
);
|
||||
protected readonly overlayClass =
|
||||
'pointer-events-none absolute inset-x-0 bottom-0 z-20 flex translate-y-1 gap-1 p-1 opacity-0 transition-[opacity,translate] duration-150 group-hover/card:pointer-events-auto group-hover/card:translate-y-0 group-hover/card:opacity-100 group-has-[:focus-visible]/card:pointer-events-auto group-has-[:focus-visible]/card:translate-y-0 group-has-[:focus-visible]/card:opacity-100 pointer-fine:group-data-[active=true]/card:pointer-events-auto pointer-fine:group-data-[active=true]/card:translate-y-0 pointer-fine:group-data-[active=true]/card:opacity-100 motion-reduce:transition-none';
|
||||
protected readonly actionClass =
|
||||
'inline-flex items-center justify-center gap-1.5 rounded-md bg-black text-xs font-[550] text-white/90 ring-1 ring-inset ring-white/20 hover:text-white active:translate-y-px pointer-coarse:active:translate-y-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
|
||||
protected readonly metaTitleClass = 'min-h-[17px] truncate text-[13px]/[17px] font-[550] text-text';
|
||||
protected readonly metaSecondaryClass = 'min-h-[15px] truncate text-xs/[15px] text-text-secondary';
|
||||
|
||||
protected openDetails(event: MouseEvent): void {
|
||||
if (this.consumeLongPress()) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (isContextMenuGesture(event)) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (!isPlainLeftClick(event)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (this.detailMode() === 'request') {
|
||||
this.detailRequested.emit();
|
||||
} else {
|
||||
void this.router.navigate(this.detailLink());
|
||||
}
|
||||
}
|
||||
|
||||
protected onSelectOverlay(event: MouseEvent): void {
|
||||
if (isContextMenuGesture(event)) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
this.toggleSelect.emit({shiftKey: event.shiftKey});
|
||||
}
|
||||
|
||||
protected startLongPress(event: PointerEvent): void {
|
||||
this.cancelLongPress();
|
||||
this.longPressFired = false;
|
||||
if (event.pointerType === 'mouse' || !this.overlays() || this.selectionActive()) {
|
||||
return;
|
||||
}
|
||||
const request = contextMenuRequest(event);
|
||||
this.pressOrigin = {x: event.clientX, y: event.clientY};
|
||||
this.pressTarget = event.currentTarget as HTMLElement;
|
||||
this.pressTarget.addEventListener('pointermove', this.onPressMove, {passive: true});
|
||||
this.pressTimer = window.setTimeout(() => {
|
||||
this.pressTimer = null;
|
||||
this.longPressFired = true;
|
||||
this.menuRequested.emit(request);
|
||||
}, LONG_PRESS_MS);
|
||||
}
|
||||
|
||||
private cancelLongPressAfterMove(event: PointerEvent): void {
|
||||
const origin = this.pressOrigin;
|
||||
if (this.pressTimer === null || !origin) {
|
||||
return;
|
||||
}
|
||||
const moved = Math.hypot(event.clientX - origin.x, event.clientY - origin.y);
|
||||
if (moved > LONG_PRESS_TOLERANCE_PX) {
|
||||
this.cancelLongPress();
|
||||
}
|
||||
}
|
||||
|
||||
protected endLongPress(): void {
|
||||
this.cancelLongPress();
|
||||
}
|
||||
|
||||
protected onAction(event: MouseEvent): void {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.action.emit();
|
||||
}
|
||||
|
||||
protected onMenu(event: MouseEvent): void {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.menuRequested.emit(contextMenuRequest(event));
|
||||
}
|
||||
|
||||
protected requestContextMenu(event: MouseEvent): void {
|
||||
this.cancelLongPress();
|
||||
if (!this.overlays()) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (this.longPressFired) {
|
||||
return;
|
||||
}
|
||||
this.menuRequested.emit(contextMenuRequest(event));
|
||||
}
|
||||
|
||||
private cancelLongPress(): void {
|
||||
if (this.pressTimer !== null) {
|
||||
clearTimeout(this.pressTimer);
|
||||
this.pressTimer = null;
|
||||
}
|
||||
this.pressTarget?.removeEventListener('pointermove', this.onPressMove);
|
||||
this.pressTarget = null;
|
||||
this.pressOrigin = null;
|
||||
}
|
||||
|
||||
private consumeLongPress(): boolean {
|
||||
if (!this.longPressFired) {
|
||||
return false;
|
||||
}
|
||||
this.longPressFired = false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export const BOOK_CARD_COVER_ASPECT = 7 / 5;
|
||||
|
||||
export const BOOK_CARD_META_PADDING_TOP = 8;
|
||||
export const BOOK_CARD_META_TITLE_HEIGHT = 17;
|
||||
export const BOOK_CARD_META_AUTHOR_HEIGHT = 16;
|
||||
export const BOOK_CARD_META_ACCESSORY_HEIGHT = 15;
|
||||
|
||||
export const BOOK_CARD_RADIUS_CLASS = 'rounded-[clamp(6px,calc(var(--card-width,150px)*0.08),12px)]';
|
||||
|
||||
export function bookCardAspectClass(square: boolean): string {
|
||||
return square ? 'aspect-square' : 'aspect-[5/7]';
|
||||
}
|
||||
|
||||
export function bookCardHeightForWidth(
|
||||
width: number,
|
||||
{square, metaLines}: {square: boolean; metaLines: 2 | 3},
|
||||
): number {
|
||||
const coverHeight = Math.round(width * (square ? 1 : BOOK_CARD_COVER_ASPECT));
|
||||
const metaHeight = BOOK_CARD_META_PADDING_TOP
|
||||
+ BOOK_CARD_META_TITLE_HEIGHT
|
||||
+ BOOK_CARD_META_AUTHOR_HEIGHT
|
||||
+ (metaLines - 2) * BOOK_CARD_META_ACCESSORY_HEIGHT;
|
||||
return coverHeight + metaHeight;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import {booleanAttribute, ChangeDetectionStrategy, Component, computed, input, output} from '@angular/core';
|
||||
import {LucideCheck} from '@lucide/angular';
|
||||
|
||||
import {cn} from '../../../../shared/ui/cn';
|
||||
|
||||
const cardCheckboxBaseClass =
|
||||
'group/check flex size-6 items-center justify-center rounded-md bg-black/80 text-white ring-1 ring-inset ring-white/30 transition-opacity motion-reduce:transition-none ' +
|
||||
'pointer-events-none opacity-0 ' +
|
||||
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
|
||||
const cardCheckboxInteractiveClass =
|
||||
'group-hover/card:pointer-events-auto group-hover/card:opacity-100 group-has-[:focus-visible]/card:pointer-events-auto group-has-[:focus-visible]/card:opacity-100 group-data-[active=true]/card:pointer-events-auto group-data-[active=true]/card:opacity-100';
|
||||
const cardCheckboxSelectedClass = 'bg-primary text-primary-contrast ring-primary';
|
||||
const cardCheckIconClass =
|
||||
'size-3.5 opacity-0 transition-opacity group-hover/check:opacity-100 motion-reduce:transition-none';
|
||||
|
||||
@Component({
|
||||
selector: 'app-card-selection',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [LucideCheck],
|
||||
host: {class: 'pointer-events-none absolute left-2 top-2 z-20'},
|
||||
template: `
|
||||
@if (selectionMode()) {
|
||||
<span [class]="controlClass()" aria-hidden="true">
|
||||
<svg lucideCheck [class]="checkClass()"></svg>
|
||||
</span>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
[class]="controlClass()"
|
||||
[attr.aria-pressed]="selected()"
|
||||
[attr.aria-label]="ariaLabel()"
|
||||
(click)="onToggle($event)"
|
||||
>
|
||||
<svg lucideCheck [class]="checkClass()"></svg>
|
||||
</button>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class CardSelectionComponent {
|
||||
readonly selected = input(false, {transform: booleanAttribute});
|
||||
readonly selectionMode = input(false, {transform: booleanAttribute});
|
||||
readonly ariaLabel = input.required<string>();
|
||||
|
||||
readonly selectionToggled = output<{shiftKey: boolean}>();
|
||||
|
||||
protected readonly controlClass = computed(() =>
|
||||
cn(
|
||||
cardCheckboxBaseClass,
|
||||
this.selectionMode() ? '' : cardCheckboxInteractiveClass,
|
||||
this.selected() || this.selectionMode() ? 'opacity-100' : '',
|
||||
this.selected() && !this.selectionMode() ? 'pointer-events-auto' : '',
|
||||
this.selected() ? cardCheckboxSelectedClass : '',
|
||||
),
|
||||
);
|
||||
protected readonly checkClass = computed(() =>
|
||||
cn(cardCheckIconClass, this.selected() ? 'opacity-100' : ''),
|
||||
);
|
||||
|
||||
protected onToggle(event: MouseEvent): void {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.selectionToggled.emit({shiftKey: event.shiftKey});
|
||||
}
|
||||
}
|
||||
@@ -664,4 +664,25 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="showcase-section">
|
||||
<h2>Book Cards</h2>
|
||||
<app-book-menu #bookCardMenu openInNewTab [books]="bookCards()" />
|
||||
<div class="flex flex-wrap items-start gap-6">
|
||||
@for (book of bookCards(); track book.id) {
|
||||
<app-book-card
|
||||
class="w-40"
|
||||
[book]="book"
|
||||
showFormatPill
|
||||
[menuOpen]="bookCardMenu.openBookId() === book.id"
|
||||
(action)="readBook(book)"
|
||||
(menuRequested)="bookCardMenu.openFor(book, $event)" />
|
||||
} @empty {
|
||||
@if (!bookCardsPending()) {
|
||||
<p class="text-sm text-text-muted dark:text-text-secondary">No books in the library.</p>
|
||||
}
|
||||
}
|
||||
<app-book-card-skeleton class="w-40" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</main>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
|
||||
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
|
||||
import { CdkScrollable } from '@angular/cdk/scrolling';
|
||||
import { Router } from '@angular/router';
|
||||
import { email, form, FormField, minLength, required, validate } from '@angular/forms/signals';
|
||||
@@ -65,6 +65,14 @@ import { AppTabsComponent, type TabItem } from '../../shared/ui/tabs/app-tabs.co
|
||||
import { AppTagComponent } from '../../shared/ui/tag/app-tag.component';
|
||||
import { AppTextareaComponent } from '../../shared/ui/textarea/app-textarea.component';
|
||||
import { AppTooltipDirective } from '../../shared/ui/tooltip/app-tooltip.directive';
|
||||
import { injectQuery } from '@tanstack/angular-query-experimental';
|
||||
import { BookQueryService } from '../book/data/book-query.service';
|
||||
import { EMPTY_FACET_SELECTION } from '../book/data/book-query-params';
|
||||
import { type BookSummary } from '../book/data/book-response.models';
|
||||
import { BookCardComponent } from '../book/components/cards/book-card.component';
|
||||
import { BookCardSkeletonComponent } from '../book/components/cards/book-card-skeleton.component';
|
||||
import { BookMenuComponent } from '../book/components/book-menu/book-menu.component';
|
||||
import { BookNavigationService } from '../book/service/book-navigation.service';
|
||||
|
||||
interface ButtonExample {
|
||||
tone: ButtonTone;
|
||||
@@ -114,6 +122,9 @@ interface ButtonExample {
|
||||
AppTagComponent,
|
||||
AppTextareaComponent,
|
||||
AppTooltipDirective,
|
||||
BookCardComponent,
|
||||
BookCardSkeletonComponent,
|
||||
BookMenuComponent,
|
||||
LucideFolder,
|
||||
LucideSmartphone,
|
||||
LucideList,
|
||||
@@ -137,6 +148,21 @@ interface ButtonExample {
|
||||
})
|
||||
export class DesignSystemComponent {
|
||||
private readonly router = inject(Router);
|
||||
private readonly bookQueryService = inject(BookQueryService);
|
||||
private readonly bookNavigation = inject(BookNavigationService);
|
||||
|
||||
private readonly bookCardsQuery = injectQuery(() => this.bookQueryService.page({
|
||||
facets: EMPTY_FACET_SELECTION,
|
||||
facetLogic: 'or',
|
||||
sort: [{ key: 'title', direction: 'asc' }],
|
||||
size: 4,
|
||||
}));
|
||||
readonly bookCards = computed(() => this.bookCardsQuery.data()?.content ?? []);
|
||||
readonly bookCardsPending = computed(() => this.bookCardsQuery.isPending());
|
||||
|
||||
readBook(book: BookSummary): void {
|
||||
this.bookNavigation.readBook(book);
|
||||
}
|
||||
|
||||
openExample(path: string): void {
|
||||
void this.router.navigate(['/design-system', 'form', path]);
|
||||
|
||||
@@ -20,15 +20,25 @@
|
||||
/>
|
||||
} @else {
|
||||
<div
|
||||
class="placeholder group flex aspect-[5/7] h-full w-full flex-col items-center justify-center gap-1 overflow-hidden rounded-[inherit] p-1 text-center data-[size=md]:p-2 data-[size=lg]:gap-2 data-[size=lg]:p-4"
|
||||
class="placeholder group flex aspect-[5/7] h-full w-full flex-col justify-end overflow-hidden rounded-[inherit] p-2 text-left data-[size=md]:p-3 data-[size=lg]:p-3 bg-[linear-gradient(135deg,oklch(0.58_0.075_var(--cover-h))_25%,oklch(0.46_0.09_var(--cover-h))_95%)] dark:bg-[linear-gradient(135deg,oklch(0.40_0.065_var(--cover-h))_25%,oklch(0.30_0.06_var(--cover-h))_95%)]"
|
||||
[attr.data-size]="size()"
|
||||
[style.background]="color()"
|
||||
[style.--cover-h]="hue()"
|
||||
>
|
||||
<div class="placeholder-title line-clamp-3 max-w-full overflow-hidden break-words text-xs font-semibold leading-snug text-white/90 group-data-[size=md]:text-sm group-data-[size=lg]:text-base">
|
||||
{{ title() }}
|
||||
</div>
|
||||
<div class="placeholder-author line-clamp-1 max-w-full overflow-hidden break-words text-xs text-white/55 group-data-[size=lg]:text-sm">
|
||||
{{ authorsLabel() }}
|
||||
<div
|
||||
class="@max-[80px]:hidden transition-transform duration-300 ease-glide group-hover/lift:-translate-y-7 group-has-[:focus-visible]/lift:-translate-y-7 group-[.cover-lifted]/lift:-translate-y-7 motion-reduce:transition-none text-[oklch(0.95_0.025_var(--cover-h))] dark:text-[oklch(0.94_0.03_var(--cover-h))]"
|
||||
>
|
||||
@if (titleOnly()) {
|
||||
<div class="placeholder-title line-clamp-3 max-w-full overflow-hidden break-words font-normal leading-[1.25] font-cover-serif text-[14px] group-data-[size=md]:text-[17px] group-data-[size=lg]:text-[19px]">
|
||||
{{ title() }}
|
||||
</div>
|
||||
} @else {
|
||||
<div class="placeholder-title line-clamp-3 max-w-full overflow-hidden break-words font-normal leading-[1.25] font-cover-serif text-[12px] group-data-[size=md]:text-[15px] group-data-[size=lg]:text-[17px]">
|
||||
{{ title() }}
|
||||
</div>
|
||||
<div class="placeholder-author mt-1 line-clamp-1 max-w-full overflow-hidden break-words uppercase tracking-[0.08em] opacity-70 font-cover-serif text-[8.5px] group-data-[size=md]:mt-1.5 group-data-[size=md]:text-[9.5px] group-data-[size=lg]:text-[11px]">
|
||||
{{ authorsLabel() }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, signal, viewChild} from '@angular/core';
|
||||
import {Image} from '@openng/optimus-ui/image';
|
||||
|
||||
const COVER_COLORS = [
|
||||
'#1a1a2e', '#2d3436', '#0c3547', '#1e3d59', '#2c2c54', '#1b262c',
|
||||
'#2B2D42', '#3D405B', '#463F3A', '#1B2838', '#2E4057', '#4A3728',
|
||||
];
|
||||
const COVER_HUES = [20, 155, 185, 205, 235, 265, 290, 320, 350];
|
||||
|
||||
function hashString(str: string): number {
|
||||
let hash = 0;
|
||||
@@ -15,8 +12,8 @@ function hashString(str: string): number {
|
||||
return hash;
|
||||
}
|
||||
|
||||
function coverColorFor(title: string, author: string): string {
|
||||
return COVER_COLORS[Math.abs(hashString(title + author) % COVER_COLORS.length)];
|
||||
function coverHueFor(title: string, author: string): number {
|
||||
return COVER_HUES[Math.abs(hashString(title + author)) % COVER_HUES.length];
|
||||
}
|
||||
|
||||
type CoverSize = 'sm' | 'md' | 'lg';
|
||||
@@ -30,7 +27,7 @@ type CoverAuthors = string | string[];
|
||||
imports: [Image],
|
||||
templateUrl: './cover.component.html',
|
||||
host: {
|
||||
class: 'block w-full',
|
||||
class: '@container block w-full',
|
||||
'[class.h-full]': '!natural()',
|
||||
'[class.h-auto]': 'natural()',
|
||||
'(window:popstate)': 'closePreview()',
|
||||
@@ -54,7 +51,10 @@ export class CoverComponent {
|
||||
const authors = this.authors();
|
||||
return Array.isArray(authors) ? authors.join(', ') : authors ?? '';
|
||||
});
|
||||
protected readonly color = computed(() => coverColorFor(this.title() ?? '', this.authorsLabel()));
|
||||
protected readonly hue = computed(() => coverHueFor(this.title() ?? '', this.authorsLabel()));
|
||||
protected readonly titleOnly = computed(
|
||||
() => !this.authorsLabel() || (hashString((this.title() ?? '') + this.authorsLabel()) & 1) === 0,
|
||||
);
|
||||
protected readonly imageClass = computed(() => [
|
||||
'cover-img block w-full rounded-[inherit]',
|
||||
this.natural() ? 'h-auto' : 'h-full',
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {fileSizeDisplayUnit, formatFileSizeKb} from './file-size';
|
||||
|
||||
describe('file-size util', () => {
|
||||
it('picks display units and formats with adaptive precision', () => {
|
||||
expect(fileSizeDisplayUnit(358).label).toBe('KB');
|
||||
expect(fileSizeDisplayUnit(1468006).label).toBe('GB');
|
||||
expect(formatFileSizeKb(700)).toBe('700 KB');
|
||||
expect(formatFileSizeKb(15360)).toBe('15.0 MB');
|
||||
expect(formatFileSizeKb(1468006)).toBe('1.40 GB');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
export const FILE_SIZE_UNITS = [
|
||||
{label: 'KB', kb: 1},
|
||||
{label: 'MB', kb: 1024},
|
||||
{label: 'GB', kb: 1024 ** 2},
|
||||
{label: 'TB', kb: 1024 ** 3},
|
||||
] as const;
|
||||
|
||||
export type FileSizeUnit = (typeof FILE_SIZE_UNITS)[number];
|
||||
|
||||
export function fileSizeDisplayUnit(fileSizeKb: number): FileSizeUnit {
|
||||
return [...FILE_SIZE_UNITS].reverse().find(unit => fileSizeKb >= unit.kb) ?? FILE_SIZE_UNITS[0];
|
||||
}
|
||||
|
||||
export function formatFileSizeKb(fileSizeKb: number): string {
|
||||
const unit = fileSizeDisplayUnit(fileSizeKb);
|
||||
const size = fileSizeKb / unit.kb;
|
||||
const decimals = size >= 100 ? 0 : size >= 10 ? 1 : 2;
|
||||
return `${size.toFixed(decimals)} ${unit.label}`;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
const applePlatform = /Mac/i.test(navigator.userAgent);
|
||||
|
||||
export function isContextMenuGesture(event: MouseEvent): boolean {
|
||||
return applePlatform && event.ctrlKey;
|
||||
}
|
||||
|
||||
export function isPlainLeftClick(event: MouseEvent): boolean {
|
||||
return event.button === 0
|
||||
&& !event.ctrlKey
|
||||
&& !event.metaKey
|
||||
&& !event.shiftKey
|
||||
&& !event.altKey;
|
||||
}
|
||||
Reference in New Issue
Block a user