refactor(ui): remove old book browser (#2575)
This commit is contained in:
+2
-2
@@ -116,12 +116,12 @@
|
||||
<div class="virtual-scroller-item"
|
||||
[style.width.px]="currentCardSize.width"
|
||||
[style.height.px]="currentCardSize.height">
|
||||
<app-book-card
|
||||
<app-legacy-book-card
|
||||
[index]="virtualItem.index"
|
||||
[book]="book"
|
||||
[isSeriesCollapsed]="false"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</app-legacy-book-card>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@ import {Subject, of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/legacy-book-card/book-card-overlay-preference.service';
|
||||
import {CoverScalePreferenceService} from '../../../../shared/service/cover-scale-preference.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import type {AuthorDetails} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
|
||||
+4
-4
@@ -11,9 +11,9 @@ import { Tooltip } from '@openng/optimus-ui/tooltip';
|
||||
import { AuthorService } from '../../service/author.service';
|
||||
import { AuthorDetails } from '../../model/author.model';
|
||||
import { BookService } from '../../../book/service/book.service';
|
||||
import { BookCardComponent } from '../../../book/components/book-browser/book-card/book-card.component';
|
||||
import { CoverScalePreferenceService } from '../../../book/components/book-browser/cover-scale-preference.service';
|
||||
import { BookCardOverlayPreferenceService } from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import { LegacyBookCardComponent } from '../../../book/components/legacy-book-card/legacy-book-card.component';
|
||||
import { CoverScalePreferenceService } from '../../../../shared/service/cover-scale-preference.service';
|
||||
import { BookCardOverlayPreferenceService } from '../../../book/components/legacy-book-card/book-card-overlay-preference.service';
|
||||
import { UserService } from '../../../settings/user-management/user.service';
|
||||
import { AuthorMatchComponent } from '../author-match/author-match.component';
|
||||
import { AuthorEditorComponent } from '../author-editor/author-editor.component';
|
||||
@@ -37,7 +37,7 @@ import { createVirtualGrid } from '../../../../shared/util/virtual-grid.util';
|
||||
Tag,
|
||||
TranslocoDirective,
|
||||
Tooltip,
|
||||
BookCardComponent,
|
||||
LegacyBookCardComponent,
|
||||
AuthorMatchComponent,
|
||||
AuthorEditorComponent
|
||||
]
|
||||
|
||||
@@ -10,7 +10,7 @@ import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {type BookSummary} from '../data/book-response.models';
|
||||
import {ShelfDefinitionQueryService} from '../data/shelf-definition-query.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../service/book-dialog-helper.service';
|
||||
import {BookBrowseBulkBarComponent} from './book-browse-bulk-bar.component';
|
||||
|
||||
function selectionOf(ids: readonly number[]): BrowseSelection {
|
||||
|
||||
@@ -8,7 +8,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {createQueryClientHarness, flushQueryAsync} from '../../../core/testing/query-testing';
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../service/book-dialog-helper.service';
|
||||
import {type BrowseSelection, type BrowseSelectionState} from '../../../shared/browse/selection';
|
||||
import {createBookBrowseBulkCommands} from './book-browse-bulk-commands';
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import {BookShelfCommandService} from '../data/book-shelf-command.service';
|
||||
import {type BookSummary, type KnownBookReadStatus} from '../data/book-response.models';
|
||||
import {MetadataRefreshSubmissionService} from '../../metadata/data/metadata-refresh-submission.service';
|
||||
import {type BookFileAttacherSourceBook} from '../components/book-file-attacher/book-file-attacher.component';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../service/book-dialog-helper.service';
|
||||
import {legacyBookCachePatches, withLegacyBookCache} from '../service/book-command-legacy-adapter';
|
||||
import {resolveSelectedIds, type BrowseSelection} from '../../../shared/browse/selection';
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import {LibraryService} from '../service/library.service';
|
||||
import {LibraryShelfMenuService} from '../service/library-shelf-menu.service';
|
||||
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {ShelfDefinitionQueryService} from '../data/shelf-definition-query.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../service/book-dialog-helper.service';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../settings/email-v2/email.service';
|
||||
import {type BookSortTerm} from '../data/book-query-params';
|
||||
|
||||
@@ -24,7 +24,7 @@ import {LayoutService} from '../../../shared/layout/layout.service';
|
||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
||||
import {PageTitleService} from '../../../shared/service/page-title.service';
|
||||
import {createGridDensity, type GridDensityDirection} from '../../../shared/util/grid-density.util';
|
||||
import {CoverScalePreferenceService} from '../components/book-browser/cover-scale-preference.service';
|
||||
import {CoverScalePreferenceService} from '../../../shared/service/cover-scale-preference.service';
|
||||
import {LibraryService} from '../service/library.service';
|
||||
import {BookNavigationService} from '../service/book-navigation.service';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {convertToParamMap} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookBrowserEntityService} from './book-browser-entity.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {EntityType} from './book-browser.component';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {MagicShelfService, MagicShelf} from '../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: id, title: `Book ${id}`},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookBrowserEntityService', () => {
|
||||
let service: BookBrowserEntityService;
|
||||
let libraryService: {libraries: ReturnType<typeof vi.fn>};
|
||||
let shelfService: {shelves: ReturnType<typeof vi.fn>};
|
||||
let magicShelfService: {findShelfById: ReturnType<typeof vi.fn>};
|
||||
let bookRuleEvaluatorService: {evaluateGroup: ReturnType<typeof vi.fn>};
|
||||
|
||||
const library = {
|
||||
id: 1,
|
||||
name: 'Library',
|
||||
watch: true,
|
||||
paths: [{path: '/books'}]
|
||||
} as Library;
|
||||
const shelf = {id: 2, name: 'Shelf'} as Shelf;
|
||||
const magicShelf = {
|
||||
id: 3,
|
||||
name: 'Magic Shelf',
|
||||
filterJson: JSON.stringify({group: 'all'})
|
||||
} as MagicShelf;
|
||||
|
||||
beforeEach(() => {
|
||||
libraryService = {
|
||||
libraries: vi.fn(() => [library])
|
||||
};
|
||||
shelfService = {
|
||||
shelves: vi.fn(() => [shelf])
|
||||
};
|
||||
magicShelfService = {
|
||||
findShelfById: vi.fn((id: number) => id === 3 ? magicShelf : null)
|
||||
};
|
||||
bookRuleEvaluatorService = {
|
||||
evaluateGroup: vi.fn((book: Book) => book.id === 2)
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookBrowserEntityService,
|
||||
{provide: LibraryService, useValue: libraryService},
|
||||
{provide: ShelfService, useValue: shelfService},
|
||||
{provide: MagicShelfService, useValue: magicShelfService},
|
||||
{provide: BookRuleEvaluatorService, useValue: bookRuleEvaluatorService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookBrowserEntityService);
|
||||
});
|
||||
|
||||
it('resolves entity ids from route params in priority order', () => {
|
||||
const allParams = convertToParamMap({
|
||||
libraryId: '1',
|
||||
shelfId: '2',
|
||||
magicShelfId: '3'
|
||||
});
|
||||
const shelfFirstParams = convertToParamMap({
|
||||
shelfId: '2',
|
||||
magicShelfId: '3'
|
||||
});
|
||||
const emptyParams = convertToParamMap({});
|
||||
|
||||
expect(service.getEntityInfo(allParams)).toEqual({
|
||||
entityId: 1,
|
||||
entityType: EntityType.LIBRARY
|
||||
});
|
||||
expect(service.getEntityInfo(shelfFirstParams)).toEqual({
|
||||
entityId: 2,
|
||||
entityType: EntityType.SHELF
|
||||
});
|
||||
expect(service.getEntityInfo(emptyParams)).toEqual({
|
||||
entityId: NaN,
|
||||
entityType: EntityType.ALL_BOOKS
|
||||
});
|
||||
});
|
||||
|
||||
it('returns entity records and recognizes library and magic shelf types', () => {
|
||||
expect(service.getEntity(1, EntityType.LIBRARY)).toBe(library);
|
||||
expect(service.getEntity(2, EntityType.SHELF)).toBe(shelf);
|
||||
expect(service.getEntity(3, EntityType.MAGIC_SHELF)).toBe(magicShelf);
|
||||
expect(service.getEntity(999, EntityType.ALL_BOOKS)).toBeNull();
|
||||
|
||||
expect(service.isLibrary(library)).toBe(true);
|
||||
expect(service.isLibrary(shelf as Library | Shelf | MagicShelf)).toBe(false);
|
||||
expect(service.isMagicShelf(magicShelf)).toBe(true);
|
||||
expect(service.isMagicShelf(null)).toBe(false);
|
||||
});
|
||||
|
||||
it('filters books by entity type and handles magic shelf parsing failures', () => {
|
||||
const books = [
|
||||
makeBook(1, {libraryId: 1, shelves: [{id: 2} as never]}),
|
||||
makeBook(2, {libraryId: 1, shelves: []}),
|
||||
makeBook(3, {libraryId: 2, shelves: [{id: 2} as never]})
|
||||
];
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
expect(service.getBooksByEntity(books, 1, EntityType.LIBRARY)).toEqual([
|
||||
books[0],
|
||||
books[1]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 2, EntityType.SHELF)).toEqual([
|
||||
books[0],
|
||||
books[2]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 0, EntityType.UNSHELVED)).toEqual([
|
||||
books[1]
|
||||
]);
|
||||
expect(service.getBooksByEntity(books, 0, EntityType.ALL_BOOKS)).toBe(books);
|
||||
|
||||
expect(service.getBooksByEntity(books, 3, EntityType.MAGIC_SHELF)).toEqual([
|
||||
books[1]
|
||||
]);
|
||||
expect(bookRuleEvaluatorService.evaluateGroup).toHaveBeenCalledWith(
|
||||
books[0],
|
||||
{group: 'all'},
|
||||
books
|
||||
);
|
||||
|
||||
magicShelfService.findShelfById.mockReturnValueOnce({
|
||||
id: 4,
|
||||
name: 'Broken Magic Shelf',
|
||||
filterJson: '{broken json'
|
||||
} as MagicShelf);
|
||||
|
||||
expect(service.getBooksByEntity(books, 4, EntityType.MAGIC_SHELF)).toEqual([]);
|
||||
expect(warnSpy).toHaveBeenCalledWith('Invalid filterJson for MagicShelf');
|
||||
});
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {ParamMap} from '@angular/router';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||
import {EntityType} from './book-browser.component';
|
||||
|
||||
export interface EntityInfo {
|
||||
entityId: number;
|
||||
entityType: EntityType;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookBrowserEntityService {
|
||||
private libraryService = inject(LibraryService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private magicShelfService = inject(MagicShelfService);
|
||||
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
|
||||
getEntityInfo(paramMap: ParamMap): EntityInfo {
|
||||
const libraryId = Number(paramMap.get('libraryId') || NaN);
|
||||
const shelfId = Number(paramMap.get('shelfId') || NaN);
|
||||
const magicShelfId = Number(paramMap.get('magicShelfId') || NaN);
|
||||
|
||||
if (!Number.isNaN(libraryId)) {
|
||||
return {entityId: libraryId, entityType: EntityType.LIBRARY};
|
||||
}
|
||||
|
||||
if (!Number.isNaN(shelfId)) {
|
||||
return {entityId: shelfId, entityType: EntityType.SHELF};
|
||||
}
|
||||
|
||||
if (!Number.isNaN(magicShelfId)) {
|
||||
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
|
||||
}
|
||||
|
||||
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
|
||||
}
|
||||
|
||||
getEntity(entityId: number, entityType: EntityType): Library | Shelf | MagicShelf | null {
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return this.libraryService.libraries().find(lib => lib.id === entityId) ?? null;
|
||||
case EntityType.SHELF:
|
||||
return this.shelfService.shelves().find(shelf => shelf.id === entityId) ?? null;
|
||||
case EntityType.MAGIC_SHELF:
|
||||
return this.magicShelfService.findShelfById(entityId) ?? null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getBooksByEntity(books: Book[], entityId: number, entityType: EntityType): Book[] {
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return books.filter(book => book.libraryId === entityId);
|
||||
case EntityType.SHELF:
|
||||
return books.filter(book => book.shelves?.some(shelf => shelf.id === entityId) ?? false);
|
||||
case EntityType.MAGIC_SHELF: {
|
||||
const magicShelf = this.getEntity(entityId, entityType);
|
||||
return this.isMagicShelf(magicShelf) ? this.filterByMagicShelf(books, magicShelf) : [];
|
||||
}
|
||||
case EntityType.UNSHELVED:
|
||||
return books.filter(book => !book.shelves || book.shelves.length === 0);
|
||||
case EntityType.ALL_BOOKS:
|
||||
default:
|
||||
return books;
|
||||
}
|
||||
}
|
||||
|
||||
isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
|
||||
return (entity as Library).paths !== undefined;
|
||||
}
|
||||
|
||||
isMagicShelf(entity: Library | Shelf | MagicShelf | null): entity is MagicShelf {
|
||||
return !!entity && 'filterJson' in entity;
|
||||
}
|
||||
|
||||
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
|
||||
if (!magicShelf.filterJson) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
|
||||
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
|
||||
} catch {
|
||||
console.warn('Invalid filterJson for MagicShelf');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
-300
@@ -1,300 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {EntityType} from './book-browser.component';
|
||||
import {
|
||||
BookBrowserQueryParamsService,
|
||||
QUERY_PARAMS,
|
||||
VIEW_MODES
|
||||
} from './book-browser-query-params.service';
|
||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||
import {EntityViewPreferences} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('BookBrowserQueryParamsService', () => {
|
||||
let service: BookBrowserQueryParamsService;
|
||||
let routerNavigate: ReturnType<typeof vi.fn>;
|
||||
let routeSnapshot: {
|
||||
queryParams: Record<string, string | null>;
|
||||
queryParamMap: ParamMap;
|
||||
};
|
||||
let activatedRoute: {snapshot: typeof routeSnapshot};
|
||||
|
||||
const sortOptions: SortOption[] = [
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING},
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Authors', field: 'author', direction: SortDirection.ASCENDING}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
routerNavigate = vi.fn();
|
||||
routeSnapshot = {
|
||||
queryParams: {},
|
||||
queryParamMap: convertToParamMap({})
|
||||
};
|
||||
activatedRoute = {snapshot: routeSnapshot};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookBrowserQueryParamsService,
|
||||
{provide: Router, useValue: {navigate: routerNavigate}},
|
||||
{provide: ActivatedRoute, useValue: activatedRoute}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookBrowserQueryParamsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('parses explicit query params, filters, and toggle state', () => {
|
||||
const result = service.parseQueryParams(
|
||||
convertToParamMap({
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE,
|
||||
[QUERY_PARAMS.SORT]: 'title:desc,author:asc',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi,series:A%3AB',
|
||||
[QUERY_PARAMS.FMODE]: 'or',
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
}),
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
viewMode: VIEW_MODES.TABLE,
|
||||
sortOption: {label: 'Title', field: 'title', direction: SortDirection.DESCENDING},
|
||||
sortCriteria: [
|
||||
{label: 'Title', field: 'title', direction: SortDirection.DESCENDING},
|
||||
{label: 'Authors', field: 'author', direction: SortDirection.ASCENDING}
|
||||
],
|
||||
filters: {
|
||||
tag: ['fiction', 'sci fi'],
|
||||
series: ['A:B']
|
||||
},
|
||||
filterMode: 'or',
|
||||
viewModeFromToggle: true
|
||||
});
|
||||
});
|
||||
|
||||
it('uses entity overrides, legacy preferences, and default sort fallback', () => {
|
||||
const userPrefs: EntityViewPreferences = {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
sortCriteria: [
|
||||
{field: 'title', direction: 'DESC'}
|
||||
],
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 7,
|
||||
preferences: {
|
||||
sortKey: 'authors',
|
||||
sortDir: 'DESC',
|
||||
sortCriteria: [
|
||||
{field: 'authors', direction: 'DESC'}
|
||||
],
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: false
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const overrideResult = service.parseQueryParams(
|
||||
convertToParamMap({
|
||||
[QUERY_PARAMS.FMODE]: 'single'
|
||||
}),
|
||||
userPrefs,
|
||||
EntityType.LIBRARY,
|
||||
7,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(overrideResult.viewMode).toBe(VIEW_MODES.GRID);
|
||||
expect(overrideResult.filterMode).toBe('single');
|
||||
expect(overrideResult.sortCriteria).toEqual([
|
||||
{label: 'authors', field: 'authors', direction: SortDirection.DESCENDING}
|
||||
]);
|
||||
|
||||
const legacyResult = service.parseQueryParams(
|
||||
convertToParamMap({}),
|
||||
{
|
||||
global: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'DESC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(legacyResult.sortOption).toEqual({
|
||||
label: 'Title',
|
||||
field: 'title',
|
||||
direction: SortDirection.DESCENDING
|
||||
});
|
||||
expect(legacyResult.viewMode).toBe('table');
|
||||
|
||||
const fallbackResult = service.parseQueryParams(
|
||||
convertToParamMap({}),
|
||||
{
|
||||
global: {
|
||||
sortKey: 'missing',
|
||||
sortDir: 'DESC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
sortOptions,
|
||||
'and'
|
||||
);
|
||||
|
||||
expect(fallbackResult.sortOption).toEqual({
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
});
|
||||
});
|
||||
|
||||
it('serializes and deserializes sorts and filters while ignoring malformed input', () => {
|
||||
expect(service.serializeSort([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
{label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING}
|
||||
])).toBe('title:asc,addedOn:desc');
|
||||
|
||||
expect(service.deserializeSort('title:desc,missing:asc', sortOptions)).toEqual([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.DESCENDING}
|
||||
]);
|
||||
|
||||
expect(service.serializeFilters({
|
||||
tag: ['sci fi', 'new:release'],
|
||||
series: ['A/B']
|
||||
})).toBe('tag:sci%20fi|new%3Arelease,series:A%2FB');
|
||||
|
||||
expect(service.deserializeFilters('tag:sci%20fi|new%3Arelease,broken,series:A%2FB')).toEqual({
|
||||
tag: ['sci fi', 'new:release'],
|
||||
series: ['A/B']
|
||||
});
|
||||
});
|
||||
|
||||
it('updates query params for view mode, sort, filters, and sync changes', () => {
|
||||
routeSnapshot.queryParams = {
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'title:asc',
|
||||
[QUERY_PARAMS.DIRECTION]: 'desc',
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.GRID,
|
||||
[QUERY_PARAMS.FMODE]: 'and',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
};
|
||||
routeSnapshot.queryParamMap = convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
});
|
||||
|
||||
service.updateViewMode(VIEW_MODES.TABLE);
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.VIEW]: VIEW_MODES.TABLE,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
}));
|
||||
|
||||
service.updateSort({label: 'Added On', field: 'addedOn', direction: SortDirection.DESCENDING});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: expect.objectContaining({
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'addedOn:desc',
|
||||
[QUERY_PARAMS.DIRECTION]: null
|
||||
}),
|
||||
replaceUrl: true
|
||||
}));
|
||||
|
||||
routerNavigate.mockClear();
|
||||
routeSnapshot.queryParamMap = convertToParamMap({});
|
||||
service.updateFilters(null);
|
||||
expect(routerNavigate).not.toHaveBeenCalled();
|
||||
|
||||
routeSnapshot.queryParamMap = convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
});
|
||||
service.updateFilters({tag: ['fiction', 'sci fi']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {[QUERY_PARAMS.FILTER]: 'tag:fiction|sci%20fi'},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
service.updateFilterMode('single', {tag: ['fiction', 'sci fi']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.FMODE]: 'single',
|
||||
[QUERY_PARAMS.FILTER]: null
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
service.updateFilterMode('or', {tag: ['fiction']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
relativeTo: activatedRoute as never,
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.FMODE]: 'or'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
}));
|
||||
|
||||
routerNavigate.mockClear();
|
||||
service.syncQueryParams('grid', 'and', {tag: ['fiction']});
|
||||
expect(routerNavigate).not.toHaveBeenCalled();
|
||||
|
||||
service.syncQueryParams('table', 'single', {tag: ['fiction']});
|
||||
expect(routerNavigate).toHaveBeenCalledWith([], expect.objectContaining({
|
||||
queryParams: {
|
||||
foo: 'bar',
|
||||
[QUERY_PARAMS.SORT]: 'title:asc',
|
||||
[QUERY_PARAMS.DIRECTION]: 'desc',
|
||||
[QUERY_PARAMS.VIEW]: 'table',
|
||||
[QUERY_PARAMS.FMODE]: 'single',
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction'
|
||||
},
|
||||
replaceUrl: true
|
||||
}));
|
||||
});
|
||||
|
||||
it('detects when a series filter should force expansion', () => {
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({}))).toBe(false);
|
||||
expect(service.shouldForceExpandSeries(convertToParamMap({
|
||||
[QUERY_PARAMS.FILTER]: 'tag:fiction,series:space-opera'
|
||||
}))).toBe(true);
|
||||
});
|
||||
});
|
||||
-306
@@ -1,306 +0,0 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
|
||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||
import {BookFilterMode, EntityViewPreference, EntityViewPreferences, SortCriterion} from '../../../settings/user-management/user.service';
|
||||
import {EntityType} from './book-browser.component';
|
||||
|
||||
export const QUERY_PARAMS = {
|
||||
VIEW: 'view',
|
||||
SORT: 'sort',
|
||||
DIRECTION: 'direction',
|
||||
FILTER: 'filter',
|
||||
FMODE: 'fmode',
|
||||
SIDEBAR: 'sidebar',
|
||||
FROM: 'from',
|
||||
} as const;
|
||||
|
||||
export const VIEW_MODES = {
|
||||
GRID: 'grid',
|
||||
TABLE: 'table',
|
||||
} as const;
|
||||
|
||||
export const SORT_DIRECTION = {
|
||||
ASCENDING: 'asc',
|
||||
DESCENDING: 'desc',
|
||||
} as const;
|
||||
|
||||
export interface BookBrowserQueryState {
|
||||
viewMode: 'grid' | 'table';
|
||||
sortField: string;
|
||||
sortDirection: SortDirection;
|
||||
filters: Record<string, string[]>;
|
||||
filterMode: BookFilterMode;
|
||||
}
|
||||
|
||||
export interface QueryParseResult {
|
||||
viewMode: string;
|
||||
sortOption: SortOption;
|
||||
sortCriteria: SortOption[];
|
||||
filters: Record<string, string[]>;
|
||||
filterMode: BookFilterMode;
|
||||
viewModeFromToggle: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookBrowserQueryParamsService {
|
||||
private router = inject(Router);
|
||||
private activatedRoute = inject(ActivatedRoute);
|
||||
|
||||
parseQueryParams(
|
||||
queryParamMap: ParamMap,
|
||||
userPrefs: EntityViewPreferences | undefined,
|
||||
entityType: EntityType | undefined,
|
||||
entityId: number | undefined,
|
||||
sortOptions: SortOption[],
|
||||
defaultFilterMode: BookFilterMode
|
||||
): QueryParseResult {
|
||||
const viewParam = queryParamMap.get(QUERY_PARAMS.VIEW);
|
||||
const sortParam = queryParamMap.get(QUERY_PARAMS.SORT);
|
||||
const directionParam = queryParamMap.get(QUERY_PARAMS.DIRECTION);
|
||||
const filterParams = queryParamMap.get(QUERY_PARAMS.FILTER);
|
||||
const filterModeParam = queryParamMap.get(QUERY_PARAMS.FMODE);
|
||||
const fromParam = queryParamMap.get(QUERY_PARAMS.FROM);
|
||||
|
||||
const filterMode = (filterModeParam || defaultFilterMode) as BookFilterMode;
|
||||
|
||||
// Parse filters
|
||||
const filters = this.deserializeFilters(filterParams);
|
||||
|
||||
// Determine effective preferences
|
||||
const globalPrefs = userPrefs?.global;
|
||||
const currentEntityTypeStr = entityType?.toString().toUpperCase().replaceAll(' ', '_');
|
||||
const override = userPrefs?.overrides?.find(o =>
|
||||
o.entityType?.toUpperCase() === currentEntityTypeStr &&
|
||||
o.entityId === entityId
|
||||
);
|
||||
|
||||
const effectivePrefs: EntityViewPreference = override?.preferences ?? globalPrefs ?? {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID',
|
||||
coverSize: 1.0,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
};
|
||||
|
||||
// Parse sort criteria - supports both legacy and new multi-sort format
|
||||
let sortCriteria: SortOption[];
|
||||
|
||||
if (sortParam) {
|
||||
// Check if it's new multi-sort format (contains colons like "author:asc,title:desc")
|
||||
if (sortParam.includes(':')) {
|
||||
sortCriteria = this.deserializeSort(sortParam, sortOptions);
|
||||
} else {
|
||||
// Legacy format: separate sort and direction params
|
||||
const effectiveSortDir = directionParam
|
||||
? (directionParam.toLowerCase() === SORT_DIRECTION.DESCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING)
|
||||
: SortDirection.ASCENDING;
|
||||
const matchedSort = sortOptions.find(opt => opt.field === sortParam);
|
||||
sortCriteria = matchedSort ? [{
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: effectiveSortDir
|
||||
}] : [];
|
||||
}
|
||||
} else {
|
||||
// Use user preferences
|
||||
if (effectivePrefs.sortCriteria && effectivePrefs.sortCriteria.length > 0) {
|
||||
sortCriteria = effectivePrefs.sortCriteria.map((c: SortCriterion) => {
|
||||
const matchedSort = sortOptions.find(opt => opt.field === c.field);
|
||||
return {
|
||||
label: matchedSort?.label ?? c.field,
|
||||
field: c.field,
|
||||
direction: c.direction === 'DESC' ? SortDirection.DESCENDING : SortDirection.ASCENDING
|
||||
};
|
||||
});
|
||||
} else {
|
||||
// Fall back to legacy single sort preference
|
||||
const userSortKey = effectivePrefs.sortKey;
|
||||
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING;
|
||||
const matchedSort = sortOptions.find(opt => opt.field === userSortKey);
|
||||
sortCriteria = matchedSort ? [{
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: userSortDir
|
||||
}] : [];
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure we have at least a default sort
|
||||
if (sortCriteria.length === 0) {
|
||||
sortCriteria = [{
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
}];
|
||||
}
|
||||
|
||||
// For backward compatibility, expose the first sort as sortOption
|
||||
const sortOption = sortCriteria[0];
|
||||
|
||||
// Determine view mode
|
||||
const viewModeFromToggle = fromParam === 'toggle';
|
||||
const viewMode = viewModeFromToggle
|
||||
? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID
|
||||
? viewParam
|
||||
: VIEW_MODES.GRID)
|
||||
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
|
||||
|
||||
return {
|
||||
viewMode,
|
||||
sortOption,
|
||||
sortCriteria,
|
||||
filters,
|
||||
filterMode,
|
||||
viewModeFromToggle
|
||||
};
|
||||
}
|
||||
|
||||
updateViewMode(mode: 'grid' | 'table'): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.VIEW]: mode,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
updateSort(sortOption: SortOption): void {
|
||||
this.updateMultiSort([sortOption]);
|
||||
}
|
||||
|
||||
updateMultiSort(sortCriteria: SortOption[]): void {
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const newParams = {
|
||||
...currentParams,
|
||||
[QUERY_PARAMS.SORT]: this.serializeSort(sortCriteria),
|
||||
[QUERY_PARAMS.DIRECTION]: null // Remove legacy direction param
|
||||
};
|
||||
|
||||
this.router.navigate([], {
|
||||
queryParams: newParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
serializeSort(criteria: SortOption[]): string {
|
||||
return criteria.map(c =>
|
||||
`${c.field}:${c.direction === SortDirection.ASCENDING ? 'asc' : 'desc'}`
|
||||
).join(',');
|
||||
}
|
||||
|
||||
deserializeSort(sortParam: string, sortOptions: SortOption[]): SortOption[] {
|
||||
const criteria: SortOption[] = [];
|
||||
|
||||
sortParam.split(',').forEach(part => {
|
||||
const [field, dir] = part.split(':');
|
||||
if (field) {
|
||||
const matchedSort = sortOptions.find(opt => opt.field === field);
|
||||
if (matchedSort) {
|
||||
criteria.push({
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: dir?.toLowerCase() === 'desc' ? SortDirection.DESCENDING : SortDirection.ASCENDING
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return criteria;
|
||||
}
|
||||
|
||||
updateFilters(filters: Record<string, string[]> | null): void {
|
||||
const queryParam = filters && Object.keys(filters).length > 0
|
||||
? this.serializeFilters(filters)
|
||||
: null;
|
||||
|
||||
if (queryParam !== this.activatedRoute.snapshot.queryParamMap.get(QUERY_PARAMS.FILTER)) {
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.activatedRoute,
|
||||
queryParams: {[QUERY_PARAMS.FILTER]: queryParam},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
updateFilterMode(mode: BookFilterMode, currentFilters: Record<string, string[]>): void {
|
||||
const params: Record<string, string | null> = {[QUERY_PARAMS.FMODE]: mode};
|
||||
|
||||
// Clear filters if switching from multiple selected to single mode
|
||||
if (mode === 'single') {
|
||||
const categories = Object.keys(currentFilters);
|
||||
if (categories.length > 1 || (categories.length === 1 && currentFilters[categories[0]].length > 1)) {
|
||||
params[QUERY_PARAMS.FILTER] = null;
|
||||
}
|
||||
}
|
||||
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.activatedRoute,
|
||||
queryParams: params,
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
});
|
||||
}
|
||||
|
||||
serializeFilters(filters: Record<string, string[]>): string {
|
||||
return Object.entries(filters)
|
||||
.map(([k, v]) => `${k}:${v.map(val => encodeURIComponent(val)).join('|')}`)
|
||||
.join(',');
|
||||
}
|
||||
|
||||
deserializeFilters(filterParam: string | null): Record<string, string[]> {
|
||||
const parsedFilters: Record<string, string[]> = {};
|
||||
|
||||
if (!filterParam) return parsedFilters;
|
||||
|
||||
filterParam.split(',').forEach(pair => {
|
||||
const [key, ...valueParts] = pair.split(':');
|
||||
const value = valueParts.join(':');
|
||||
if (key && value) {
|
||||
parsedFilters[key] = value.split('|').map(v => decodeURIComponent(v.trim())).filter(Boolean);
|
||||
}
|
||||
});
|
||||
|
||||
return parsedFilters;
|
||||
}
|
||||
|
||||
syncQueryParams(
|
||||
viewMode: string,
|
||||
filterMode: BookFilterMode,
|
||||
filters: Record<string, string[]>
|
||||
): void {
|
||||
const queryParams: Record<string, string | number | null | undefined> = {
|
||||
[QUERY_PARAMS.VIEW]: viewMode,
|
||||
[QUERY_PARAMS.FMODE]: filterMode,
|
||||
};
|
||||
|
||||
if (Object.keys(filters).length > 0) {
|
||||
queryParams[QUERY_PARAMS.FILTER] = this.serializeFilters(filters);
|
||||
}
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const changed = Object.keys(queryParams).some(k => (queryParams[k] ?? undefined) !== (currentParams[k] ?? undefined));
|
||||
|
||||
if (changed) {
|
||||
const mergedParams = {...currentParams, ...queryParams};
|
||||
this.router.navigate([], {
|
||||
queryParams: mergedParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
|
||||
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
|
||||
return (
|
||||
!!filterParam &&
|
||||
typeof filterParam === 'string' &&
|
||||
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,469 +0,0 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.browser'">
|
||||
<div class="book-browser-container">
|
||||
<div class="book-browser-main">
|
||||
|
||||
<div class="book-browser-header">
|
||||
<div class="entity-info-wrapper">
|
||||
@if (entityType(); as entityType) {
|
||||
<div class="entity-info">
|
||||
<p class="entity-title">
|
||||
@if (entityType === EntityType.ALL_BOOKS) {
|
||||
@if (currentFilterLabel() && rawFilterParamFromUrl()) {
|
||||
{{ currentFilterLabel() }}
|
||||
} @else if (isFilterActive() || hasSearchTerm()) {
|
||||
{{ computedFilterLabel() }}
|
||||
} @else {
|
||||
{{ t('labels.allBooks') }}
|
||||
}
|
||||
} @else if (entityType === EntityType.UNSHELVED) {
|
||||
{{ (isFilterActive() || hasSearchTerm()) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
|
||||
} @else {
|
||||
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive() || hasSearchTerm()) ? ' ' + t('labels.filteredSuffix') : '' }}
|
||||
}
|
||||
</p>
|
||||
@if (!showBooksLoadingPlaceholder() && seriesCollapseFilter.seriesCollapsed() && books(); as books) {
|
||||
<p class="series-collapsed-info">
|
||||
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (entityMenuTarget(); as menuTarget) {
|
||||
<div class="entity-menu-wrapper">
|
||||
<app-library-shelf-menu
|
||||
#entityMenu
|
||||
[target]="menuTarget"
|
||||
[ariaLabel]="'common.moreActionsFor' | transloco: {label: menuTarget.entity.name}" />
|
||||
@if (entityMenu.available()) {
|
||||
<button
|
||||
pButton
|
||||
type="button"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
[attr.aria-label]="'common.moreActionsFor' | transloco: {label: menuTarget.entity.name}"
|
||||
[appMenuTriggerFor]="entityMenu.menu()">
|
||||
<i class="pi pi-ellipsis-v" aria-hidden="true"></i>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<div class="toolbar-icons">
|
||||
@if (isFilterActive()) {
|
||||
<a class="toolbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
|
||||
<i
|
||||
class="pi pi-filter-slash filter-clear-icon"
|
||||
[pTooltip]="t('tooltip.clearFilters')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (currentViewMode() === 'table') {
|
||||
<div>
|
||||
<a class="toolbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
|
||||
<i
|
||||
class="pi pi-eye"
|
||||
[pTooltip]="t('tooltip.visibleColumns')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
<p-popover #columnPopover [dismissable]="true" appendTo="body">
|
||||
<div class="column-popover-content">
|
||||
<p-multiSelect
|
||||
optionLabel="header"
|
||||
[options]="columnPreferenceService.allColumns"
|
||||
[ngModel]="visibleColumns()"
|
||||
(ngModelChange)="onVisibleColumnsChange($event)"
|
||||
display="chip"
|
||||
[placeholder]="t('placeholder.selectColumns')"
|
||||
[style]="{ width: '100%' }"
|
||||
[filter]="true"
|
||||
[showClear]="true"
|
||||
></p-multiSelect>
|
||||
</div>
|
||||
<div class="column-popover-footer">
|
||||
<p>{{ t('labels.setAsDefault') }}</p>
|
||||
<p-button
|
||||
[label]="t('labels.save')"
|
||||
outlined
|
||||
size="small"
|
||||
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns())"></p-button>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
}
|
||||
<a class="toolbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
|
||||
<i
|
||||
[class]="viewIcon()"
|
||||
[pTooltip]="t('tooltip.toggleView')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
<div>
|
||||
<a
|
||||
class="toolbar-item"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
(click)="seriesCollapseOverlay.toggle($event)"
|
||||
(keydown.enter)="seriesCollapseOverlay.toggle($event)"
|
||||
[pTooltip]="'common.displaySettings' | transloco"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-cog"></i>
|
||||
</a>
|
||||
<p-popover
|
||||
#seriesCollapseOverlay
|
||||
[dismissable]="true"
|
||||
appendTo="body">
|
||||
<div class="display-settings-popover">
|
||||
<div class="display-settings-section">
|
||||
<div class="display-settings-checkbox-row">
|
||||
<p-checkbox
|
||||
inputId="collapse-series-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
|
||||
</p-checkbox>
|
||||
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="display-settings-section">
|
||||
<span class="display-settings-label">{{ 'common.cardSize' | transloco }}</span>
|
||||
<app-grid-density-buttons
|
||||
[smallerDisabled]="gridDensitySmallerDisabled()"
|
||||
[largerDisabled]="gridDensityLargerDisabled()"
|
||||
(densityChange)="adjustGridDensity($event)"/>
|
||||
</div>
|
||||
<div class="display-settings-section">
|
||||
<div class="display-settings-checkbox-row">
|
||||
<p-checkbox
|
||||
inputId="show-book-type-pill-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill()"
|
||||
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
|
||||
</p-checkbox>
|
||||
<label for="show-book-type-pill-checkbox" class="display-settings-label">{{ t('labels.bookTypeOverlay') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<div class="sort-button-wrapper">
|
||||
<a class="toolbar-item" role="button" tabindex="0" (click)="sortPopover.toggle($event)" (keydown.enter)="sortPopover.toggle($event)">
|
||||
<i
|
||||
class="pi pi-sort"
|
||||
[pTooltip]="t('tooltip.selectSorting')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
@if (sortCriteriaCount() > 1) {
|
||||
<p-badge [value]="sortCriteriaCount().toString()" class="sort-badge"/>
|
||||
}
|
||||
</a>
|
||||
<p-popover #sortPopover [dismissable]="true" appendTo="body">
|
||||
<app-multi-sort-popover
|
||||
[sortCriteria]="this.bookSorter.selectedSortCriteria"
|
||||
[availableSortOptions]="visibleSortOptions()"
|
||||
[showSaveButton]="canSaveSort()"
|
||||
(criteriaChange)="onSortCriteriaChange($event)"
|
||||
(saveSortConfig)="onSaveSortConfig($event)">
|
||||
</app-multi-sort-popover>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- MOBILE SEARCH (only visible below md) -->
|
||||
<div class="mobile-search-wrapper">
|
||||
<button
|
||||
type="button"
|
||||
class="toolbar-item"
|
||||
(click)="searchDropdown.toggle($event)"
|
||||
[pTooltip]="t('tooltip.search')"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<i class="pi pi-search"></i>
|
||||
</button>
|
||||
|
||||
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '21rem' }">
|
||||
<div class="search-popover-content">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[placeholder]="t('placeholder.search')"
|
||||
[ngModel]="bookTitle()"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
aria-label="{{ t('placeholder.search') }}"
|
||||
class="search-input-full"
|
||||
/>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="search-clear-btn"
|
||||
(click)="clearSearch(); searchDropdown.hide()"
|
||||
></p-button>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<div class="desktop-search-wrapper">
|
||||
<i class="pi pi-search search-icon"></i>
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[placeholder]="t('placeholder.search')"
|
||||
[ngModel]="bookTitle()"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
aria-label="{{ t('placeholder.search') }}"
|
||||
class="search-input"
|
||||
/>
|
||||
@if (bookTitle()) {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="search-clear-btn"
|
||||
(click)="clearSearch()"
|
||||
></p-button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<a class="toolbar-item" role="button" tabindex="0" (click)="toggleSidebar()" (keydown.enter)="toggleSidebar()">
|
||||
<i
|
||||
[ngClass]="showFilter() ? 'pi pi-filter-fill' : 'pi pi-filter'"
|
||||
[pTooltip]="t('tooltip.toggleSidebar')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="book-browser-body">
|
||||
<div class="book-browser-content">
|
||||
@if (booksError()) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
@switch (entityType()) {
|
||||
@case (EntityType.LIBRARY) {
|
||||
{{ t('labels.failedLibrary') }}
|
||||
}
|
||||
@case (EntityType.SHELF) {
|
||||
{{ t('labels.failedShelf') }}
|
||||
}
|
||||
@default {
|
||||
{{ t('labels.failedBooks') }}
|
||||
}
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
} @else {
|
||||
@let visibleBooks = books();
|
||||
@if (visibleBooks.length === 0 && !showBooksLoadingPlaceholder()) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
{{ t('labels.noBooks') }}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) {
|
||||
<app-book-table
|
||||
[books]="visibleBooks"
|
||||
[virtualRowCount]="virtualRowCount()"
|
||||
[loadedBookCount]="loadedBookCount()"
|
||||
[isFetchingNextPage]="isFetchingNextBooksPage()"
|
||||
[bookQueryToken]="bookQueryToken()"
|
||||
(selectAllRequested)="selectAllBooks()"
|
||||
(loadNextPage)="loadNextBooksPage()"
|
||||
[visibleColumns]="visibleColumns()"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary()"
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode() === 'grid') {
|
||||
<div #scrollElement class="virtual-scroller">
|
||||
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
|
||||
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
|
||||
@if (visibleBooks[virtualItem.index]; as book) {
|
||||
<div
|
||||
class="virtual-cell"
|
||||
[style.width.px]="virtualGrid.itemWidth()"
|
||||
[style.height.px]="virtualItem.size"
|
||||
[style.transform]="virtualGrid.itemTransform(virtualItem)">
|
||||
<app-book-card
|
||||
[index]="virtualItem.index"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[seriesViewEnabled]="seriesViewEnabled()"
|
||||
[onBookSelect]="onBookCardSelect"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="bookSelectionService.isBookSelected(book)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary()"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
} @else {
|
||||
<div
|
||||
class="virtual-cell virtual-loader-cell"
|
||||
[style.width.px]="virtualGrid.itemWidth()"
|
||||
[style.height.px]="virtualItem.size"
|
||||
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (userService.currentUser(); as currentUser) {
|
||||
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||
<div class="footer-content">
|
||||
<div class="footer-left">
|
||||
<div class="selected-count-badge">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span class="selected-count">{{ selectedCount() }}</span>
|
||||
<span class="selected-label">{{ t('labels.selected') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-center">
|
||||
@if (entityType(); as entityType) {
|
||||
<div class="action-buttons-group">
|
||||
@if (hasMetadataMenuItems()) {
|
||||
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
[pTooltip]="t('tooltip.metadataActions')"
|
||||
tooltipPosition="top"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
icon="pi pi-database">
|
||||
</p-button>
|
||||
}
|
||||
<p-button
|
||||
icon="pi pi-bookmark-fill"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(onClick)="openShelfAssigner()"
|
||||
[pTooltip]="t('tooltip.assignToShelf')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
@if (entityType === EntityType.SHELF) {
|
||||
<p-button
|
||||
icon="pi pi-bookmark"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(click)="unshelfBooks()"
|
||||
[pTooltip]="t('tooltip.removeFromShelf')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (currentUser.permissions.canBulkLockUnlockMetadata) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-lock"
|
||||
severity="info"
|
||||
(click)="lockUnlockMetadata()"
|
||||
[pTooltip]="t('tooltip.lockUnlockMetadata')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (currentUser.permissions.canMoveOrganizeFiles && appSettingsService.appSettings()?.diskType === 'LOCAL') {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-arrows-h"
|
||||
severity="info"
|
||||
(click)="moveFiles()"
|
||||
[pTooltip]="t('tooltip.organizeFiles')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-link"
|
||||
severity="info"
|
||||
(click)="attachFilesToBook()"
|
||||
[disabled]="!canAttachFiles()"
|
||||
[pTooltip]="t('tooltip.attachToBook')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (hasMoreActionsItems()) {
|
||||
<div class="more-actions-wrapper">
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
[pTooltip]="t('tooltip.moreActions')"
|
||||
tooltipPosition="top"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
icon="pi pi-ellipsis-v">
|
||||
</p-button>
|
||||
<p-tieredMenu #menu [model]="moreActionsMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="action-buttons-group">
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-check-square"
|
||||
severity="success"
|
||||
(click)="selectAllBooks()"
|
||||
[pTooltip]="t('tooltip.selectAll')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-times"
|
||||
severity="warn"
|
||||
(click)="deselectAllBooks()"
|
||||
[pTooltip]="t('tooltip.deselectAll')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
</div>
|
||||
@if (currentUser?.permissions?.admin || currentUser?.permissions?.canDeleteBook) {
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
(click)="confirmDeleteBooks()"
|
||||
[pTooltip]="t('tooltip.deleteSelected')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
<div class="footer-right"></div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (showFilter()) {
|
||||
<div
|
||||
class="mobile-filter-mask"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
(click)="toggleSidebar()"
|
||||
(keydown.enter)="toggleSidebar()">
|
||||
</div>
|
||||
}
|
||||
<app-book-filter
|
||||
[showFilter]="showFilter()"
|
||||
class="filter-overlay-container"
|
||||
[ngClass]="{ 'active': showFilter() }"
|
||||
[entity]="entity()"
|
||||
[entityType]="entityType()"
|
||||
[style.display]="showFilter() ? '' : 'none'"
|
||||
(filterSelected)="onFilterSelected($event)"
|
||||
(filterModeChanged)="onFilterModeChanged($event)">
|
||||
</app-book-filter>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</ng-container>
|
||||
@@ -1,520 +0,0 @@
|
||||
// Layout containers
|
||||
.book-browser-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.book-browser-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.book-browser-body {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
flex-direction: row;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.book-browser-content {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
// Header bar
|
||||
.book-browser-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.2188rem;
|
||||
padding: 0.3063rem;
|
||||
margin-right: 2px;
|
||||
flex-shrink: 0;
|
||||
background-color: var(--color-card);
|
||||
border-bottom: 1px solid var(--p-content-border-color);
|
||||
|
||||
@media (width >= 768px) {
|
||||
gap: 0.875rem;
|
||||
padding: 0.4375rem 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Entity info section
|
||||
.entity-info-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.entity-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1094rem;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
|
||||
@media (width <= 767px) {
|
||||
gap: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.entity-title {
|
||||
font-size: 1.0938rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin: 0;
|
||||
|
||||
@media (width <= 767px) {
|
||||
font-size: var(--app-text-base);
|
||||
padding-left: 0.2188rem;
|
||||
}
|
||||
}
|
||||
|
||||
.series-collapsed-info {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--color-text-secondary);
|
||||
margin: 0;
|
||||
|
||||
@media (width <= 767px) {
|
||||
display: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.entity-menu-wrapper {
|
||||
margin-left: 0.4375rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// Toolbar actions
|
||||
.toolbar-actions {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 0.2188rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
@media (width >= 768px) {
|
||||
gap: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.toolbar-icons {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 0.2188rem;
|
||||
|
||||
@media (width >= 768px) {
|
||||
gap: 1.3125rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Icon with orange color for filter
|
||||
.filter-clear-icon {
|
||||
color: orange;
|
||||
}
|
||||
|
||||
// Popover content containers
|
||||
.column-popover-content {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.column-popover-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
padding-top: 0.875rem;
|
||||
padding-left: 0.2188rem;
|
||||
}
|
||||
|
||||
.display-settings-popover {
|
||||
width: 220px;
|
||||
padding: 0.4375rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.875rem;
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.display-settings-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4375rem;
|
||||
}
|
||||
|
||||
.display-settings-checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
}
|
||||
|
||||
.display-settings-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
// Sort button wrapper
|
||||
.sort-button-wrapper {
|
||||
position: relative;
|
||||
|
||||
.sort-badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -6px;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort menu item (kept for backward compat)
|
||||
.sort-menu-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.4375rem 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
// Search section
|
||||
.mobile-search-wrapper {
|
||||
position: relative;
|
||||
|
||||
@media (width >= 768px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.desktop-search-wrapper {
|
||||
display: none;
|
||||
position: relative;
|
||||
|
||||
@media (width >= 768px) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.search-popover-content {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-input-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-clear-btn {
|
||||
position: absolute;
|
||||
right: 0.4375rem;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
// Footer bar
|
||||
.book-browser-footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 10%;
|
||||
right: 10%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
padding: 0.875rem 0.4375rem 0.4375rem;
|
||||
z-index: 1;
|
||||
border-radius: 10px 10px 0 0;
|
||||
border: 1px solid rgb(255 255 255 / 50%);
|
||||
border-width: 1px 1px 0;
|
||||
background-color: var(--color-card);
|
||||
transition: transform 0.15s ease-out, opacity 0.15s ease-out;
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
|
||||
&.footer-hidden {
|
||||
transform: translateY(100%);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (width <= 768px) {
|
||||
left: 0;
|
||||
right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.footer-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 0.4375rem;
|
||||
flex-shrink: 0;
|
||||
width: 120px;
|
||||
|
||||
@media (width <= 768px) {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-center {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
|
||||
padding: 0 16px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (width <= 768px) {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-right {
|
||||
flex-shrink: 0;
|
||||
width: 120px;
|
||||
|
||||
@media (width <= 768px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.selected-count-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.4375rem 0.875rem;
|
||||
font-size: 0.7875rem;
|
||||
color: var(--color-text);
|
||||
|
||||
i {
|
||||
font-size: var(--app-text-base);
|
||||
margin-right: 0.4375rem;
|
||||
}
|
||||
|
||||
@media (width <= 768px) {
|
||||
padding: 0.35rem 0.7rem;
|
||||
font-size: 0.7438rem;
|
||||
|
||||
i {
|
||||
font-size: 0.7875rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.selected-count {
|
||||
font-weight: 700;
|
||||
font-size: var(--app-text-base);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.selected-label {
|
||||
margin-left: 0.2188rem;
|
||||
}
|
||||
|
||||
.action-buttons-group {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 0.4375rem;
|
||||
|
||||
@media (width >= 768px) {
|
||||
gap: 1.3125rem;
|
||||
}
|
||||
}
|
||||
|
||||
.more-actions-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
// Virtual scroller and grid
|
||||
.virtual-scroller {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0.875rem;
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.virtual-loader-cell {
|
||||
border-radius: 8px;
|
||||
background: var(--p-content-border-color);
|
||||
animation: skeleton-pulse 1.5s ease-in-out infinite;
|
||||
pointer-events: none;
|
||||
will-change: opacity;
|
||||
}
|
||||
|
||||
@keyframes skeleton-pulse {
|
||||
0%, 100% { opacity: 0.3; }
|
||||
50% { opacity: 0.6; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.virtual-loader-cell {
|
||||
animation: none;
|
||||
will-change: auto;
|
||||
}
|
||||
}
|
||||
|
||||
// No books state
|
||||
.no-books-container {
|
||||
padding-top: 2.625rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.no-books-text {
|
||||
font-size: var(--app-text-base);
|
||||
font-weight: 500;
|
||||
color: var(--color-text);
|
||||
background: var(--color-card);
|
||||
padding: 0.6563rem 0.875rem;
|
||||
border-radius: 0.4375rem;
|
||||
}
|
||||
|
||||
// Toolbar actions (icon buttons)
|
||||
.toolbar-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--color-border);
|
||||
width: 2.1875rem;
|
||||
height: 2.1875rem;
|
||||
transition: outline-color 0.2s, border-color 0.2s;
|
||||
border-radius: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
outline-color: transparent;
|
||||
background-color: var(--color-card);
|
||||
cursor: pointer;
|
||||
|
||||
@media (width <= 767px) {
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
i, span {
|
||||
color: var(--color-primary);
|
||||
font-size: 1.0938rem;
|
||||
font-weight: 100;
|
||||
|
||||
@media (width <= 767px) {
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Search input styling
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 10px;
|
||||
transform: translateY(-50%);
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
min-width: 19.25rem;
|
||||
padding-left: 30px;
|
||||
height: 2.1875rem;
|
||||
line-height: 2.1875rem;
|
||||
font-size: var(--app-text-base);
|
||||
box-sizing: border-box;
|
||||
|
||||
@media (width <= 767px) {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Filter overlay (mobile sidebar)
|
||||
.mobile-filter-mask {
|
||||
@media (width <= 991px) {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 998;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgb(0 0 0 / 40%);
|
||||
}
|
||||
}
|
||||
|
||||
.filter-overlay-container {
|
||||
--book-filter-sidebar-width: 225px;
|
||||
|
||||
flex-shrink: 0;
|
||||
z-index: 50;
|
||||
|
||||
@media (width <= 991px) {
|
||||
width: var(--book-filter-sidebar-width);
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: 100%;
|
||||
background-color: var(--color-card);
|
||||
box-shadow: -2px 0 10px rgb(0 0 0 / 15%);
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
z-index: 1001;
|
||||
|
||||
&.active {
|
||||
transform: translateX(0);
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (width >= 992px) {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
|
||||
&:not(.active) {
|
||||
width: 0 !important;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
&.active {
|
||||
width: var(--book-filter-sidebar-width);
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
-509
@@ -1,509 +0,0 @@
|
||||
import {signal, WritableSignal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
||||
import {BehaviorSubject, Subject} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
|
||||
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||
import {BookMenuService} from '../../service/book-menu.service';
|
||||
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
|
||||
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
|
||||
import {BookSelectionService} from './book-selection.service';
|
||||
import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.service';
|
||||
import {BookBrowserEntityService} from './book-browser-entity.service';
|
||||
import {RouteScrollPositionService} from '../../../../shared/service/route-scroll-position.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {BookBrowserComponent, EntityType} from './book-browser.component';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LayoutService} from '../../../../shared/layout/layout.service';
|
||||
import {type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
|
||||
|
||||
function makeBook(id: number, libraryId: number, title: string, addedOn: string): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title,
|
||||
},
|
||||
addedOn,
|
||||
} as Book;
|
||||
}
|
||||
|
||||
function makeCurrentUser() {
|
||||
return {
|
||||
id: 1,
|
||||
username: 'tester',
|
||||
name: 'Tester',
|
||||
email: 'tester@example.com',
|
||||
locale: 'en',
|
||||
theme: 'grimmory',
|
||||
themeAccent: null,
|
||||
themeSyncEnabled: true,
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false,
|
||||
},
|
||||
userSettings: {
|
||||
filterMode: 'and',
|
||||
enableSeriesView: false,
|
||||
visibleSortFields: ['addedOn', 'title'],
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true,
|
||||
},
|
||||
overrides: [],
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
interface BookBrowserHarness {
|
||||
component: BookBrowserComponent;
|
||||
books: WritableSignal<Book[]>;
|
||||
booksError: WritableSignal<string | null>;
|
||||
isBooksLoading: WritableSignal<boolean>;
|
||||
paramMap$: BehaviorSubject<ParamMap>;
|
||||
setHasNextPage: (value: boolean) => void;
|
||||
setIsFetchingNextPage: (value: boolean) => void;
|
||||
queryParamsService: {
|
||||
shouldForceExpandSeries: ReturnType<typeof vi.fn>;
|
||||
updateViewMode: ReturnType<typeof vi.fn>;
|
||||
updateFilters: ReturnType<typeof vi.fn>;
|
||||
updateFilterMode: ReturnType<typeof vi.fn>;
|
||||
updateMultiSort: ReturnType<typeof vi.fn>;
|
||||
parseQueryParams: ReturnType<typeof vi.fn>;
|
||||
syncQueryParams: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
routeSnapshot: {
|
||||
routeConfig: {path: string};
|
||||
paramMap: ParamMap;
|
||||
queryParamMap: ParamMap;
|
||||
params: Record<string, string>;
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(options?: {
|
||||
books?: Book[];
|
||||
totalElements?: number;
|
||||
booksError?: string | null;
|
||||
isBooksLoading?: boolean;
|
||||
translate?: (key: string) => string;
|
||||
}): BookBrowserHarness {
|
||||
const books = signal<Book[]>(
|
||||
options?.books ?? [
|
||||
makeBook(2, 1, 'Zulu', '2024-02-01T00:00:00Z'),
|
||||
makeBook(1, 1, 'Alpha', '2024-01-01T00:00:00Z'),
|
||||
makeBook(3, 2, 'Bravo', '2024-03-01T00:00:00Z'),
|
||||
]
|
||||
);
|
||||
const booksError = signal<string | null>(options?.booksError ?? null);
|
||||
const isBooksLoading = signal<boolean>(options?.isBooksLoading ?? false);
|
||||
const isFetchingNextPage = signal(false);
|
||||
const hasNextPage = signal(false);
|
||||
const currentUser = signal(makeCurrentUser());
|
||||
const showFilter = signal(false);
|
||||
const seriesCollapsed = signal(false);
|
||||
const routerEvents$ = new Subject<unknown>();
|
||||
const paramMap$ = new BehaviorSubject(convertToParamMap({libraryId: '1'}));
|
||||
const queryParamMap$ = new BehaviorSubject(convertToParamMap({}));
|
||||
const url$ = new BehaviorSubject<unknown[]>([]);
|
||||
const defaultSort: SortOption = {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'};
|
||||
const queryParamsService = {
|
||||
parseQueryParams: vi.fn((_q, _u, _et, _ei, _sortOptions, defaultFilterMode) => ({
|
||||
viewMode: VIEW_MODES.GRID,
|
||||
sortOption: defaultSort,
|
||||
sortCriteria: [defaultSort],
|
||||
filters: {},
|
||||
filterMode: defaultFilterMode,
|
||||
viewModeFromToggle: false,
|
||||
})),
|
||||
syncQueryParams: vi.fn(),
|
||||
shouldForceExpandSeries: vi.fn(() => false),
|
||||
updateViewMode: vi.fn(),
|
||||
updateFilters: vi.fn(),
|
||||
updateFilterMode: vi.fn(),
|
||||
updateMultiSort: vi.fn(),
|
||||
};
|
||||
const routeSnapshot = {
|
||||
routeConfig: {path: 'library/:libraryId/books'},
|
||||
paramMap: paramMap$.value,
|
||||
queryParamMap: queryParamMap$.value,
|
||||
params: {libraryId: '1'},
|
||||
};
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SortService,
|
||||
BookSelectionService,
|
||||
BookNavigationService,
|
||||
{
|
||||
provide: UserService,
|
||||
useValue: {
|
||||
currentUser: currentUser.asReadonly(),
|
||||
getCurrentUser: vi.fn(() => currentUser()),
|
||||
updateUserSetting: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: CoverScalePreferenceService,
|
||||
useValue: {
|
||||
scaleFactor: vi.fn(() => 1),
|
||||
setScale: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TableColumnPreferenceService,
|
||||
useValue: {
|
||||
allColumns: [],
|
||||
visibleColumns: [],
|
||||
initPreferences: vi.fn(),
|
||||
saveVisibleColumns: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: SidebarFilterTogglePrefService,
|
||||
useValue: {
|
||||
showFilter: showFilter.asReadonly(),
|
||||
toggle: vi.fn(() => showFilter.update(value => !value)),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: SeriesCollapseFilter,
|
||||
useValue: {
|
||||
seriesCollapsed: seriesCollapsed.asReadonly(),
|
||||
setContext: vi.fn(),
|
||||
collapseBooks: vi.fn((items: Book[]) => items),
|
||||
setCollapsed: vi.fn((value: boolean) => seriesCollapsed.set(value)),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookSelectionService,
|
||||
useValue: {
|
||||
selectedBooks: signal([]),
|
||||
selectedCount: signal(0),
|
||||
deselectAll: vi.fn(),
|
||||
setCurrentBooks: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookNavigationService,
|
||||
useValue: {
|
||||
setAvailableBookIds: vi.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: RouteScrollPositionService,
|
||||
useValue: {
|
||||
createKey: vi.fn(() => 'test-key'),
|
||||
keyFor: vi.fn(() => 'test-key'),
|
||||
savePosition: vi.fn(),
|
||||
getPosition: vi.fn(() => 0),
|
||||
trackRoute: vi.fn(),
|
||||
},
|
||||
},
|
||||
{provide: ConfirmationService, useValue: {confirm: vi.fn()}},
|
||||
{provide: TaskHelperService, useValue: {}},
|
||||
{
|
||||
provide: BookCardOverlayPreferenceService,
|
||||
useValue: {
|
||||
showBookTypePill: vi.fn(() => true),
|
||||
setShowBookTypePill: vi.fn(),
|
||||
},
|
||||
},
|
||||
{provide: AppSettingsService, useValue: {appSettings: vi.fn(() => null)}},
|
||||
{provide: LayoutService, useValue: {isDesktop: signal(true), sidebarTransitioning: signal(false)}},
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: {
|
||||
url: url$.asObservable(),
|
||||
paramMap: paramMap$.asObservable(),
|
||||
queryParamMap: queryParamMap$.asObservable(),
|
||||
snapshot: routeSnapshot,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: Router,
|
||||
useValue: {
|
||||
events: routerEvents$.asObservable(),
|
||||
navigate: vi.fn(),
|
||||
},
|
||||
},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{
|
||||
provide: BookService,
|
||||
useValue: {
|
||||
books: books.asReadonly(),
|
||||
isBooksLoading: isBooksLoading.asReadonly(),
|
||||
booksError: booksError.asReadonly(),
|
||||
},
|
||||
},
|
||||
{provide: BookMetadataManageService, useValue: {}},
|
||||
{provide: BookDialogHelperService, useValue: {}},
|
||||
{
|
||||
provide: BookMenuService,
|
||||
useValue: {
|
||||
getMoreActionsMenu: vi.fn(() => []),
|
||||
getMetadataMenuItems: vi.fn(() => []),
|
||||
},
|
||||
},
|
||||
{provide: PageTitleService, useValue: {setPageTitle: vi.fn()}},
|
||||
{provide: LoadingService, useValue: {show: vi.fn(), hide: vi.fn()}},
|
||||
{provide: LocalStorageService, useValue: {get: vi.fn(), set: vi.fn()}},
|
||||
{
|
||||
provide: BookBrowserQueryParamsService,
|
||||
useValue: queryParamsService,
|
||||
},
|
||||
{
|
||||
provide: BookBrowserEntityService,
|
||||
useValue: {
|
||||
getEntityInfo: vi.fn((paramMap: ParamMap) => ({
|
||||
entityId: Number(paramMap.get('libraryId')),
|
||||
entityType: EntityType.LIBRARY,
|
||||
})),
|
||||
getEntity: vi.fn((entityId: number) => ({id: entityId, name: `Library ${entityId}`})),
|
||||
getBooksByEntity: vi.fn((items: Book[], entityId: number) =>
|
||||
items.filter(book => book.libraryId === entityId)
|
||||
),
|
||||
isLibrary: vi.fn(() => true),
|
||||
isMagicShelf: vi.fn(() => false),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: TranslocoService,
|
||||
useValue: {
|
||||
langChanges$: new Subject<string>().asObservable(),
|
||||
getActiveLang: vi.fn(() => 'en'),
|
||||
translate: vi.fn((key: string) => {
|
||||
if (options?.translate) {
|
||||
return options.translate(key);
|
||||
}
|
||||
|
||||
return {
|
||||
'book.browser.tooltip.toggleView': 'Toggle between Grid and Table view',
|
||||
'book.browser.labels.allBooks': 'All Books',
|
||||
'book.browser.labels.unshelvedBooks': 'Unshelved Books',
|
||||
}[key] ?? key;
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const component = TestBed.runInInjectionContext(() => new BookBrowserComponent());
|
||||
|
||||
return {
|
||||
component,
|
||||
books,
|
||||
booksError,
|
||||
isBooksLoading,
|
||||
paramMap$,
|
||||
setHasNextPage: value => hasNextPage.set(value),
|
||||
setIsFetchingNextPage: value => isFetchingNextPage.set(value),
|
||||
queryParamsService,
|
||||
routeSnapshot,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookBrowserComponent', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('switches view mode through the display settings control', () => {
|
||||
const {component, queryParamsService} = createHarness();
|
||||
|
||||
component.currentViewMode.set(VIEW_MODES.GRID);
|
||||
|
||||
component.onViewModeChange(VIEW_MODES.TABLE);
|
||||
|
||||
expect(component.currentViewMode()).toBe(VIEW_MODES.TABLE);
|
||||
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
|
||||
});
|
||||
|
||||
it('updates books when sorting changes', () => {
|
||||
const {component} = createHarness();
|
||||
|
||||
TestBed.flushEffects();
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(component.books().map(book => book.id)).toEqual([2, 1]);
|
||||
|
||||
component.applySortCriteria([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||
]);
|
||||
TestBed.flushEffects();
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(component.books().map(book => book.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('updates books after a context change', () => {
|
||||
const {component, paramMap$, routeSnapshot} = createHarness();
|
||||
|
||||
TestBed.flushEffects();
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(component.books().map(book => book.id)).toEqual([2, 1]);
|
||||
|
||||
routeSnapshot.paramMap = convertToParamMap({libraryId: '2'});
|
||||
routeSnapshot.params = {libraryId: '2'};
|
||||
paramMap$.next(routeSnapshot.paramMap);
|
||||
TestBed.flushEffects();
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(component.books().map(book => book.id)).toEqual([3]);
|
||||
});
|
||||
|
||||
it('hides loading placeholders when the books query is in an error state', () => {
|
||||
const {component} = createHarness({
|
||||
booksError: 'Failed to load books',
|
||||
isBooksLoading: true,
|
||||
});
|
||||
|
||||
expect(component.showBooksLoadingPlaceholder()).toBe(false);
|
||||
expect(component.showTableLoadingPlaceholder()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps rendered books visible when loading starts after the first render', () => {
|
||||
const renderedBooks = Array.from({length: 30}, (_, index) =>
|
||||
makeBook(index + 1, 1, `Book ${index + 1}`, `2024-01-${String(index + 1).padStart(2, '0')}T00:00:00Z`)
|
||||
);
|
||||
const {component, isBooksLoading} = createHarness({books: renderedBooks});
|
||||
|
||||
TestBed.flushEffects();
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
expect(component.books()).toHaveLength(30);
|
||||
expect(component.virtualRowCount()).toBe(30);
|
||||
|
||||
isBooksLoading.set(true);
|
||||
|
||||
expect(component.showBooksLoadingPlaceholder()).toBe(false);
|
||||
expect(component.virtualRowCount()).toBe(30);
|
||||
});
|
||||
|
||||
it('sizes grid loading placeholders to fill the viewport', () => {
|
||||
const {component} = createHarness({books: [], isBooksLoading: true});
|
||||
const loadingGrid = component as unknown as {
|
||||
minimumLoadingGridItemCount(metrics: VirtualGridMetrics): number;
|
||||
};
|
||||
|
||||
component.currentViewMode.set(VIEW_MODES.GRID);
|
||||
|
||||
expect(loadingGrid.minimumLoadingGridItemCount({
|
||||
viewportWidth: 960,
|
||||
viewportHeight: 900,
|
||||
columns: 6,
|
||||
itemHeight: 200,
|
||||
gap: 20,
|
||||
})).toBe(36);
|
||||
});
|
||||
|
||||
it('calls SeriesCollapseFilter.collapseBooks when computing books', () => {
|
||||
createHarness();
|
||||
const filter = TestBed.inject(SeriesCollapseFilter);
|
||||
const collapseBooksSpy = vi.spyOn(filter, 'collapseBooks');
|
||||
|
||||
vi.runOnlyPendingTimers();
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(collapseBooksSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.skip('uses the known total book count while more pages are available', () => {
|
||||
const {component, setHasNextPage} = createHarness({totalElements: 100});
|
||||
|
||||
setHasNextPage(true);
|
||||
|
||||
vi.runOnlyPendingTimers();
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.virtualRowCount()).toBe(100);
|
||||
expect(component.virtualGrid.virtualizer.options().count).toBe(100);
|
||||
});
|
||||
|
||||
it.skip('uses one unloaded slot for collapsed series while more pages are available', () => {
|
||||
const {component, setHasNextPage} = createHarness({totalElements: 100});
|
||||
const filter = TestBed.inject(SeriesCollapseFilter);
|
||||
filter.setCollapsed(true);
|
||||
setHasNextPage(true);
|
||||
|
||||
vi.runOnlyPendingTimers();
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.virtualRowCount()).toBe(component.books().length + 1);
|
||||
expect(component.virtualGrid.virtualizer.options().count).toBe(component.books().length + 1);
|
||||
});
|
||||
|
||||
it('uses the rendered book count once pagination is exhausted', () => {
|
||||
const {component} = createHarness();
|
||||
const filter = TestBed.inject(SeriesCollapseFilter);
|
||||
vi.mocked(filter.collapseBooks).mockImplementation((items: Book[]) => items.slice(0, 1));
|
||||
|
||||
vi.runOnlyPendingTimers();
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(component.books()).toHaveLength(1);
|
||||
expect(component.virtualRowCount()).toBe(1);
|
||||
expect(component.virtualGrid.virtualizer.options().count).toBe(1);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
-68
@@ -1,68 +0,0 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.filter'">
|
||||
<div class="book-filter-container">
|
||||
|
||||
<div class="filter-header">
|
||||
<span class="filter-title">{{ t('title') }}</span>
|
||||
<p-selectButton
|
||||
[options]="filterModeOptions"
|
||||
[ngModel]="selectedFilterMode()"
|
||||
(ngModelChange)="onFilterModeChange($event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-mode-select"
|
||||
allowEmpty="false"
|
||||
></p-selectButton>
|
||||
</div>
|
||||
|
||||
<div class="filter-content">
|
||||
<p-accordion [value]="expandedPanels()" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
|
||||
@for (filterType of visibleFilterTypes(); track filterType; let i = $index) {
|
||||
@if (filterSignals[filterType]().length > 0 || activeFilters()[filterType]?.length) {
|
||||
<p-accordion-panel [value]="i">
|
||||
<p-accordion-header>
|
||||
<span class="filter-type-label">
|
||||
<span class="filter-label-text">
|
||||
{{ getFilterLabel(filterType) }}
|
||||
</span>
|
||||
@if (activeFilters()[filterType]?.length; as count) {
|
||||
<span class="active-filter-count">
|
||||
({{ count }})
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
</p-accordion-header>
|
||||
|
||||
<p-accordion-content>
|
||||
@if (expandedPanels().includes(i)) {
|
||||
<cdk-virtual-scroll-viewport
|
||||
[itemSize]="28"
|
||||
[style.height.px]="getVirtualScrollHeight(filterSignals[filterType]().length)"
|
||||
class="filter-list">
|
||||
<div
|
||||
*cdkVirtualFor="let filter of filterSignals[filterType](); trackBy: trackByFilter"
|
||||
class="filter-row"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
[ngClass]="{
|
||||
'active': isActive(filterType, getFilterValueId(filter)),
|
||||
'active-not': isActive(filterType, getFilterValueId(filter)) && selectedFilterMode() === 'not'
|
||||
}"
|
||||
(click)="handleFilterClick(filterType, getFilterValueId(filter))"
|
||||
(keydown.enter)="handleFilterClick(filterType, getFilterValueId(filter))">
|
||||
<span class="filter-value-text">{{ getFilterValueDisplay(filter) }}</span>
|
||||
<p-badge class="filter-value-badge" [value]="filter.bookCount"></p-badge>
|
||||
</div>
|
||||
</cdk-virtual-scroll-viewport>
|
||||
}
|
||||
</p-accordion-content>
|
||||
</p-accordion-panel>
|
||||
}
|
||||
}
|
||||
</p-accordion>
|
||||
|
||||
<div class="footer-notice">
|
||||
{{ t('footerNote') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
:host ::ng-deep p-accordion {
|
||||
--p-accordion-header-padding: 0.525rem 0.875rem;
|
||||
--p-accordion-header-background: var(--color-card);
|
||||
--p-accordion-header-active-background: var(--color-card);
|
||||
--p-accordion-header-hover-background: var(--color-surface-hover);
|
||||
--p-accordion-header-active-hover-background: var(--color-surface-hover);
|
||||
--p-accordion-content-background: var(--color-card);
|
||||
}
|
||||
|
||||
:host ::ng-deep .p-accordionpanel {
|
||||
background: var(--color-card);
|
||||
}
|
||||
|
||||
:host ::ng-deep .p-togglebutton {
|
||||
--p-togglebutton-content-padding: 0.2188rem 0.3063rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep .cdk-virtual-scroll-orientation-vertical .cdk-virtual-scroll-content-wrapper {
|
||||
width: calc(var(--book-filter-sidebar-width, 225px) - 35px) !important;
|
||||
min-width: unset;
|
||||
}
|
||||
|
||||
.book-filter-container {
|
||||
height: 100%;
|
||||
border-radius: 0;
|
||||
overflow: hidden;
|
||||
background: var(--color-card);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-left: 1px solid var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.filter-header {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.875rem;
|
||||
border-bottom: 1px solid var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.filter-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.filter-mode-select {
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
|
||||
:host ::ng-deep .filter-mode-select .p-togglebutton-label {
|
||||
font-size: var(--app-text-xs);
|
||||
}
|
||||
|
||||
.filter-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding-bottom: 0.875rem;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.filter-type-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.2188rem;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-label-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 1;
|
||||
max-width: 175px;
|
||||
}
|
||||
|
||||
.active-filter-count {
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--color-primary);
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-list {
|
||||
padding-right: 0.2188rem;
|
||||
}
|
||||
|
||||
.filter-row {
|
||||
cursor: pointer;
|
||||
height: 26px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.4375rem;
|
||||
max-width: 97%;
|
||||
transition: color var(--transition-base);
|
||||
|
||||
&.active {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
&.active-not {
|
||||
color: var(--p-red-400);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-value-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-value-badge {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.truncation-notice {
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--color-text-secondary);
|
||||
text-align: center;
|
||||
padding-top: 0.4375rem;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.footer-notice {
|
||||
font-size: var(--app-text-xs);
|
||||
color: var(--color-text-secondary);
|
||||
text-align: center;
|
||||
padding-top: 0.875rem;
|
||||
padding-left: 0.875rem;
|
||||
padding-right: 0.875rem;
|
||||
margin-top: 0.4375rem;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around reset streams, user-setting effects,
|
||||
// and virtual-scroll accordion rendering so filter-mode changes and panel expansion can be
|
||||
// asserted without the full book-browser sidebar runtime.
|
||||
describe.skip('BookFilterComponent', () => {
|
||||
it('needs signal seams to verify visible filter hydration, mode changes, and emitted active-filter payloads', () => {
|
||||
// TODO(seam): Cover selectedFilterMode, setFilters, and emitFilters after the user-settings signal and filter service signals are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs UI-shell seams to verify reset handling, panel expansion, and multi-select filter clicks', () => {
|
||||
// TODO(seam): Cover handleFilterClick, clearActiveFilter, and accordion expansion after the virtual-scroll and select-button runtime is removed from the test surface.
|
||||
});
|
||||
});
|
||||
-208
@@ -1,208 +0,0 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal, Signal} from '@angular/core';
|
||||
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from '@openng/optimus-ui/accordion';
|
||||
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {Badge} from '@openng/optimus-ui/badge';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {SelectButton} from '@openng/optimus-ui/selectbutton';
|
||||
import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType} from '../../../../settings/user-management/user.service';
|
||||
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
|
||||
import {BookFilterService} from './book-filter.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||
import {EntityType} from '../book-browser.component';
|
||||
|
||||
interface FilterModeOption {
|
||||
label: string;
|
||||
value: BookFilterMode;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-filter',
|
||||
templateUrl: './book-filter.component.html',
|
||||
styleUrls: ['./book-filter.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
standalone: true,
|
||||
imports: [
|
||||
Accordion, AccordionPanel, AccordionHeader, AccordionContent,
|
||||
CdkVirtualScrollViewport, CdkFixedSizeVirtualScroll, CdkVirtualForOf,
|
||||
NgClass, Badge, FormsModule, SelectButton,
|
||||
TranslocoDirective
|
||||
]
|
||||
})
|
||||
export class BookFilterComponent {
|
||||
readonly showFilter = input(false);
|
||||
|
||||
readonly entity = input<Library | Shelf | MagicShelf | null>(null);
|
||||
readonly entityType = input<EntityType>(EntityType.ALL_BOOKS);
|
||||
|
||||
readonly filterSelected = output<Record<string, unknown> | null>();
|
||||
readonly filterModeChanged = output<BookFilterMode>();
|
||||
|
||||
private readonly filterService = inject(BookFilterService);
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
readonly activeFilters = signal<Record<string, unknown[]>>({});
|
||||
readonly expandedPanels = signal<number[]>([]);
|
||||
|
||||
private readonly visibleFilters = signal<VisibleFilterType[]>([...DEFAULT_VISIBLE_FILTERS]);
|
||||
|
||||
readonly visibleFilterTypes = computed(() => {
|
||||
const vf = this.visibleFilters();
|
||||
return vf.filter(f => this.filterTypes.includes(f as FilterType)) as FilterType[];
|
||||
});
|
||||
|
||||
readonly filterLabelKeys = FILTER_LABEL_KEYS;
|
||||
|
||||
readonly filterModeOptions: FilterModeOption[] = [
|
||||
{label: 'AND', value: 'and'},
|
||||
{label: 'OR', value: 'or'},
|
||||
{label: 'NOT', value: 'not'},
|
||||
{label: '1', value: 'single'}
|
||||
];
|
||||
|
||||
private readonly _selectedFilterMode = signal<BookFilterMode>('and');
|
||||
readonly selectedFilterMode = this._selectedFilterMode.asReadonly();
|
||||
|
||||
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
|
||||
this.entity,
|
||||
this.entityType,
|
||||
this.activeFilters,
|
||||
this.selectedFilterMode
|
||||
);
|
||||
get filterTypes(): FilterType[] {
|
||||
return Object.keys(this.filterSignals) as FilterType[];
|
||||
}
|
||||
|
||||
private readonly syncUserSettings = effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (!user) return;
|
||||
this.visibleFilters.set(user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS]);
|
||||
});
|
||||
|
||||
onFilterModeChange(mode: BookFilterMode): void {
|
||||
if (mode === this._selectedFilterMode()) return;
|
||||
this._selectedFilterMode.set(mode);
|
||||
this.filterModeChanged.emit(mode);
|
||||
this.emitFilters();
|
||||
}
|
||||
|
||||
getFilterLabel(type: FilterType): string {
|
||||
const key = this.filterLabelKeys[type];
|
||||
return key ? this.t.translate(key) : type;
|
||||
}
|
||||
|
||||
handleFilterClick(filterType: string, value: unknown): void {
|
||||
if (this._selectedFilterMode() === 'single') {
|
||||
this.handleSingleMode(filterType, value);
|
||||
} else {
|
||||
this.handleMultiMode(filterType, value);
|
||||
}
|
||||
this.emitFilters();
|
||||
}
|
||||
|
||||
setFilters(filters: Record<string, unknown>): void {
|
||||
const result: Record<string, unknown[]> = {};
|
||||
for (const [key, value] of Object.entries(filters)) {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
result[key] = values.map(v => this.filterService.processFilterValue(key, v));
|
||||
}
|
||||
this.activeFilters.set(result);
|
||||
this.emitFilters();
|
||||
}
|
||||
|
||||
clearActiveFilter(): void {
|
||||
this.activeFilters.set({});
|
||||
this.expandedPanels.set([]);
|
||||
this.filterSelected.emit(null);
|
||||
}
|
||||
|
||||
onExpandedPanelsChange(value: string | number | string[] | number[] | null | undefined): void {
|
||||
if (Array.isArray(value)) {
|
||||
const panels = value.map(Number);
|
||||
if (JSON.stringify(panels) !== JSON.stringify(this.expandedPanels())) {
|
||||
this.expandedPanels.set(panels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getVirtualScrollHeight(itemCount: number): number {
|
||||
return Math.min(itemCount * 28, 440);
|
||||
}
|
||||
|
||||
trackByFilter = (_: number, f: Filter): unknown => this.getFilterValueId(f);
|
||||
|
||||
getFilterValueId(f: Filter): unknown {
|
||||
const value = f.value;
|
||||
return typeof value === 'object' && value !== null && 'id' in value
|
||||
? value.id
|
||||
: f.value;
|
||||
}
|
||||
|
||||
getFilterValueDisplay(f: Filter): string {
|
||||
const value = f.value;
|
||||
if (typeof value === 'object' && value !== null && 'name' in value) {
|
||||
return String(value.name ?? '');
|
||||
}
|
||||
return String(value ?? '');
|
||||
}
|
||||
|
||||
isActive(filterType: string, filterId: unknown): boolean {
|
||||
const active = this.activeFilters()[filterType];
|
||||
if (!active) return false;
|
||||
return active.some(v => v === filterId || String(v) === String(filterId));
|
||||
}
|
||||
|
||||
private handleSingleMode(filterType: string, value: unknown): void {
|
||||
const id = this.extractId(value);
|
||||
const current = this.activeFilters()[filterType];
|
||||
const isSame = current?.length === 1 && this.valuesMatch(current[0], id);
|
||||
this.activeFilters.set(isSame ? {} : {[filterType]: [id]});
|
||||
}
|
||||
|
||||
private handleMultiMode(filterType: string, value: unknown): void {
|
||||
const id = this.extractId(value);
|
||||
const current = {...this.activeFilters()};
|
||||
const arr = [...(current[filterType] ?? [])];
|
||||
|
||||
const index = arr.findIndex(v => this.valuesMatch(v, id));
|
||||
if (index > -1) {
|
||||
arr.splice(index, 1);
|
||||
if (arr.length === 0) {
|
||||
delete current[filterType];
|
||||
} else {
|
||||
current[filterType] = arr;
|
||||
}
|
||||
} else {
|
||||
current[filterType] = [...arr, id];
|
||||
}
|
||||
this.activeFilters.set(current);
|
||||
}
|
||||
|
||||
private extractId(value: unknown): unknown {
|
||||
return typeof value === 'object' && value !== null && 'id' in value
|
||||
? (value as {id: unknown}).id
|
||||
: value;
|
||||
}
|
||||
|
||||
private valuesMatch(a: unknown, b: unknown): boolean {
|
||||
return a === b || String(a) === String(b);
|
||||
}
|
||||
|
||||
private emitFilters(): void {
|
||||
const filters = this.activeFilters();
|
||||
const hasFilters = Object.keys(filters).length > 0;
|
||||
this.filterSelected.emit(hasFilters ? {...filters} : null);
|
||||
|
||||
// Update expanded panels to show panels with active filters
|
||||
const panels = new Set<number>();
|
||||
const types = this.visibleFilterTypes();
|
||||
types.forEach((type, i) => {
|
||||
if (filters[type]?.length) panels.add(i);
|
||||
});
|
||||
this.expandedPanels.set([...panels]);
|
||||
}
|
||||
}
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {
|
||||
CONTENT_RATING_LABELS,
|
||||
FILTER_CONFIGS,
|
||||
FILTER_EXTRACTORS,
|
||||
FILTER_LABEL_KEYS,
|
||||
MATCH_SCORE_RANGES,
|
||||
NUMERIC_ID_FILTER_TYPES,
|
||||
RATING_OPTIONS_10,
|
||||
READ_STATUS_LABELS
|
||||
} from './book-filter.config';
|
||||
|
||||
const makeBook = (overrides: Partial<Book> = {}): Book => ({
|
||||
id: 1,
|
||||
libraryId: 9,
|
||||
libraryName: 'Main',
|
||||
...overrides
|
||||
});
|
||||
|
||||
describe('book-filter.config', () => {
|
||||
it('covers every read status with a label', () => {
|
||||
expect(READ_STATUS_LABELS[ReadStatus.UNREAD]).toBe('Unread');
|
||||
expect(READ_STATUS_LABELS[ReadStatus.UNSET]).toBe('Unset');
|
||||
expect(Object.keys(READ_STATUS_LABELS)).toHaveLength(Object.keys(ReadStatus).length);
|
||||
});
|
||||
|
||||
it('defines 10 one-step rating buckets', () => {
|
||||
expect(RATING_OPTIONS_10).toHaveLength(10);
|
||||
expect(RATING_OPTIONS_10[0]).toMatchObject({id: 1, label: '1', min: 1, max: 2, sortIndex: 0});
|
||||
expect(RATING_OPTIONS_10.at(-1)).toMatchObject({id: 10, label: '10', min: 10, max: 11, sortIndex: 9});
|
||||
});
|
||||
|
||||
it('keeps filter labels and configs aligned', () => {
|
||||
const configKeys = Object.keys(FILTER_CONFIGS).sort();
|
||||
const labelKeysWithoutLibrary = Object.keys(FILTER_LABEL_KEYS).filter((key) => key !== 'library').sort();
|
||||
|
||||
expect(labelKeysWithoutLibrary).toEqual(configKeys);
|
||||
expect(FILTER_LABEL_KEYS.library).toBe('book.filter.labels.library');
|
||||
expect(NUMERIC_ID_FILTER_TYPES.has('pageCount')).toBe(true);
|
||||
expect(NUMERIC_ID_FILTER_TYPES.has('author')).toBe(false);
|
||||
});
|
||||
|
||||
it('normalizes read status, metadata match score, and content ratings', () => {
|
||||
expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: ReadStatus.READING}))).toEqual([
|
||||
{id: ReadStatus.READING, name: 'Reading'}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.readStatus(makeBook({readStatus: 'INVALID' as ReadStatus}))).toEqual([
|
||||
{id: ReadStatus.UNSET, name: 'Unset'}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.matchScore(makeBook({metadataMatchScore: 92}))).toEqual([
|
||||
{id: MATCH_SCORE_RANGES[1].id, name: MATCH_SCORE_RANGES[1].label, sortIndex: MATCH_SCORE_RANGES[1].sortIndex}
|
||||
]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.contentRating(makeBook({
|
||||
metadata: {bookId: 1, contentRating: 'EVERYONE'}
|
||||
}))).toEqual([{id: 'EVERYONE', name: CONTENT_RATING_LABELS['EVERYONE']}]);
|
||||
|
||||
expect(FILTER_EXTRACTORS.ageRating(makeBook({
|
||||
metadata: {bookId: 1, ageRating: 12}
|
||||
}))).toEqual([{id: 10, name: '10+', sortIndex: 2}]);
|
||||
});
|
||||
|
||||
it('builds comic creator filters with role-aware labels', () => {
|
||||
const filters = FILTER_EXTRACTORS.comicCreator(makeBook({
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
comicMetadata: {
|
||||
pencillers: ['Jane Artist'],
|
||||
editors: ['Max Editor']
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
expect(filters).toEqual([
|
||||
{id: 'Jane Artist:penciller', name: 'Jane Artist (Penciller)'},
|
||||
{id: 'Max Editor:editor', name: 'Max Editor (Editor)'}
|
||||
]);
|
||||
});
|
||||
});
|
||||
-383
@@ -1,383 +0,0 @@
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
|
||||
// ============================================================================
|
||||
// TYPES
|
||||
// ============================================================================
|
||||
|
||||
export interface FilterValue {
|
||||
id?: string | number;
|
||||
name?: string;
|
||||
sortIndex?: number;
|
||||
}
|
||||
|
||||
export interface Filter<T extends FilterValue = FilterValue> {
|
||||
value: T;
|
||||
bookCount: number;
|
||||
}
|
||||
|
||||
export type FilterType =
|
||||
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
|
||||
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
|
||||
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
|
||||
| 'goodreadsRating' | 'hardcoverRating' | 'lubimyczytacRating' | 'ranobedbRating'
|
||||
| 'audibleRating' | 'language' | 'pageCount' | 'mood'
|
||||
| 'ageRating' | 'contentRating'
|
||||
| 'narrator'
|
||||
| 'comicCharacter' | 'comicTeam' | 'comicLocation' | 'comicCreator';
|
||||
|
||||
export type SortMode = 'count' | 'sortIndex';
|
||||
|
||||
export interface RangeConfig {
|
||||
id: number;
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
sortIndex: number;
|
||||
}
|
||||
|
||||
export interface FilterConfig {
|
||||
label: string;
|
||||
extractor: (book: Book) => FilterValue[];
|
||||
sortMode: SortMode;
|
||||
isNumericId?: boolean;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CONSTANTS
|
||||
// ============================================================================
|
||||
|
||||
export const READ_STATUS_LABELS: Readonly<Record<ReadStatus, string>> = {
|
||||
[ReadStatus.UNREAD]: 'Unread',
|
||||
[ReadStatus.READING]: 'Reading',
|
||||
[ReadStatus.RE_READING]: 'Re-reading',
|
||||
[ReadStatus.PARTIALLY_READ]: 'Partially Read',
|
||||
[ReadStatus.PAUSED]: 'Paused',
|
||||
[ReadStatus.READ]: 'Read',
|
||||
[ReadStatus.WONT_READ]: 'Won\'t Read',
|
||||
[ReadStatus.ABANDONED]: 'Abandoned',
|
||||
[ReadStatus.UNSET]: 'Unset'
|
||||
};
|
||||
|
||||
export const RATING_RANGES_5: readonly RangeConfig[] = [
|
||||
{id: 0, label: '0 to 1', min: 0, max: 1, sortIndex: 0},
|
||||
{id: 1, label: '1 to 2', min: 1, max: 2, sortIndex: 1},
|
||||
{id: 2, label: '2 to 3', min: 2, max: 3, sortIndex: 2},
|
||||
{id: 3, label: '3 to 4', min: 3, max: 4, sortIndex: 3},
|
||||
{id: 4, label: '4 to 4.5', min: 4, max: 4.5, sortIndex: 4},
|
||||
{id: 5, label: '4.5+', min: 4.5, max: Infinity, sortIndex: 5}
|
||||
];
|
||||
|
||||
export const RATING_OPTIONS_10: readonly RangeConfig[] = Array.from({length: 10}, (_, i) => ({
|
||||
id: i + 1,
|
||||
label: `${i + 1}`,
|
||||
min: i + 1,
|
||||
max: i + 2,
|
||||
sortIndex: i
|
||||
}));
|
||||
|
||||
export const FILE_SIZE_RANGES: readonly RangeConfig[] = [
|
||||
{id: 0, label: '< 1 MB', min: 0, max: 1024, sortIndex: 0},
|
||||
{id: 1, label: '1–10 MB', min: 1024, max: 10240, sortIndex: 1},
|
||||
{id: 2, label: '10–50 MB', min: 10240, max: 51200, sortIndex: 2},
|
||||
{id: 3, label: '50–100 MB', min: 51200, max: 102400, sortIndex: 3},
|
||||
{id: 4, label: '100–500 MB', min: 102400, max: 512000, sortIndex: 4},
|
||||
{id: 5, label: '0.5–1 GB', min: 512000, max: 1048576, sortIndex: 5},
|
||||
{id: 6, label: '1–2 GB', min: 1048576, max: 2097152, sortIndex: 6},
|
||||
{id: 7, label: '2+ GB', min: 2097152, max: Infinity, sortIndex: 7}
|
||||
];
|
||||
|
||||
export const PAGE_COUNT_RANGES: readonly RangeConfig[] = [
|
||||
{id: 0, label: '< 50 pages', min: 0, max: 50, sortIndex: 0},
|
||||
{id: 1, label: '50–100 pages', min: 50, max: 100, sortIndex: 1},
|
||||
{id: 2, label: '100–200 pages', min: 100, max: 200, sortIndex: 2},
|
||||
{id: 3, label: '200–400 pages', min: 200, max: 400, sortIndex: 3},
|
||||
{id: 4, label: '400–600 pages', min: 400, max: 600, sortIndex: 4},
|
||||
{id: 5, label: '600–1000 pages', min: 600, max: 1000, sortIndex: 5},
|
||||
{id: 6, label: '1000+ pages', min: 1000, max: Infinity, sortIndex: 6}
|
||||
];
|
||||
|
||||
export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [
|
||||
{id: 0, min: 0.95, max: 1.01, label: 'Outstanding (95–100%)', sortIndex: 0},
|
||||
{id: 1, min: 0.90, max: 0.95, label: 'Excellent (90–94%)', sortIndex: 1},
|
||||
{id: 2, min: 0.80, max: 0.90, label: 'Great (80–89%)', sortIndex: 2},
|
||||
{id: 3, min: 0.70, max: 0.80, label: 'Good (70–79%)', sortIndex: 3},
|
||||
{id: 4, min: 0.50, max: 0.70, label: 'Fair (50–69%)', sortIndex: 4},
|
||||
{id: 5, min: 0.30, max: 0.50, label: 'Weak (30–49%)', sortIndex: 5},
|
||||
{id: 6, min: 0.00, max: 0.30, label: 'Poor (0–29%)', sortIndex: 6}
|
||||
];
|
||||
|
||||
export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [
|
||||
{id: 0, min: 0, max: 6, label: 'All Ages', sortIndex: 0},
|
||||
{id: 6, min: 6, max: 10, label: '6+', sortIndex: 1},
|
||||
{id: 10, min: 10, max: 13, label: '10+', sortIndex: 2},
|
||||
{id: 13, min: 13, max: 16, label: '13+', sortIndex: 3},
|
||||
{id: 16, min: 16, max: 18, label: '16+', sortIndex: 4},
|
||||
{id: 18, min: 18, max: 21, label: '18+', sortIndex: 5},
|
||||
{id: 21, min: 21, max: Infinity, label: '21+', sortIndex: 6}
|
||||
];
|
||||
|
||||
export const CONTENT_RATING_LABELS: Readonly<Record<string, string>> = {
|
||||
'EVERYONE': 'Everyone',
|
||||
'TEEN': 'Teen',
|
||||
'MATURE': 'Mature',
|
||||
'ADULT': 'Adult',
|
||||
'EXPLICIT': 'Explicit'
|
||||
};
|
||||
|
||||
export const readStatusLabels = READ_STATUS_LABELS;
|
||||
export const ratingRanges = RATING_RANGES_5;
|
||||
export const ratingOptions10 = RATING_OPTIONS_10;
|
||||
export const fileSizeRanges = FILE_SIZE_RANGES;
|
||||
export const pageCountRanges = PAGE_COUNT_RANGES;
|
||||
export const matchScoreRanges = MATCH_SCORE_RANGES;
|
||||
export const ageRatingRanges = AGE_RATING_OPTIONS;
|
||||
|
||||
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
|
||||
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
|
||||
'goodreadsRating', 'hardcoverRating', 'lubimyczytacRating', 'ranobedbRating',
|
||||
'audibleRating', 'pageCount', 'library', 'shelf',
|
||||
'ageRating'
|
||||
]);
|
||||
|
||||
export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
|
||||
author: 'Author',
|
||||
category: 'Genre',
|
||||
series: 'Series',
|
||||
bookType: 'File Format',
|
||||
readStatus: 'Read Status',
|
||||
personalRating: 'Personal Rating',
|
||||
publisher: 'Publisher',
|
||||
matchScore: 'Metadata Match Score',
|
||||
library: 'Library',
|
||||
shelf: 'Shelf',
|
||||
shelfStatus: 'Shelf Status',
|
||||
tag: 'Tag',
|
||||
publishedDate: 'Published Year',
|
||||
fileSize: 'File Size',
|
||||
amazonRating: 'Amazon Rating',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
lubimyczytacRating: 'Lubimyczytac Rating',
|
||||
ranobedbRating: 'RanobeDB Rating',
|
||||
audibleRating: 'Audible Rating',
|
||||
language: 'Language',
|
||||
pageCount: 'Page Count',
|
||||
mood: 'Mood',
|
||||
ageRating: 'Age Rating',
|
||||
contentRating: 'Content Rating',
|
||||
narrator: 'Narrator',
|
||||
comicCharacter: 'Comic Character',
|
||||
comicTeam: 'Comic Team',
|
||||
comicLocation: 'Comic Location',
|
||||
comicCreator: 'Comic Creator'
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// FILTER EXTRACTORS
|
||||
// ============================================================================
|
||||
|
||||
const findInRange = (value: number | null | undefined, ranges: readonly RangeConfig[]): FilterValue[] => {
|
||||
if (value == null) return [];
|
||||
const match = ranges.find(r => value >= r.min && value < r.max);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
};
|
||||
|
||||
const findExactRating10 = (rating: number | undefined): FilterValue[] => {
|
||||
if (!rating || rating < 1 || rating > 10) return [];
|
||||
const match = RATING_OPTIONS_10.find(r => r.id === rating);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
};
|
||||
|
||||
const normalizeMatchScore = (score: number | null | undefined): number | null => {
|
||||
if (score == null) return null;
|
||||
return score > 1 ? score / 100 : score;
|
||||
};
|
||||
|
||||
const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] =>
|
||||
values?.map(name => ({id: name, name})) ?? [];
|
||||
|
||||
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
|
||||
value ? [{id: value, name: value}] : [];
|
||||
|
||||
let languageDisplayName: (raw: string) => string = raw => raw;
|
||||
|
||||
export function registerLanguageDisplayName(resolver: (raw: string) => string): void {
|
||||
languageDisplayName = resolver;
|
||||
}
|
||||
|
||||
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
|
||||
author: (book) => extractStringsAsFilters(book.metadata?.authors),
|
||||
category: (book) => extractStringsAsFilters(book.metadata?.categories),
|
||||
series: (book) => extractSingleString(book.metadata?.seriesName?.trim()),
|
||||
bookType: (book) => book.isPhysical ? [{id: 'PHYSICAL', name: 'PHYSICAL'}] : extractSingleString(book.primaryFile?.bookType),
|
||||
readStatus: (book) => {
|
||||
const status = book.readStatus ?? ReadStatus.UNSET;
|
||||
const validStatus = status in READ_STATUS_LABELS ? status : ReadStatus.UNSET;
|
||||
return [{id: validStatus, name: READ_STATUS_LABELS[validStatus]}];
|
||||
},
|
||||
personalRating: (book) => findExactRating10(book.personalRating ?? undefined),
|
||||
publisher: (book) => extractSingleString(book.metadata?.publisher),
|
||||
matchScore: (book) => findInRange(normalizeMatchScore(book.metadataMatchScore), MATCH_SCORE_RANGES),
|
||||
shelf: (book) => book.shelves?.map(s => ({id: s.id, name: s.name})) ?? [],
|
||||
shelfStatus: (book) => {
|
||||
const isShelved = (book.shelves?.length ?? 0) > 0;
|
||||
return [{id: isShelved ? 'shelved' : 'unshelved', name: isShelved ? 'Shelved' : 'Unshelved'}];
|
||||
},
|
||||
tag: (book) => extractStringsAsFilters(book.metadata?.tags),
|
||||
publishedDate: (book) => {
|
||||
const date = book.metadata?.publishedDate;
|
||||
if (!date) return [];
|
||||
const year = new Date(date).getFullYear().toString();
|
||||
return [{id: year, name: year}];
|
||||
},
|
||||
fileSize: (book) => findInRange(book.fileSizeKb, FILE_SIZE_RANGES),
|
||||
amazonRating: (book) => findInRange(book.metadata?.amazonRating, RATING_RANGES_5),
|
||||
goodreadsRating: (book) => findInRange(book.metadata?.goodreadsRating, RATING_RANGES_5),
|
||||
hardcoverRating: (book) => findInRange(book.metadata?.hardcoverRating, RATING_RANGES_5),
|
||||
lubimyczytacRating: (book) => findInRange(book.metadata?.lubimyczytacRating, RATING_RANGES_5),
|
||||
ranobedbRating: (book) => findInRange(book.metadata?.ranobedbRating, RATING_RANGES_5),
|
||||
audibleRating: (book) => findInRange(book.metadata?.audibleRating, RATING_RANGES_5),
|
||||
language: (book) => {
|
||||
const language = book.metadata?.language;
|
||||
return language ? [{id: language, name: languageDisplayName(language)}] : [];
|
||||
},
|
||||
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
|
||||
mood: (book) => extractStringsAsFilters(book.metadata?.moods),
|
||||
ageRating: (book) => findInRange(book.metadata?.ageRating, AGE_RATING_OPTIONS),
|
||||
contentRating: (book) => {
|
||||
const rating = book.metadata?.contentRating;
|
||||
if (!rating) return [];
|
||||
const label = CONTENT_RATING_LABELS[rating] ?? rating;
|
||||
return [{id: rating, name: label}];
|
||||
},
|
||||
narrator: (book) => extractSingleString(book.metadata?.narrator),
|
||||
comicCharacter: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.characters),
|
||||
comicTeam: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.teams),
|
||||
comicLocation: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.locations),
|
||||
comicCreator: (book) => {
|
||||
const comic = book.metadata?.comicMetadata;
|
||||
if (!comic) return [];
|
||||
const creators: FilterValue[] = [];
|
||||
const roleLabels: Record<string, string> = {
|
||||
penciller: 'Penciller', inker: 'Inker', colorist: 'Colorist',
|
||||
letterer: 'Letterer', coverArtist: 'Cover Artist', editor: 'Editor'
|
||||
};
|
||||
const roles: [string[] | undefined, string][] = [
|
||||
[comic.pencillers, 'penciller'],
|
||||
[comic.inkers, 'inker'],
|
||||
[comic.colorists, 'colorist'],
|
||||
[comic.letterers, 'letterer'],
|
||||
[comic.coverArtists, 'coverArtist'],
|
||||
[comic.editors, 'editor']
|
||||
];
|
||||
for (const [names, role] of roles) {
|
||||
if (names) {
|
||||
for (const name of names) {
|
||||
creators.push({id: `${name}:${role}`, name: `${name} (${roleLabels[role]})`});
|
||||
}
|
||||
}
|
||||
}
|
||||
return creators;
|
||||
}
|
||||
};
|
||||
|
||||
// Translation key for each FilterType — used by UI components to translate filter labels
|
||||
export const FILTER_LABEL_KEYS: Readonly<Record<FilterType, string>> = {
|
||||
author: 'book.filter.labels.author',
|
||||
category: 'book.filter.labels.category',
|
||||
series: 'book.filter.labels.series',
|
||||
bookType: 'book.filter.labels.bookType',
|
||||
readStatus: 'book.filter.labels.readStatus',
|
||||
personalRating: 'book.filter.labels.personalRating',
|
||||
publisher: 'book.filter.labels.publisher',
|
||||
matchScore: 'book.filter.labels.matchScore',
|
||||
library: 'book.filter.labels.library',
|
||||
shelf: 'book.filter.labels.shelf',
|
||||
shelfStatus: 'book.filter.labels.shelfStatus',
|
||||
tag: 'book.filter.labels.tag',
|
||||
publishedDate: 'book.filter.labels.publishedDate',
|
||||
fileSize: 'book.filter.labels.fileSize',
|
||||
amazonRating: 'book.filter.labels.amazonRating',
|
||||
goodreadsRating: 'book.filter.labels.goodreadsRating',
|
||||
hardcoverRating: 'book.filter.labels.hardcoverRating',
|
||||
lubimyczytacRating: 'book.filter.labels.lubimyczytacRating',
|
||||
ranobedbRating: 'book.filter.labels.ranobedbRating',
|
||||
audibleRating: 'book.filter.labels.audibleRating',
|
||||
language: 'book.filter.labels.language',
|
||||
pageCount: 'book.filter.labels.pageCount',
|
||||
mood: 'book.filter.labels.mood',
|
||||
ageRating: 'book.filter.labels.ageRating',
|
||||
contentRating: 'book.filter.labels.contentRating',
|
||||
narrator: 'book.filter.labels.narrator',
|
||||
comicCharacter: 'book.filter.labels.comicCharacter',
|
||||
comicTeam: 'book.filter.labels.comicTeam',
|
||||
comicLocation: 'book.filter.labels.comicLocation',
|
||||
comicCreator: 'book.filter.labels.comicCreator'
|
||||
};
|
||||
|
||||
export const READ_STATUS_LABEL_KEYS: Readonly<Record<ReadStatus, string>> = {
|
||||
[ReadStatus.UNREAD]: 'book.filter.readStatus.unread',
|
||||
[ReadStatus.READING]: 'book.filter.readStatus.reading',
|
||||
[ReadStatus.RE_READING]: 'book.filter.readStatus.reReading',
|
||||
[ReadStatus.PARTIALLY_READ]: 'book.filter.readStatus.partiallyRead',
|
||||
[ReadStatus.PAUSED]: 'book.filter.readStatus.paused',
|
||||
[ReadStatus.READ]: 'book.filter.readStatus.read',
|
||||
[ReadStatus.WONT_READ]: 'book.filter.readStatus.wontRead',
|
||||
[ReadStatus.ABANDONED]: 'book.filter.readStatus.abandoned',
|
||||
[ReadStatus.UNSET]: 'book.filter.readStatus.unset'
|
||||
};
|
||||
|
||||
export const CONTENT_RATING_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
'EVERYONE': 'book.filter.contentRating.everyone',
|
||||
'TEEN': 'book.filter.contentRating.teen',
|
||||
'MATURE': 'book.filter.contentRating.mature',
|
||||
'ADULT': 'book.filter.contentRating.adult',
|
||||
'EXPLICIT': 'book.filter.contentRating.explicit'
|
||||
};
|
||||
|
||||
export const SHELF_STATUS_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
'shelved': 'book.filter.shelfStatus.shelved',
|
||||
'unshelved': 'book.filter.shelfStatus.unshelved'
|
||||
};
|
||||
|
||||
|
||||
export const COMIC_ROLE_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
penciller: 'book.filter.comicRoles.penciller',
|
||||
inker: 'book.filter.comicRoles.inker',
|
||||
colorist: 'book.filter.comicRoles.colorist',
|
||||
letterer: 'book.filter.comicRoles.letterer',
|
||||
coverArtist: 'book.filter.comicRoles.coverArtist',
|
||||
editor: 'book.filter.comicRoles.editor'
|
||||
};
|
||||
|
||||
export const FILTER_CONFIGS: Readonly<Record<Exclude<FilterType, 'library'>, Omit<FilterConfig, 'extractor'>>> = {
|
||||
author: {label: 'Author', sortMode: 'count'},
|
||||
category: {label: 'Genre', sortMode: 'count'},
|
||||
series: {label: 'Series', sortMode: 'count'},
|
||||
bookType: {label: 'Book Type', sortMode: 'count'},
|
||||
readStatus: {label: 'Read Status', sortMode: 'count'},
|
||||
personalRating: {label: 'Personal Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
publisher: {label: 'Publisher', sortMode: 'count'},
|
||||
matchScore: {label: 'Metadata Match Score', sortMode: 'sortIndex', isNumericId: true},
|
||||
shelf: {label: 'Shelf', sortMode: 'count', isNumericId: true},
|
||||
shelfStatus: {label: 'Shelf Status', sortMode: 'count'},
|
||||
tag: {label: 'Tag', sortMode: 'count'},
|
||||
publishedDate: {label: 'Published Year', sortMode: 'count'},
|
||||
fileSize: {label: 'File Size', sortMode: 'sortIndex', isNumericId: true},
|
||||
amazonRating: {label: 'Amazon Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
goodreadsRating: {label: 'Goodreads Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
hardcoverRating: {label: 'Hardcover Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
lubimyczytacRating: {label: 'Lubimyczytac Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
ranobedbRating: {label: 'RanobeDB Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
audibleRating: {label: 'Audible Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
language: {label: 'Language', sortMode: 'count'},
|
||||
pageCount: {label: 'Page Count', sortMode: 'sortIndex', isNumericId: true},
|
||||
mood: {label: 'Mood', sortMode: 'count'},
|
||||
ageRating: {label: 'Age Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
contentRating: {label: 'Content Rating', sortMode: 'count'},
|
||||
narrator: {label: 'Narrator', sortMode: 'count'},
|
||||
comicCharacter: {label: 'Comic Character', sortMode: 'count'},
|
||||
comicTeam: {label: 'Comic Team', sortMode: 'count'},
|
||||
comicLocation: {label: 'Comic Location', sortMode: 'count'},
|
||||
comicCreator: {label: 'Comic Creator', sortMode: 'count'}
|
||||
};
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around the live book, library, and
|
||||
// magic-shelf signal graph so dynamic filter aggregation can be asserted without recreating the
|
||||
// full sidebar filter runtime and evaluator dependencies.
|
||||
describe.skip('BookFilterService', () => {
|
||||
it('needs signal seams to verify library, shelf, and magic-shelf entity filtering across active sidebar filters', () => {
|
||||
// TODO(seam): Cover createFilterSignals and filterBooksByEntity once the dependent signals and evaluator service are isolated behind deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs aggregation seams to verify filter count sorting, numeric-id coercion, and invalid magic-shelf fallback handling', () => {
|
||||
// TODO(seam): Cover buildAndSortFilters, processFilterValue, and filterByMagicShelf after extractor inputs and service state are exposed through a stable harness.
|
||||
});
|
||||
});
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
import {computed, inject, Injectable, Signal} from '@angular/core';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {LibraryService} from '../../../service/library.service';
|
||||
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
|
||||
import {EntityType} from '../book-browser.component';
|
||||
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, registerLanguageDisplayName, SortMode} from './book-filter.config';
|
||||
import {filterBooksByFilters} from '../filters/sidebar-filter';
|
||||
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
||||
import {LanguageResolverService} from '../../../../../shared/service/language-resolver.service';
|
||||
|
||||
const MAX_FILTER_ITEMS = 100;
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookFilterService {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryService = inject(LibraryService);
|
||||
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
private readonly languageResolver = inject(LanguageResolverService);
|
||||
|
||||
constructor() {
|
||||
registerLanguageDisplayName(raw => this.languageResolver.displayName(raw) || raw);
|
||||
}
|
||||
|
||||
createFilterSignals(
|
||||
entity: Signal<Library | Shelf | MagicShelf | null>,
|
||||
entityType: Signal<EntityType>,
|
||||
activeFilters: Signal<Record<string, unknown[]> | null>,
|
||||
filterMode: Signal<BookFilterMode>
|
||||
): Record<FilterType, Signal<Filter[]>> {
|
||||
const filteredBooks = computed(() =>
|
||||
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
|
||||
);
|
||||
|
||||
const signals = {} as Record<FilterType, Signal<Filter[]>>;
|
||||
|
||||
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
|
||||
const filterType = type as Exclude<FilterType, 'library'>;
|
||||
signals[filterType] = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
|
||||
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
|
||||
});
|
||||
}
|
||||
|
||||
signals.library = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
|
||||
const libraries = this.libraryService.libraries();
|
||||
|
||||
const libraryMap = new Map(
|
||||
libraries
|
||||
.filter(lib => lib.id !== undefined)
|
||||
.map(lib => [lib.id!, lib.name])
|
||||
);
|
||||
|
||||
const filterMap = new Map<number, Filter>();
|
||||
|
||||
for (const book of books) {
|
||||
if (book.libraryId == null) continue;
|
||||
|
||||
if (!filterMap.has(book.libraryId)) {
|
||||
filterMap.set(book.libraryId, {
|
||||
value: {
|
||||
id: book.libraryId,
|
||||
name: libraryMap.get(book.libraryId) ?? book.libraryName ?? `Library ${book.libraryId}`
|
||||
},
|
||||
bookCount: 0
|
||||
});
|
||||
}
|
||||
filterMap.get(book.libraryId)!.bookCount++;
|
||||
}
|
||||
|
||||
return this.sortFiltersByCount(Array.from(filterMap.values()));
|
||||
});
|
||||
|
||||
return signals;
|
||||
}
|
||||
|
||||
filterBooksByEntity(
|
||||
books: Book[],
|
||||
entity: Library | Shelf | MagicShelf | null,
|
||||
entityType: EntityType
|
||||
): Book[] {
|
||||
if (!entity) return books;
|
||||
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return books.filter(book => book.libraryId === (entity as Library).id);
|
||||
|
||||
case EntityType.SHELF: {
|
||||
const shelfId = (entity as Shelf).id;
|
||||
return books.filter(book => book.shelves?.some(s => s.id === shelfId));
|
||||
}
|
||||
|
||||
case EntityType.MAGIC_SHELF:
|
||||
return this.filterByMagicShelf(books, entity as MagicShelf);
|
||||
|
||||
case EntityType.UNSHELVED:
|
||||
return books.filter(book => !book.shelves || book.shelves.length === 0);
|
||||
|
||||
default:
|
||||
return books;
|
||||
}
|
||||
}
|
||||
|
||||
processFilterValue(key: string, value: unknown): unknown {
|
||||
if (NUMERIC_ID_FILTER_TYPES.has(key as FilterType) && typeof value === 'string') {
|
||||
return Number(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
isNumericFilter(filterType: string): boolean {
|
||||
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
|
||||
}
|
||||
|
||||
private buildAndSortFilters(
|
||||
books: Book[],
|
||||
extractor: (book: Book) => FilterValue[],
|
||||
sortMode: SortMode
|
||||
): Filter[] {
|
||||
const filterMap = new Map<unknown, Filter>();
|
||||
|
||||
for (const book of books) {
|
||||
for (const item of extractor(book)) {
|
||||
const id = item.id;
|
||||
if (!filterMap.has(id)) {
|
||||
filterMap.set(id, {value: item, bookCount: 0});
|
||||
}
|
||||
filterMap.get(id)!.bookCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const filters = Array.from(filterMap.values());
|
||||
const sorted = sortMode === 'sortIndex'
|
||||
? this.sortFiltersBySortIndex(filters)
|
||||
: this.sortFiltersByCount(filters);
|
||||
|
||||
return sorted.slice(0, MAX_FILTER_ITEMS);
|
||||
}
|
||||
|
||||
private sortFiltersByCount(filters: Filter[]): Filter[] {
|
||||
return filters.sort((a, b) => {
|
||||
if (b.bookCount !== a.bookCount) return b.bookCount - a.bookCount;
|
||||
return this.compareNames(a, b);
|
||||
});
|
||||
}
|
||||
|
||||
private sortFiltersBySortIndex(filters: Filter[]): Filter[] {
|
||||
return filters.sort((a, b) => {
|
||||
const aIndex = (a.value as { sortIndex?: number }).sortIndex ?? 999;
|
||||
const bIndex = (b.value as { sortIndex?: number }).sortIndex ?? 999;
|
||||
if (aIndex !== bIndex) return aIndex - bIndex;
|
||||
return this.compareNames(a, b);
|
||||
});
|
||||
}
|
||||
|
||||
private compareNames(a: Filter, b: Filter): number {
|
||||
const aName = String((a.value as { name?: string }).name ?? '');
|
||||
const bName = String((b.value as { name?: string }).name ?? '');
|
||||
return aName.localeCompare(bName);
|
||||
}
|
||||
|
||||
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
|
||||
if (!magicShelf.filterJson) return [];
|
||||
try {
|
||||
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
|
||||
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
|
||||
} catch {
|
||||
console.warn('Invalid filterJson for MagicShelf');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookSelectionService} from './book-selection.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {bookId: id, title: `Book ${id}`},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookSelectionService', () => {
|
||||
let service: BookSelectionService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [BookSelectionService]
|
||||
});
|
||||
|
||||
service = TestBed.inject(BookSelectionService);
|
||||
});
|
||||
|
||||
it('selects and deselects single books and series groups', () => {
|
||||
const singleBook = makeBook(1);
|
||||
const seriesBook = makeBook(2, {
|
||||
seriesBooks: [makeBook(2), makeBook(3)]
|
||||
});
|
||||
|
||||
service.selectBook(singleBook);
|
||||
service.selectBook(seriesBook);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set([1, 2, 3]));
|
||||
expect(service.selectedCount()).toBe(3);
|
||||
|
||||
service.deselectBook(makeBook(1));
|
||||
service.deselectBook(seriesBook);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('tracks checkbox clicks with and without shift selection', () => {
|
||||
const books = [makeBook(1), makeBook(2), makeBook(3), makeBook(4)];
|
||||
service.setCurrentBooks(books);
|
||||
|
||||
service.handleCheckboxClick({index: 1, book: books[1], selected: true, shiftKey: false});
|
||||
expect(service.selectedBooks()).toEqual(new Set([2]));
|
||||
|
||||
service.handleCheckboxClick({index: 3, book: books[3], selected: true, shiftKey: true});
|
||||
expect(service.selectedBooks()).toEqual(new Set([2, 3, 4]));
|
||||
|
||||
service.handleCheckboxClick({index: 3, book: books[3], selected: false, shiftKey: true});
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
});
|
||||
|
||||
it('selects all current books, resets selection, and clones selected ids', () => {
|
||||
expect(() => service.selectAll()).not.toThrow();
|
||||
|
||||
const books = [makeBook(1), makeBook(2)];
|
||||
service.setCurrentBooks(books);
|
||||
service.selectAll();
|
||||
expect(service.selectedBooks()).toEqual(new Set([1, 2]));
|
||||
|
||||
const selectedIds = new Set([4, 5]);
|
||||
service.setSelectedBooks(selectedIds);
|
||||
selectedIds.add(6);
|
||||
|
||||
expect(service.selectedBooks()).toEqual(new Set([4, 5]));
|
||||
|
||||
service.deselectAll();
|
||||
expect(service.selectedBooks()).toEqual(new Set());
|
||||
expect(service.selectedCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('selects all from provided book IDs when passed to selectAll', () => {
|
||||
const books = [makeBook(1), makeBook(2)];
|
||||
service.setCurrentBooks(books);
|
||||
|
||||
service.selectAll([10, 20, 30, 40, 50]);
|
||||
expect(service.selectedBooks()).toEqual(new Set([10, 20, 30, 40, 50]));
|
||||
expect(service.selectedCount()).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
import {computed, Injectable, signal} from '@angular/core';
|
||||
import {Book} from '../../model/book.model';
|
||||
|
||||
export interface CheckboxClickEvent {
|
||||
index: number;
|
||||
book: Book;
|
||||
selected: boolean;
|
||||
shiftKey: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookSelectionService {
|
||||
private readonly _selectedBooks = signal<Set<number>>(new Set());
|
||||
readonly selectedBooks = this._selectedBooks.asReadonly();
|
||||
readonly selectedCount = computed(() => this._selectedBooks().size);
|
||||
|
||||
private currentBooks: Book[] = [];
|
||||
private lastSelectedIndex: number | null = null;
|
||||
|
||||
setCurrentBooks(books: Book[]): void {
|
||||
this.currentBooks = books;
|
||||
}
|
||||
|
||||
getSelectableBookIds(book: Book): number[] {
|
||||
return book.seriesBooks?.length
|
||||
? book.seriesBooks.map(seriesBook => seriesBook.id)
|
||||
: [book.id];
|
||||
}
|
||||
|
||||
isBookSelected(book: Book): boolean {
|
||||
const selectedIds = this._selectedBooks();
|
||||
const ids = this.getSelectableBookIds(book);
|
||||
return ids.every(id => selectedIds.has(id));
|
||||
}
|
||||
|
||||
selectBook(book: Book): void {
|
||||
this._selectedBooks.update(current => {
|
||||
const next = new Set(current);
|
||||
this.getSelectableBookIds(book).forEach(bookId => next.add(bookId));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
deselectBook(book: Book): void {
|
||||
this._selectedBooks.update(current => {
|
||||
const next = new Set(current);
|
||||
this.getSelectableBookIds(book).forEach(bookId => next.delete(bookId));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
handleCheckboxClick(event: CheckboxClickEvent): void {
|
||||
const {index, book, selected, shiftKey} = event;
|
||||
|
||||
if (!shiftKey || this.lastSelectedIndex === null) {
|
||||
this.handleBookSelection(book, selected);
|
||||
this.lastSelectedIndex = index;
|
||||
} else {
|
||||
const start = Math.min(this.lastSelectedIndex, index);
|
||||
const end = Math.max(this.lastSelectedIndex, index);
|
||||
const isUnselectingRange = !selected;
|
||||
|
||||
for (let i = start; i <= end; i++) {
|
||||
const rangeBook = this.currentBooks[i];
|
||||
if (!rangeBook) continue;
|
||||
this.handleBookSelection(rangeBook, !isUnselectingRange);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleBookSelection(book: Book, selected: boolean): void {
|
||||
if (selected) {
|
||||
this.selectBook(book);
|
||||
} else {
|
||||
this.deselectBook(book);
|
||||
}
|
||||
}
|
||||
|
||||
selectAll(allBookIds?: number[]): void {
|
||||
if (allBookIds && allBookIds.length > 0) {
|
||||
this._selectedBooks.set(new Set(allBookIds));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.currentBooks || this.currentBooks.length === 0) return;
|
||||
|
||||
this._selectedBooks.update(current => {
|
||||
const next = new Set(current);
|
||||
for (const book of this.currentBooks) {
|
||||
this.getSelectableBookIds(book).forEach(bookId => next.add(bookId));
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
deselectAll(): void {
|
||||
this._selectedBooks.set(new Set());
|
||||
this.lastSelectedIndex = null;
|
||||
}
|
||||
|
||||
setSelectedBooks(bookIds: Set<number>): void {
|
||||
this._selectedBooks.set(new Set(bookIds));
|
||||
}
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
<ng-container *transloco="let t">
|
||||
@let currentBook = book();
|
||||
@let currentMetadata = metadata();
|
||||
@let metadataLocked = isMetadataLocked();
|
||||
@let lockPending = isLockPending();
|
||||
@let squareCover = useSquareCover();
|
||||
@let imageUrl = coverUrl();
|
||||
@let coverLabel = currentMetadata.title || currentBook.fileName || t('book.table.bookCoverAlt');
|
||||
|
||||
@for (cell of cells(); track cell.id; let columnIndex = $index) {
|
||||
<div
|
||||
class="book-table-cell"
|
||||
role="gridcell"
|
||||
[attr.aria-colindex]="columnIndex + 1"
|
||||
[ngClass]="cell.className"
|
||||
[attr.title]="getCellTitle(cell)">
|
||||
@switch (cell.kind) {
|
||||
@case ('select') {
|
||||
<p-checkbox
|
||||
class="book-table-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="isSelected()"
|
||||
(ngModelChange)="onSelectionChange($event)"
|
||||
[ariaLabel]="currentMetadata.title ? t('book.table.selectBook', {title: currentMetadata.title}) : t('book.table.selectBookFallback')"></p-checkbox>
|
||||
}
|
||||
@case ('lock') {
|
||||
<button
|
||||
type="button"
|
||||
class="metadata-lock-button"
|
||||
[class.metadata-lock-button-locked]="metadataLocked"
|
||||
[disabled]="lockPending"
|
||||
[title]="metadataLocked ? t('book.table.locked') : t('book.table.unlocked')"
|
||||
[attr.aria-label]="metadataLocked ? t('book.table.locked') : t('book.table.unlocked')"
|
||||
[attr.aria-pressed]="metadataLocked"
|
||||
[attr.aria-busy]="lockPending"
|
||||
(click)="metadataLockToggleRequested.emit(currentMetadata)">
|
||||
<i [class]="lockPending ? 'pi pi-spin pi-spinner' : (metadataLocked ? 'pi pi-lock' : 'pi pi-lock-open')"></i>
|
||||
</button>
|
||||
}
|
||||
@case ('cover') {
|
||||
<a
|
||||
cdkOverlayOrigin
|
||||
#coverOrigin="cdkOverlayOrigin"
|
||||
[routerLink]="urlHelper.getBookUrl(currentBook)"
|
||||
class="cover-link"
|
||||
[attr.aria-label]="coverLabel"
|
||||
(mouseenter)="showCoverPreview(coverOrigin)"
|
||||
(mouseleave)="coverPreviewHide.emit(currentBook.id)"
|
||||
(focusin)="showCoverPreview(coverOrigin)"
|
||||
(focusout)="coverPreviewHide.emit(currentBook.id)">
|
||||
<app-cover
|
||||
class="cover-thumbnail"
|
||||
aria-hidden="true"
|
||||
[class.square-cover]="squareCover"
|
||||
[src]="imageUrl"
|
||||
[title]="currentMetadata.title || currentBook.fileName"
|
||||
[authors]="currentMetadata.authors ?? []"
|
||||
size="sm" />
|
||||
</a>
|
||||
}
|
||||
@case ('readStatus') {
|
||||
@if (showReadStatus()) {
|
||||
<div
|
||||
class="read-status-indicator"
|
||||
[ngClass]="readStatusClass()"
|
||||
[pTooltip]="t('book.table.statusWithPrefix', {status: readStatusTooltip()})"
|
||||
tooltipPosition="top">
|
||||
<i [class]="readStatusIcon()"></i>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@case ('rating') {
|
||||
<span class="rating-wrapper" [title]="cell.rating === null ? '' : cell.display">
|
||||
<app-rating
|
||||
readonly
|
||||
[value]="cell.rating ?? 0"
|
||||
[ariaLabel]="cell.rating === null ? t('book.table.noRating') : t('book.table.ratingOutOf', {rating: cell.display, max: 5})" />
|
||||
</span>
|
||||
}
|
||||
@case ('clickable') {
|
||||
@for (item of cell.links; track $index; let isLast = $last) {
|
||||
<a [routerLink]="item.url" class="cell-link">{{ item.anchor }}</a>@if (!isLast) {<span>, </span>}
|
||||
}
|
||||
}
|
||||
@case ('text') {
|
||||
{{ cell.value }}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</ng-container>
|
||||
-175
@@ -1,175 +0,0 @@
|
||||
:host {
|
||||
box-sizing: border-box;
|
||||
display: grid;
|
||||
grid-template-columns: var(--book-table-grid-template);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
min-width: 100%;
|
||||
border-bottom: 1px solid var(--book-table-cell-border-color);
|
||||
background: var(--book-table-row-background);
|
||||
color: var(--book-table-row-color);
|
||||
}
|
||||
|
||||
:host(.book-table-row-striped) {
|
||||
background: var(--book-table-row-striped-background);
|
||||
}
|
||||
|
||||
:host(:hover) {
|
||||
z-index: 3;
|
||||
background: var(--book-table-row-hover-background);
|
||||
color: var(--book-table-row-hover-color);
|
||||
}
|
||||
|
||||
.book-table-cell {
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: inherit;
|
||||
min-width: 0;
|
||||
padding: var(--book-table-cell-padding);
|
||||
border-right: 1px solid var(--book-table-cell-border-color);
|
||||
overflow: hidden;
|
||||
color: inherit;
|
||||
line-height: 1.2;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.book-table-checkbox {
|
||||
display: inline-flex;
|
||||
line-height: 0;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.metadata-lock-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.3125rem;
|
||||
height: 1.3125rem;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
color: var(--book-table-lock-unlocked-color);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--book-table-lock-unlocked-color) 16%, transparent);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
&.metadata-lock-button-locked {
|
||||
color: var(--book-table-lock-locked-color);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--book-table-lock-locked-color) 16%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.cover-link {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.cover-thumbnail {
|
||||
width: calc(1.75rem * 5 / 7);
|
||||
height: 1.75rem;
|
||||
aspect-ratio: 5 / 7;
|
||||
border-radius: 4px;
|
||||
|
||||
&.square-cover {
|
||||
width: 1.75rem;
|
||||
aspect-ratio: 1 / 1;
|
||||
}
|
||||
}
|
||||
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto;
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status-read {
|
||||
color: var(--book-table-status-read-color);
|
||||
}
|
||||
|
||||
.status-reading {
|
||||
color: var(--book-table-status-reading-color);
|
||||
}
|
||||
|
||||
.status-re-reading {
|
||||
color: var(--book-table-status-re-reading-color);
|
||||
}
|
||||
|
||||
.status-partially-read {
|
||||
color: var(--book-table-status-partially-read-color);
|
||||
}
|
||||
|
||||
.status-paused {
|
||||
color: var(--book-table-status-paused-color);
|
||||
}
|
||||
|
||||
.status-abandoned {
|
||||
color: var(--book-table-status-abandoned-color);
|
||||
}
|
||||
|
||||
.status-wont-read {
|
||||
color: var(--book-table-status-wont-read-color);
|
||||
}
|
||||
|
||||
.cell-status,
|
||||
.cell-number {
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cell-rating {
|
||||
justify-content: flex-start;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.cell-action,
|
||||
.cell-cover {
|
||||
justify-content: center;
|
||||
padding-inline: 0.4375rem;
|
||||
}
|
||||
|
||||
.cell-cover {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.cell-text {
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.rating-wrapper {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--book-table-rating-gap);
|
||||
min-width: 6.125rem;
|
||||
}
|
||||
|
||||
.cell-link {
|
||||
overflow: hidden;
|
||||
color: var(--color-primary-text);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
-129
@@ -1,129 +0,0 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {provideRouter} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {BookTableRowComponent} from './book-table-row.component';
|
||||
|
||||
function makeBook(id: number, title: string): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title,
|
||||
authors: ['Test Author'],
|
||||
categories: ['Fantasy'],
|
||||
amazonRating: 4.2,
|
||||
allMetadataLocked: false,
|
||||
},
|
||||
readStatus: ReadStatus.READING,
|
||||
fileSizeKb: 1536,
|
||||
primaryFile: {
|
||||
id: id * 10,
|
||||
bookId: id,
|
||||
bookType: 'EPUB',
|
||||
fileName: `${title}.epub`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookTableRowComponent', () => {
|
||||
let fixture: ComponentFixture<BookTableRowComponent>;
|
||||
let component: BookTableRowComponent;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookTableRowComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
provideRouter([]),
|
||||
{
|
||||
provide: UrlHelperService,
|
||||
useValue: {
|
||||
getBookUrl: (book: Book) => `/book/${book.id}`,
|
||||
filterBooksBy: (filterKey: string, filterValue: string) => `/all-books?filter=${filterKey}:${filterValue}`,
|
||||
getThumbnailUrl: () => null,
|
||||
getAudiobookThumbnailUrl: () => null,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: ReadStatusHelper,
|
||||
useValue: {
|
||||
getReadStatusIcon: () => 'pi pi-book',
|
||||
getReadStatusClass: () => 'status-reading',
|
||||
getReadStatusTooltip: () => 'Reading',
|
||||
shouldShowStatusIcon: () => true,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(BookTableRowComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.componentRef.setInput('rowIndex', 0);
|
||||
fixture.componentRef.setInput('rowHeight', 46);
|
||||
fixture.componentRef.setInput('rowStart', 0);
|
||||
fixture.componentRef.setInput('isSelected', false);
|
||||
fixture.componentRef.setInput('useSquareCovers', false);
|
||||
});
|
||||
|
||||
it('renders visible book fields as table cells', () => {
|
||||
fixture.componentRef.setInput('book', makeBook(1, 'Alpha'));
|
||||
fixture.componentRef.setInput('cellIds', ['title', 'authors', 'amazonRating', 'fileSizeKb']);
|
||||
fixture.detectChanges();
|
||||
|
||||
const host = fixture.nativeElement as HTMLElement;
|
||||
const cells = host.querySelectorAll<HTMLElement>('.book-table-cell');
|
||||
const links = host.querySelectorAll<HTMLAnchorElement>('.cell-link');
|
||||
const rating = host.querySelector<HTMLElement>('.rating-wrapper');
|
||||
|
||||
expect(cells).toHaveLength(4);
|
||||
expect(links[0]?.textContent?.trim()).toBe('Alpha');
|
||||
expect(links[0]?.getAttribute('href')).toBe('/book/1');
|
||||
expect(links[1]?.textContent?.trim()).toBe('Test Author');
|
||||
expect(rating?.querySelector('app-rating')).toBeTruthy();
|
||||
expect(rating?.getAttribute('title')).toBe('4.2');
|
||||
expect(cells[3]?.textContent?.trim()).toBe('1.5 MB');
|
||||
});
|
||||
|
||||
it('labels icon actions and cover links for assistive tech', () => {
|
||||
fixture.componentRef.setInput('book', makeBook(1, 'Alpha'));
|
||||
fixture.componentRef.setInput('cellIds', ['lock', 'cover', 'readStatus']);
|
||||
fixture.detectChanges();
|
||||
|
||||
const host = fixture.nativeElement as HTMLElement;
|
||||
const lockButton = host.querySelector<HTMLButtonElement>('.metadata-lock-button');
|
||||
const coverLink = host.querySelector<HTMLAnchorElement>('.cover-link');
|
||||
const cover = host.querySelector<HTMLElement>('app-cover');
|
||||
|
||||
expect(lockButton?.getAttribute('aria-label')).toBe('Unlocked');
|
||||
expect(lockButton?.getAttribute('aria-pressed')).toBe('false');
|
||||
expect(coverLink?.getAttribute('aria-label')).toBe('Alpha');
|
||||
expect(cover?.getAttribute('aria-hidden')).toBe('true');
|
||||
});
|
||||
|
||||
it('formats file sizes with the matching unit', () => {
|
||||
fixture.componentRef.setInput('cellIds', ['fileSizeKb']);
|
||||
|
||||
fixture.componentRef.setInput('book', {...makeBook(1, 'Alpha'), fileSizeKb: 512});
|
||||
fixture.detectChanges();
|
||||
expect((fixture.nativeElement as HTMLElement).textContent).toContain('512 KB');
|
||||
|
||||
fixture.componentRef.setInput('book', {...makeBook(1, 'Alpha'), fileSizeKb: 2 * 1024 * 1024});
|
||||
fixture.detectChanges();
|
||||
expect((fixture.nativeElement as HTMLElement).textContent).toContain('2.0 GB');
|
||||
});
|
||||
|
||||
it('uses empty metadata for books without metadata instead of treating them as loading', () => {
|
||||
fixture.componentRef.setInput('book', {...makeBook(1, 'Alpha'), metadata: undefined});
|
||||
fixture.componentRef.setInput('cellIds', ['title']);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(component.metadata().bookId).toBe(1);
|
||||
expect(component.cells()[0]).toEqual(expect.objectContaining({id: 'title', kind: 'clickable', title: ''}));
|
||||
});
|
||||
});
|
||||
-337
@@ -1,337 +0,0 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, inject, input, output} from '@angular/core';
|
||||
import {CdkOverlayOrigin} from '@angular/cdk/overlay';
|
||||
import {DatePipe, NgClass} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {RouterLink, UrlTree} from '@angular/router';
|
||||
import {TranslocoDirective} from '@jsverse/transloco';
|
||||
import {Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {Book, BookMetadata} from '../../../model/book.model';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {LanguageResolverService} from '../../../../../shared/service/language-resolver.service';
|
||||
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
|
||||
import {AppRatingComponent} from '../../../../../shared/ui/rating/app-rating.component';
|
||||
import {RATING_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
|
||||
|
||||
interface BookTableCellLink {
|
||||
url: string | UrlTree;
|
||||
anchor?: string | number | null;
|
||||
}
|
||||
|
||||
interface BookTableBaseCellView {
|
||||
id: string;
|
||||
className: string;
|
||||
}
|
||||
|
||||
interface BookTableActionCellView extends BookTableBaseCellView {
|
||||
kind: 'select' | 'lock' | 'cover';
|
||||
}
|
||||
|
||||
interface BookTableReadStatusCellView extends BookTableBaseCellView {
|
||||
kind: 'readStatus';
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface BookTableRatingCellView extends BookTableBaseCellView {
|
||||
kind: 'rating';
|
||||
rating: number | null;
|
||||
display: string;
|
||||
}
|
||||
|
||||
interface BookTableClickableCellView extends BookTableBaseCellView {
|
||||
kind: 'clickable';
|
||||
links: BookTableCellLink[];
|
||||
title: string | number;
|
||||
}
|
||||
|
||||
interface BookTableTextCellView extends BookTableBaseCellView {
|
||||
kind: 'text';
|
||||
value: string | number;
|
||||
}
|
||||
|
||||
type BookTableCellView =
|
||||
| BookTableActionCellView
|
||||
| BookTableReadStatusCellView
|
||||
| BookTableRatingCellView
|
||||
| BookTableClickableCellView
|
||||
| BookTableTextCellView;
|
||||
type BookTableCellKind = BookTableCellView['kind'];
|
||||
|
||||
export interface BookTableRowCoverPreview {
|
||||
book: Book;
|
||||
metadata: BookMetadata;
|
||||
origin: CdkOverlayOrigin;
|
||||
coverUrl: string | null;
|
||||
useSquareCover: boolean;
|
||||
}
|
||||
|
||||
export interface BookTableSelectionChange {
|
||||
book: Book;
|
||||
checked: boolean;
|
||||
}
|
||||
|
||||
const CLICKABLE_FIELDS = new Set(['title', 'authors', 'publisher', 'seriesName', 'categories', 'language']);
|
||||
const CLICKABLE_FILTER_KEYS: Record<string, string> = {
|
||||
authors: 'author',
|
||||
publisher: 'publisher',
|
||||
categories: 'category',
|
||||
language: 'language',
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-table-row',
|
||||
standalone: true,
|
||||
templateUrl: './book-table-row.component.html',
|
||||
styleUrls: ['./book-table-row.component.scss'],
|
||||
imports: [
|
||||
CdkOverlayOrigin,
|
||||
Checkbox,
|
||||
CoverComponent,
|
||||
FormsModule,
|
||||
NgClass,
|
||||
AppRatingComponent,
|
||||
RouterLink,
|
||||
Tooltip,
|
||||
TranslocoDirective,
|
||||
],
|
||||
providers: [DatePipe],
|
||||
host: {
|
||||
role: 'row',
|
||||
'[attr.aria-rowindex]': 'rowIndex() + 2',
|
||||
'[attr.aria-selected]': 'isSelected()',
|
||||
'[class.book-table-row-striped]': 'rowIndex() % 2 === 0',
|
||||
'[style.height.px]': 'rowHeight()',
|
||||
'[style.transform]': '"translateY(" + rowStart() + "px)"',
|
||||
},
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class BookTableRowComponent {
|
||||
readonly book = input.required<Book>();
|
||||
readonly cellIds = input.required<string[]>();
|
||||
readonly rowIndex = input.required<number>();
|
||||
readonly rowHeight = input.required<number>();
|
||||
readonly rowStart = input.required<number>();
|
||||
readonly isSelected = input(false);
|
||||
readonly isLockPending = input(false);
|
||||
readonly useSquareCovers = input(false);
|
||||
|
||||
readonly selectionChange = output<BookTableSelectionChange>();
|
||||
readonly metadataLockToggleRequested = output<BookMetadata>();
|
||||
readonly coverPreviewShow = output<BookTableRowCoverPreview>();
|
||||
readonly coverPreviewHide = output<number>();
|
||||
|
||||
private readonly datePipe = inject(DatePipe);
|
||||
private readonly readStatusHelper = inject(ReadStatusHelper);
|
||||
private readonly languageResolver = inject(LanguageResolverService);
|
||||
protected readonly urlHelper = inject(UrlHelperService);
|
||||
|
||||
readonly metadata = computed<BookMetadata>(() => {
|
||||
const book = this.book();
|
||||
return book.metadata ?? {bookId: book.id};
|
||||
});
|
||||
readonly useSquareCover = computed(() => this.isAudiobook() || this.useSquareCovers());
|
||||
readonly coverUrl = computed(() => {
|
||||
const book = this.book();
|
||||
const metadata = this.metadata();
|
||||
return this.useSquareCover()
|
||||
? this.urlHelper.getAudiobookThumbnailUrl(book.id, metadata.audiobookCoverUpdatedOn)
|
||||
: this.urlHelper.getThumbnailUrl(book.id, metadata.coverUpdatedOn);
|
||||
});
|
||||
readonly readStatusClass = computed(() => this.readStatusHelper.getReadStatusClass(this.book().readStatus));
|
||||
readonly readStatusIcon = computed(() => this.readStatusHelper.getReadStatusIcon(this.book().readStatus));
|
||||
readonly readStatusTooltip = computed(() => this.readStatusHelper.getReadStatusTooltip(this.book().readStatus));
|
||||
readonly showReadStatus = computed(() => this.readStatusHelper.shouldShowStatusIcon(this.book().readStatus));
|
||||
readonly isMetadataLocked = computed(() => isMetadataFullyLocked(this.metadata()));
|
||||
readonly cells = computed(() => this.cellIds().map(field => this.createCellView(field)));
|
||||
|
||||
onSelectionChange(checked: boolean): void {
|
||||
this.selectionChange.emit({book: this.book(), checked});
|
||||
}
|
||||
|
||||
showCoverPreview(origin: CdkOverlayOrigin): void {
|
||||
this.coverPreviewShow.emit({
|
||||
book: this.book(),
|
||||
metadata: this.metadata(),
|
||||
origin,
|
||||
coverUrl: this.coverUrl(),
|
||||
useSquareCover: this.useSquareCover(),
|
||||
});
|
||||
}
|
||||
|
||||
private createCellView(field: string): BookTableCellView {
|
||||
const metadata = this.metadata();
|
||||
const book = this.book();
|
||||
const kind = this.getCellKind(field);
|
||||
const cell = {
|
||||
id: field,
|
||||
className: this.getCellClass(field),
|
||||
};
|
||||
|
||||
switch (kind) {
|
||||
case 'select':
|
||||
case 'lock':
|
||||
case 'cover':
|
||||
return {...cell, kind};
|
||||
case 'readStatus':
|
||||
return {...cell, kind, label: this.readStatusHelper.getReadStatusTooltip(book.readStatus)};
|
||||
case 'rating': {
|
||||
const rating = this.getRatingValue(metadata, field);
|
||||
return {...cell, kind, rating, display: rating === null ? '' : rating.toFixed(1)};
|
||||
}
|
||||
case 'clickable':
|
||||
return {...cell, kind, links: this.getCellClickableValue(metadata, book, field), title: this.getCellValue(metadata, book, field)};
|
||||
case 'text':
|
||||
return {...cell, kind, value: this.getCellValue(metadata, book, field)};
|
||||
}
|
||||
}
|
||||
|
||||
getCellTitle(cell: BookTableCellView): string | number | null {
|
||||
switch (cell.kind) {
|
||||
case 'readStatus':
|
||||
return cell.label;
|
||||
case 'clickable':
|
||||
return cell.title;
|
||||
case 'text':
|
||||
return cell.value;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private getCellKind(field: string): BookTableCellKind {
|
||||
if (field === 'select') return 'select';
|
||||
if (field === 'lock') return 'lock';
|
||||
if (field === 'cover') return 'cover';
|
||||
if (field === 'readStatus') return 'readStatus';
|
||||
if (RATING_FIELDS.has(field)) return 'rating';
|
||||
if (CLICKABLE_FIELDS.has(field)) return 'clickable';
|
||||
return 'text';
|
||||
}
|
||||
|
||||
private getCellClass(field: string): string {
|
||||
if (field === 'select' || field === 'lock') return 'cell-action';
|
||||
if (field === 'cover') return 'cell-cover';
|
||||
if (field === 'readStatus') return 'cell-status';
|
||||
if (RATING_FIELDS.has(field)) return 'cell-rating';
|
||||
if (field.endsWith('ReviewCount') || field === 'pageCount' || field === 'seriesNumber') return 'cell-number';
|
||||
return 'cell-text';
|
||||
}
|
||||
|
||||
private getCellClickableValue(metadata: BookMetadata, book: Book, field: string): BookTableCellLink[] {
|
||||
let values: string[];
|
||||
switch (field) {
|
||||
case 'title':
|
||||
return [{
|
||||
url: this.urlHelper.getBookUrl(book),
|
||||
anchor: metadata.title ?? book.fileName
|
||||
}];
|
||||
case 'categories':
|
||||
values = metadata.categories ?? [];
|
||||
break;
|
||||
case 'authors':
|
||||
values = metadata.authors ?? [];
|
||||
break;
|
||||
case 'seriesName': {
|
||||
const seriesName = metadata.seriesName;
|
||||
if (!seriesName) return [];
|
||||
return [{
|
||||
url: this.urlHelper.filterBooksBy('series', seriesName),
|
||||
anchor: seriesName
|
||||
}];
|
||||
}
|
||||
case 'language': {
|
||||
const language = metadata.language;
|
||||
if (!language) return [];
|
||||
return [{
|
||||
url: this.urlHelper.filterBooksBy('language', language),
|
||||
anchor: this.languageResolver.displayName(language)
|
||||
}];
|
||||
}
|
||||
default: {
|
||||
const value = this.getMetadataValue(metadata, field);
|
||||
values = typeof value === 'string' && value ? [value] : [];
|
||||
}
|
||||
}
|
||||
|
||||
return values.map(item => ({
|
||||
url: this.urlHelper.filterBooksBy(CLICKABLE_FILTER_KEYS[field] ?? field, item),
|
||||
anchor: item
|
||||
}));
|
||||
}
|
||||
|
||||
private getCellValue(metadata: BookMetadata, book: Book, field: string): string | number {
|
||||
switch (field) {
|
||||
case 'title':
|
||||
return metadata.title ?? '';
|
||||
case 'authors':
|
||||
return this.getAuthorNames(metadata.authors);
|
||||
case 'publisher':
|
||||
return metadata.publisher ?? '';
|
||||
case 'seriesName':
|
||||
return metadata.seriesName ?? '';
|
||||
case 'seriesNumber':
|
||||
return metadata.seriesNumber ?? '';
|
||||
case 'categories':
|
||||
return this.getGenres(metadata.categories);
|
||||
case 'publishedDate':
|
||||
return metadata.publishedDate ? this.datePipe.transform(metadata.publishedDate, 'dd-MMM-yyyy') ?? '' : '';
|
||||
case 'lastReadTime':
|
||||
return book.lastReadTime ? this.datePipe.transform(book.lastReadTime, 'dd-MMM-yyyy') ?? '' : '';
|
||||
case 'addedOn':
|
||||
return book.addedOn ? this.datePipe.transform(book.addedOn, 'dd-MMM-yyyy') ?? '' : '';
|
||||
case 'fileName':
|
||||
return book.primaryFile?.fileName ?? '';
|
||||
case 'fileSizeKb':
|
||||
return this.formatFileSize(book.fileSizeKb);
|
||||
case 'language':
|
||||
return this.languageResolver.displayName(metadata.language);
|
||||
case 'pageCount':
|
||||
return metadata.pageCount ?? '';
|
||||
case 'amazonReviewCount':
|
||||
case 'goodreadsReviewCount':
|
||||
case 'hardcoverReviewCount':
|
||||
return metadata[field] ?? '';
|
||||
case 'isbn':
|
||||
return metadata.isbn13 ?? metadata.isbn10 ?? '';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
private getAuthorNames(authors?: string[] | null): string {
|
||||
return authors?.join(', ') || '';
|
||||
}
|
||||
|
||||
private getGenres(genres?: string[] | null): string {
|
||||
return genres?.join(', ') || '';
|
||||
}
|
||||
|
||||
private formatFileSize(kb?: number): string {
|
||||
if (kb == null || Number.isNaN(kb)) return '-';
|
||||
if (kb < 1024) {
|
||||
return `${Number.isInteger(kb) ? kb.toFixed(0) : kb.toFixed(1)} KB`;
|
||||
}
|
||||
if (kb < 1024 * 1024) {
|
||||
return `${(kb / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
return `${(kb / (1024 * 1024)).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
private getRatingValue(metadata: BookMetadata, field: string): number | null {
|
||||
const rating = this.getMetadataValue(metadata, field);
|
||||
return typeof rating === 'number' ? rating : null;
|
||||
}
|
||||
|
||||
private getMetadataValue(metadata: BookMetadata, field: string): unknown {
|
||||
return this.isKeyOf(metadata, field) ? metadata[field] : undefined;
|
||||
}
|
||||
|
||||
private isKeyOf<T extends object>(value: T, field: PropertyKey): field is keyof T {
|
||||
return Object.prototype.hasOwnProperty.call(value, field);
|
||||
}
|
||||
|
||||
private isAudiobook(): boolean {
|
||||
return this.book().primaryFile?.bookType === 'AUDIOBOOK';
|
||||
}
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
<ng-container *transloco="let t">
|
||||
<div
|
||||
#scrollElement
|
||||
class="book-table-scroll p-datatable p-component p-datatable-scrollable p-datatable-striped p-datatable-gridlines p-datatable-resizable"
|
||||
role="grid"
|
||||
(scroll)="clearCoverPreview()"
|
||||
(wheel)="clearCoverPreview()"
|
||||
[attr.aria-label]="t('book.table.label')"
|
||||
[attr.aria-rowcount]="ariaRowCount()"
|
||||
[attr.aria-colcount]="ariaColumnCount()">
|
||||
<div class="book-table p-datatable-table p-datatable-scrollable-table p-datatable-resizable-table" [style]="columnSizeVars()" [style.width.px]="tableWidth()">
|
||||
@for (headerGroup of table.getHeaderGroups(); track headerGroup.id) {
|
||||
<div class="book-table-header-row" role="row" aria-rowindex="1">
|
||||
@for (header of headerGroup.headers; track header.id; let columnIndex = $index) {
|
||||
<div
|
||||
class="book-table-header-cell p-datatable-header-cell p-datatable-resizable-column"
|
||||
role="columnheader"
|
||||
[attr.aria-colindex]="columnIndex + 1"
|
||||
[class.cell-action]="header.column.id === 'select' || header.column.id === 'lock'"
|
||||
[class.cell-cover]="header.column.id === 'cover'">
|
||||
@if (header.column.id === 'select') {
|
||||
<p-checkbox
|
||||
class="book-table-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="allLoadedBooksSelected()"
|
||||
[indeterminate]="someBooksSelected()"
|
||||
(ngModelChange)="onHeaderCheckboxChange($event)"
|
||||
[ariaLabel]="t('book.browser.tooltip.selectAll')"></p-checkbox>
|
||||
} @else {
|
||||
<span class="p-datatable-column-title">{{ header.column.columnDef.header }}</span>
|
||||
}
|
||||
|
||||
@if (header.column.getCanResize()) {
|
||||
<span
|
||||
class="column-resizer p-datatable-column-resizer"
|
||||
(mousedown)="startColumnResize(header, $event)"
|
||||
(touchstart)="startColumnResize(header, $event)"
|
||||
aria-hidden="true"></span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="book-table-body" [style.height.px]="rowVirtualizer.getTotalSize()">
|
||||
@for (virtualRow of rowVirtualizer.getVirtualItems(); track virtualRow.key) {
|
||||
@if (books()[virtualRow.index]; as book) {
|
||||
<app-book-table-row
|
||||
[book]="book"
|
||||
[cellIds]="visibleCellIds()"
|
||||
[rowIndex]="virtualRow.index"
|
||||
[rowHeight]="virtualRow.size"
|
||||
[rowStart]="virtualRow.start"
|
||||
[isSelected]="isRowSelected(book)"
|
||||
[isLockPending]="isMetadataLockPending(book.id)"
|
||||
[useSquareCovers]="useSquareCovers()"
|
||||
(selectionChange)="onBookSelectionChange($event)"
|
||||
(metadataLockToggleRequested)="toggleMetadataLock($event)"
|
||||
(coverPreviewShow)="showCoverPreview($event)"
|
||||
(coverPreviewHide)="hideCoverPreview($event)" />
|
||||
} @else {
|
||||
<div
|
||||
class="book-table-row book-table-row-loading"
|
||||
role="row"
|
||||
aria-busy="true"
|
||||
[attr.aria-rowindex]="virtualRow.index + 2"
|
||||
[class.book-table-row-striped]="virtualRow.index % 2 === 0"
|
||||
[style.height.px]="virtualRow.size"
|
||||
[style.transform]="'translateY(' + virtualRow.start + 'px)'">
|
||||
@for (columnId of visibleCellIds(); track columnId; let columnIndex = $index) {
|
||||
<div
|
||||
class="book-table-cell"
|
||||
role="gridcell"
|
||||
[attr.aria-colindex]="columnIndex + 1"
|
||||
[class.cell-action]="columnId === 'select' || columnId === 'lock'"
|
||||
[class.cell-cover]="columnId === 'cover'">
|
||||
<span class="loading-line" [class.loading-line-short]="columnId !== 'title'"></span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (coverPreview(); as preview) {
|
||||
<ng-template
|
||||
cdkConnectedOverlay
|
||||
[cdkConnectedOverlayOrigin]="preview.origin"
|
||||
[cdkConnectedOverlayOpen]="true"
|
||||
[cdkConnectedOverlayPositions]="coverOverlayPositions"
|
||||
[cdkConnectedOverlayViewportMargin]="8"
|
||||
[cdkConnectedOverlayPush]="true"
|
||||
[cdkConnectedOverlayFlexibleDimensions]="true">
|
||||
<div class="cover-preview">
|
||||
<app-cover
|
||||
class="cover-preview-image"
|
||||
[class.square-cover]="preview.useSquareCover"
|
||||
[src]="preview.coverUrl"
|
||||
[title]="preview.metadata.title"
|
||||
[authors]="preview.metadata.authors ?? []"
|
||||
[alt]="preview.metadata.title || t('book.table.bookCoverAlt')" />
|
||||
</div>
|
||||
</ng-template>
|
||||
}
|
||||
</ng-container>
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
|
||||
--book-table-border-color: var(--p-datatable-border-color, color-mix(in srgb, var(--p-content-border-color) 82%, black));
|
||||
--book-table-header-background: var(--p-datatable-header-cell-background, var(--p-content-background));
|
||||
--book-table-header-color: var(--p-datatable-header-cell-color, var(--p-text-color));
|
||||
--book-table-header-padding: var(--p-datatable-header-cell-padding, 0.6563rem 0.875rem);
|
||||
--book-table-header-weight: var(--p-datatable-column-title-font-weight, 600);
|
||||
--book-table-row-background: var(--p-datatable-row-background, var(--p-content-background));
|
||||
--book-table-row-color: var(--p-datatable-row-color, var(--p-text-color));
|
||||
--book-table-row-hover-background: var(--p-datatable-row-hover-background, var(--p-content-hover-background));
|
||||
--book-table-row-hover-color: var(--p-datatable-row-hover-color, var(--p-text-color));
|
||||
--book-table-row-striped-background: var(--p-datatable-row-striped-background, var(--color-app));
|
||||
--book-table-cell-border-color: var(--p-datatable-body-cell-border-color, var(--book-table-border-color));
|
||||
--book-table-cell-padding: var(--p-datatable-body-cell-padding, 0.6563rem 0.875rem);
|
||||
--book-table-rating-gap: var(--p-rating-gap, 0.2188rem);
|
||||
--book-table-lock-unlocked-color: var(--color-lock-unlocked, var(--color-green-600));
|
||||
--book-table-lock-locked-color: var(--color-lock-locked, var(--color-red-600));
|
||||
--book-table-status-read-color: var(--color-green-500);
|
||||
--book-table-status-reading-color: var(--color-blue-500);
|
||||
--book-table-status-re-reading-color: var(--color-cyan-500);
|
||||
--book-table-status-partially-read-color: var(--color-amber-500);
|
||||
--book-table-status-paused-color: var(--color-yellow-500);
|
||||
--book-table-status-abandoned-color: var(--color-red-500);
|
||||
--book-table-status-wont-read-color: var(--color-pink-500);
|
||||
}
|
||||
|
||||
.book-table-scroll {
|
||||
box-sizing: border-box;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
background: var(--book-table-row-background);
|
||||
}
|
||||
|
||||
.book-table {
|
||||
min-width: 100%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.book-table-header-row,
|
||||
.book-table-row {
|
||||
box-sizing: border-box;
|
||||
display: grid;
|
||||
grid-template-columns: var(--book-table-grid-template);
|
||||
min-width: 100%;
|
||||
}
|
||||
|
||||
.book-table-header-row {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 20;
|
||||
min-height: 46px;
|
||||
background: var(--book-table-header-background);
|
||||
border-bottom: 1px solid var(--book-table-border-color);
|
||||
}
|
||||
|
||||
.book-table-header-cell,
|
||||
.book-table-cell {
|
||||
box-sizing: border-box;
|
||||
height: inherit;
|
||||
min-width: 0;
|
||||
border-right: 1px solid var(--book-table-cell-border-color);
|
||||
}
|
||||
|
||||
.book-table-header-cell {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: var(--book-table-header-padding);
|
||||
color: var(--book-table-header-color);
|
||||
font-weight: normal;
|
||||
text-align: start;
|
||||
white-space: nowrap;
|
||||
|
||||
.p-datatable-column-title {
|
||||
overflow: hidden;
|
||||
font-weight: var(--book-table-header-weight);
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
|
||||
.column-resizer {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: -3px;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.book-table-body {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.book-table-row {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
border-bottom: 1px solid var(--book-table-cell-border-color);
|
||||
background: var(--book-table-row-background);
|
||||
color: var(--book-table-row-color);
|
||||
}
|
||||
|
||||
.book-table-row-striped {
|
||||
background: var(--book-table-row-striped-background);
|
||||
}
|
||||
|
||||
.book-table-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: var(--book-table-cell-padding);
|
||||
overflow: hidden;
|
||||
color: inherit;
|
||||
line-height: 1.2;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.book-table-checkbox {
|
||||
display: inline-flex;
|
||||
line-height: 0;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.cover-preview {
|
||||
width: 12.25rem;
|
||||
max-height: calc(100dvh - 1.75rem);
|
||||
border-radius: 6px;
|
||||
box-shadow:
|
||||
0 18px 48px rgb(0 0 0 / 42%),
|
||||
0 4px 14px rgb(0 0 0 / 32%);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cover-preview-image {
|
||||
width: 100%;
|
||||
max-height: calc(100dvh - 5.25rem);
|
||||
aspect-ratio: 5 / 7;
|
||||
border-radius: inherit;
|
||||
|
||||
&.square-cover {
|
||||
aspect-ratio: 1 / 1;
|
||||
}
|
||||
}
|
||||
|
||||
.cell-action,
|
||||
.cell-cover {
|
||||
justify-content: center;
|
||||
padding-inline: 0.4375rem;
|
||||
}
|
||||
|
||||
.cell-cover {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.book-table-row-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.loading-line {
|
||||
display: block;
|
||||
width: 85%;
|
||||
height: 0.6563rem;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--p-text-color) 14%, transparent);
|
||||
animation: loading-line-pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.loading-line-short {
|
||||
width: 48%;
|
||||
}
|
||||
|
||||
@keyframes loading-line-pulse {
|
||||
0%, 100% { opacity: 0.3; }
|
||||
50% { opacity: 0.6; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.loading-line {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
-292
@@ -1,292 +0,0 @@
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {By} from '@angular/platform-browser';
|
||||
import {provideRouter} from '@angular/router';
|
||||
import {of, Subject} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {Book, BookMetadata, ReadStatus} from '../../../model/book.model';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {BookSelectionService} from '../book-selection.service';
|
||||
import {BookTableComponent} from './book-table.component';
|
||||
import {BookTableRowComponent} from './book-table-row.component';
|
||||
|
||||
function makeBook(id: number, title: string): Book & {metadata: BookMetadata} {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title,
|
||||
authors: ['Test Author'],
|
||||
categories: ['Fantasy'],
|
||||
amazonRating: 4.2,
|
||||
allMetadataLocked: false,
|
||||
},
|
||||
readStatus: ReadStatus.READING,
|
||||
primaryFile: {
|
||||
id: id * 10,
|
||||
bookId: id,
|
||||
bookType: 'EPUB',
|
||||
fileName: `${title}.epub`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookTableComponent', () => {
|
||||
let fixture: ComponentFixture<BookTableComponent>;
|
||||
let component: BookTableComponent;
|
||||
let bookSelectionService: BookSelectionService;
|
||||
let bookMetadataManageService: { toggleAllLock: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
bookMetadataManageService = {
|
||||
toggleAllLock: vi.fn(() => of(null)),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookTableComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
provideRouter([]),
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{
|
||||
provide: UrlHelperService,
|
||||
useValue: {
|
||||
getBookUrl: (book: Book) => `/book/${book.id}`,
|
||||
filterBooksBy: (filterKey: string, filterValue: string) => `/all-books?filter=${filterKey}:${filterValue}`,
|
||||
getThumbnailUrl: () => null,
|
||||
getAudiobookThumbnailUrl: () => null,
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: BookMetadataManageService,
|
||||
useValue: bookMetadataManageService,
|
||||
},
|
||||
{
|
||||
provide: ReadStatusHelper,
|
||||
useValue: {
|
||||
getReadStatusIcon: () => 'pi pi-book',
|
||||
getReadStatusClass: () => 'status-reading',
|
||||
getReadStatusTooltip: () => 'Reading',
|
||||
shouldShowStatusIcon: () => true,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(BookTableComponent);
|
||||
component = fixture.componentInstance;
|
||||
bookSelectionService = TestBed.inject(BookSelectionService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('renders grid semantics and keeps resize handles out of the tab order', () => {
|
||||
fixture = TestBed.createComponent(BookTableComponent);
|
||||
fixture.componentRef.setInput('books', [makeBook(1, 'Alpha')]);
|
||||
fixture.componentRef.setInput('visibleColumns', [
|
||||
{field: 'title', header: 'Title'},
|
||||
{field: 'amazonRating', header: 'Amazon Rating'},
|
||||
]);
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
const host = fixture.nativeElement as HTMLElement;
|
||||
const grid = host.querySelector<HTMLElement>('.book-table-scroll');
|
||||
const headerCells = host.querySelectorAll<HTMLElement>('.book-table-header-cell');
|
||||
const resizer = host.querySelector<HTMLElement>('.column-resizer');
|
||||
|
||||
expect(grid?.getAttribute('role')).toBe('grid');
|
||||
expect(grid?.getAttribute('aria-rowcount')).toBe('2');
|
||||
expect(grid?.getAttribute('aria-colcount')).toBe('5');
|
||||
expect(headerCells[0]?.getAttribute('role')).toBe('columnheader');
|
||||
expect(headerCells[0]?.getAttribute('aria-colindex')).toBe('1');
|
||||
expect(resizer?.tagName).toBe('SPAN');
|
||||
expect(resizer?.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(resizer?.hasAttribute('tabindex')).toBe(false);
|
||||
});
|
||||
|
||||
it('does not recreate a rendered row when selection changes', () => {
|
||||
const book = makeBook(1, 'Alpha');
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 0, key: 1, start: 0, size: 46, end: 46, lane: 0}
|
||||
]);
|
||||
fixture.componentRef.setInput('books', [book]);
|
||||
fixture.componentRef.setInput('visibleColumns', [
|
||||
{field: 'title', header: 'Title'},
|
||||
{field: 'amazonRating', header: 'Amazon Rating'},
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const initialRowDebugElement = fixture.debugElement.query(By.directive(BookTableRowComponent));
|
||||
const initialRowInstance = initialRowDebugElement.componentInstance as BookTableRowComponent;
|
||||
const selectionSpy = vi.spyOn(bookSelectionService, 'handleBookSelection');
|
||||
const initialRowElement = initialRowDebugElement.nativeElement as HTMLElement;
|
||||
const checkboxInput = initialRowElement.querySelector<HTMLInputElement>('input[type="checkbox"]');
|
||||
|
||||
expect(checkboxInput).toBeTruthy();
|
||||
checkboxInput!.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
const updatedRowDebugElement = fixture.debugElement.query(By.directive(BookTableRowComponent));
|
||||
const updatedRowInstance = updatedRowDebugElement.componentInstance as BookTableRowComponent;
|
||||
expect(updatedRowDebugElement.nativeElement).toBe(initialRowDebugElement.nativeElement);
|
||||
expect(updatedRowInstance).toBe(initialRowInstance);
|
||||
expect(selectionSpy).toHaveBeenCalledWith(book, true);
|
||||
expect(updatedRowInstance.isSelected()).toBe(true);
|
||||
expect(bookSelectionService.isBookSelected(book)).toBe(true);
|
||||
expect(component.isRowSelected(book)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not request the next page again after a same-size book refresh', () => {
|
||||
const loadNextPageSpy = vi.fn();
|
||||
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
|
||||
]);
|
||||
component.loadNextPage.subscribe(loadNextPageSpy);
|
||||
|
||||
fixture.componentRef.setInput('books', books);
|
||||
fixture.componentRef.setInput('virtualRowCount', 100);
|
||||
fixture.componentRef.setInput('isFetchingNextPage', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
fixture.componentRef.setInput('books', books.map(book => ({
|
||||
...book,
|
||||
metadata: {...book.metadata},
|
||||
})));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('can request the next page again after the parent signals a query swap', () => {
|
||||
const loadNextPageSpy = vi.fn();
|
||||
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
|
||||
const nextBooks = Array.from({length: 50}, (_, index) => makeBook(index + 101, `Next Book ${index + 1}`));
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
|
||||
]);
|
||||
component.loadNextPage.subscribe(loadNextPageSpy);
|
||||
|
||||
const initialQueryToken = {query: 'first'};
|
||||
fixture.componentRef.setInput('books', books);
|
||||
fixture.componentRef.setInput('virtualRowCount', 51);
|
||||
fixture.componentRef.setInput('isFetchingNextPage', false);
|
||||
fixture.componentRef.setInput('bookQueryToken', initialQueryToken);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
fixture.componentRef.setInput('books', nextBooks);
|
||||
fixture.componentRef.setInput('bookQueryToken', {query: 'second'});
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('re-arms pagination after a next-page request completes without new rows', () => {
|
||||
const loadNextPageSpy = vi.fn();
|
||||
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
|
||||
]);
|
||||
component.loadNextPage.subscribe(loadNextPageSpy);
|
||||
|
||||
fixture.componentRef.setInput('books', books);
|
||||
fixture.componentRef.setInput('virtualRowCount', 51);
|
||||
fixture.componentRef.setInput('isFetchingNextPage', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
fixture.componentRef.setInput('isFetchingNextPage', true);
|
||||
fixture.detectChanges();
|
||||
fixture.componentRef.setInput('isFetchingNextPage', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
fixture.componentRef.setInput('virtualRowCount', 52);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('can request the next page again when loaded books grow but rendered rows do not', () => {
|
||||
const loadNextPageSpy = vi.fn();
|
||||
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
|
||||
]);
|
||||
component.loadNextPage.subscribe(loadNextPageSpy);
|
||||
|
||||
fixture.componentRef.setInput('books', books);
|
||||
fixture.componentRef.setInput('virtualRowCount', 51);
|
||||
fixture.componentRef.setInput('loadedBookCount', 50);
|
||||
fixture.componentRef.setInput('isFetchingNextPage', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
fixture.componentRef.setInput('isFetchingNextPage', true);
|
||||
fixture.detectChanges();
|
||||
fixture.componentRef.setInput('loadedBookCount', 60);
|
||||
fixture.componentRef.setInput('isFetchingNextPage', false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(loadNextPageSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('requests metadata lock without mutating the input book', () => {
|
||||
const book = makeBook(1, 'Alpha');
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 0, key: 1, start: 0, size: 46, end: 46, lane: 0}
|
||||
]);
|
||||
fixture.componentRef.setInput('books', [book]);
|
||||
fixture.componentRef.setInput('visibleColumns', [{field: 'title', header: 'Title'}]);
|
||||
fixture.detectChanges();
|
||||
|
||||
component.toggleMetadataLock(book.metadata);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(book.metadata?.allMetadataLocked).toBe(false);
|
||||
expect(bookMetadataManageService.toggleAllLock).toHaveBeenCalledWith(new Set([1]), 'LOCK');
|
||||
});
|
||||
|
||||
it('disables a row lock button while that book lock request is in flight', () => {
|
||||
const lockRequest = new Subject<void>();
|
||||
bookMetadataManageService.toggleAllLock.mockReturnValue(lockRequest.asObservable());
|
||||
const book = makeBook(1, 'Alpha');
|
||||
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
|
||||
{index: 0, key: 1, start: 0, size: 46, end: 46, lane: 0}
|
||||
]);
|
||||
fixture.componentRef.setInput('books', [book]);
|
||||
fixture.componentRef.setInput('visibleColumns', [{field: 'title', header: 'Title'}]);
|
||||
fixture.detectChanges();
|
||||
|
||||
component.toggleMetadataLock(book.metadata);
|
||||
fixture.detectChanges();
|
||||
|
||||
const host = fixture.nativeElement as HTMLElement;
|
||||
const button = host.querySelector<HTMLButtonElement>('.metadata-lock-button');
|
||||
expect(button?.disabled).toBe(true);
|
||||
|
||||
component.toggleMetadataLock(book.metadata);
|
||||
expect(bookMetadataManageService.toggleAllLock).toHaveBeenCalledTimes(1);
|
||||
|
||||
lockRequest.next();
|
||||
lockRequest.complete();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(button?.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
-325
@@ -1,325 +0,0 @@
|
||||
import {ChangeDetectionStrategy, Component, DestroyRef, ElementRef, computed, effect, inject, input, output, signal, viewChild} from '@angular/core';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {CdkConnectedOverlay, ConnectedPosition} from '@angular/cdk/overlay';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {finalize} from 'rxjs';
|
||||
import {ColumnDef, ColumnSizingState, Header, columnResizingFeature, columnSizingFeature, functionalUpdate, injectTable, tableFeatures} from '@tanstack/angular-table';
|
||||
import {injectVirtualizer} from '@tanstack/angular-virtual';
|
||||
import {Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import {Book, BookMetadata} from '../../../model/book.model';
|
||||
import {RouteScrollPositionService} from '../../../../../shared/service/route-scroll-position.service';
|
||||
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {BookSelectionService} from '../book-selection.service';
|
||||
import {BookTableRowComponent, type BookTableRowCoverPreview, type BookTableSelectionChange} from './book-table-row.component';
|
||||
import {RATING_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
|
||||
|
||||
interface BookTableColumn {
|
||||
field: string;
|
||||
header: string;
|
||||
}
|
||||
|
||||
const ROW_HEIGHT = 46;
|
||||
const RENDER_OVERSCAN_ROWS = 16;
|
||||
const RESIZE_OVERSCAN_ROWS = 2;
|
||||
const PAGE_LOAD_AHEAD_ROWS = 40;
|
||||
const DEFAULT_COLUMN_SIZES: Record<string, number> = {
|
||||
readStatus: 72,
|
||||
title: 260,
|
||||
fileName: 240,
|
||||
authors: 220,
|
||||
categories: 220,
|
||||
pageCount: 120,
|
||||
seriesNumber: 120,
|
||||
};
|
||||
const DEFAULT_RATING_COLUMN_SIZE = 148;
|
||||
const DEFAULT_REVIEW_COUNT_COLUMN_SIZE = 120;
|
||||
const DEFAULT_TEXT_COLUMN_SIZE = 180;
|
||||
const MIN_COLUMN_SIZES: Record<string, number> = {
|
||||
readStatus: 64,
|
||||
pageCount: 96,
|
||||
seriesNumber: 96,
|
||||
};
|
||||
const DEFAULT_MIN_COLUMN_SIZE = 120;
|
||||
const MAX_COLUMN_SIZES: Record<string, number> = {
|
||||
title: 420,
|
||||
fileName: 420,
|
||||
authors: 360,
|
||||
categories: 360,
|
||||
};
|
||||
const DEFAULT_MAX_COLUMN_SIZE = 280;
|
||||
const features = tableFeatures({columnSizingFeature, columnResizingFeature});
|
||||
const COVER_OVERLAY_POSITIONS: ConnectedPosition[] = [
|
||||
{originX: 'end', originY: 'center', overlayX: 'start', overlayY: 'center', offsetX: 8},
|
||||
{originX: 'start', originY: 'center', overlayX: 'end', overlayY: 'center', offsetX: -8},
|
||||
{originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top', offsetX: 8},
|
||||
{originX: 'end', originY: 'bottom', overlayX: 'start', overlayY: 'bottom', offsetX: 8},
|
||||
];
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-table',
|
||||
standalone: true,
|
||||
templateUrl: './book-table.component.html',
|
||||
imports: [
|
||||
CdkConnectedOverlay,
|
||||
BookTableRowComponent,
|
||||
Checkbox,
|
||||
FormsModule,
|
||||
TranslocoDirective,
|
||||
CoverComponent
|
||||
],
|
||||
styleUrls: ['./book-table.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class BookTableComponent {
|
||||
readonly selectAllRequested = output<void>();
|
||||
readonly loadNextPage = output<void>();
|
||||
|
||||
readonly books = input<Book[]>([]);
|
||||
readonly visibleColumns = input<BookTableColumn[]>([]);
|
||||
readonly virtualRowCount = input(0);
|
||||
readonly loadedBookCount = input<number | null>(null);
|
||||
readonly isFetchingNextPage = input(false);
|
||||
readonly useSquareCovers = input(false);
|
||||
readonly bookQueryToken = input<unknown>(undefined);
|
||||
|
||||
private readonly activatedRoute = inject(ActivatedRoute);
|
||||
private readonly scrollService = inject(RouteScrollPositionService);
|
||||
protected readonly bookSelectionService = inject(BookSelectionService);
|
||||
private readonly bookMetadataManageService = inject(BookMetadataManageService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
|
||||
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute, 'table')) ?? 0;
|
||||
|
||||
private readonly columnSizing = signal<ColumnSizingState>({});
|
||||
protected readonly coverPreview = signal<BookTableRowCoverPreview | null>(null);
|
||||
private readonly pendingLockBookIds = signal<Set<number>>(new Set());
|
||||
|
||||
protected readonly coverOverlayPositions = COVER_OVERLAY_POSITIONS;
|
||||
|
||||
private readonly columnDefs = computed<ColumnDef<typeof features, Book>[]>(() => [
|
||||
{id: 'select', header: '', size: 42, minSize: 42, maxSize: 42, enableResizing: false},
|
||||
{id: 'lock', header: '', size: 42, minSize: 42, maxSize: 42, enableResizing: false},
|
||||
{id: 'cover', header: '', size: 56, minSize: 56, maxSize: 56, enableResizing: false},
|
||||
...this.visibleColumns().map(column => ({
|
||||
id: column.field,
|
||||
header: column.header,
|
||||
size: this.defaultColumnSize(column.field),
|
||||
minSize: this.minColumnSize(column.field),
|
||||
maxSize: this.maxColumnSize(column.field),
|
||||
})),
|
||||
]);
|
||||
|
||||
readonly table = injectTable(() => ({
|
||||
features,
|
||||
data: this.books(),
|
||||
columns: this.columnDefs(),
|
||||
getRowId: book => String(book.id),
|
||||
columnResizeMode: 'onChange',
|
||||
state: {
|
||||
columnSizing: this.columnSizing(),
|
||||
},
|
||||
onColumnSizingChange: updater => {
|
||||
this.columnSizing.update(current => functionalUpdate(updater, current));
|
||||
},
|
||||
}));
|
||||
|
||||
readonly visibleCellIds = computed(() => ['select', 'lock', 'cover', ...this.visibleColumns().map(column => column.field)]);
|
||||
readonly ariaRowCount = computed(() => this.rowCount() + 1);
|
||||
readonly ariaColumnCount = computed(() => this.visibleCellIds().length);
|
||||
readonly isColumnResizing = computed(() => Boolean(this.table.atoms.columnResizing.get().isResizingColumn));
|
||||
readonly rowCount = computed(() => Math.max(this.virtualRowCount(), this.books().length));
|
||||
readonly columnSizeVars = computed<Record<string, number | string>>(() => {
|
||||
this.columnSizing();
|
||||
this.visibleColumns();
|
||||
|
||||
const headers = this.table.getFlatHeaders();
|
||||
const styles = headers.reduce<Record<string, number | string>>((columnStyles, header) => {
|
||||
columnStyles[`--book-table-col-${header.column.id}-size`] = header.column.getSize();
|
||||
return columnStyles;
|
||||
}, {});
|
||||
|
||||
styles['--book-table-grid-template'] = this.table.getAllFlatColumns()
|
||||
.map(column => `calc(var(--book-table-col-${column.id}-size) * 1px)`)
|
||||
.join(' ');
|
||||
|
||||
return styles;
|
||||
});
|
||||
readonly tableWidth = computed(() => {
|
||||
this.columnSizing();
|
||||
this.visibleColumns();
|
||||
return this.table.getAllFlatColumns().reduce((width, column) => width + column.getSize(), 0);
|
||||
});
|
||||
readonly allLoadedBooksSelected = computed(() => {
|
||||
const books = this.books();
|
||||
return books.length > 0 && books.every(book => this.bookSelectionService.isBookSelected(book));
|
||||
});
|
||||
readonly someBooksSelected = computed(() => {
|
||||
return this.bookSelectionService.selectedCount() > 0 && !this.allLoadedBooksSelected();
|
||||
});
|
||||
|
||||
readonly rowVirtualizer = injectVirtualizer<HTMLElement, HTMLElement>(() => ({
|
||||
scrollElement: this.scrollElement(),
|
||||
count: this.rowCount(),
|
||||
estimateSize: () => ROW_HEIGHT,
|
||||
overscan: this.isColumnResizing() ? RESIZE_OVERSCAN_ROWS : RENDER_OVERSCAN_ROWS,
|
||||
initialOffset: this.initialScrollOffset,
|
||||
getItemKey: index => this.books()[index]?.id ?? `loading-${index}`,
|
||||
}));
|
||||
|
||||
constructor() {
|
||||
this.scrollService.trackRoute({
|
||||
scrollElement: this.scrollElement,
|
||||
route: this.activatedRoute,
|
||||
destroyRef: this.destroyRef,
|
||||
keySuffix: 'table',
|
||||
dismissOverlaysBeforeSave: true,
|
||||
beforeSave: () => this.clearCoverPreview(),
|
||||
});
|
||||
}
|
||||
|
||||
private readonly measureRowsEffect = effect(() => {
|
||||
this.rowCount();
|
||||
this.visibleColumns();
|
||||
queueMicrotask(() => this.rowVirtualizer.measure());
|
||||
});
|
||||
|
||||
private lastLoadRequestLoadedBookCount: number | undefined;
|
||||
private lastSeenQueryToken: unknown;
|
||||
private readonly paginatorEffect = effect(() => {
|
||||
const queryToken = this.bookQueryToken();
|
||||
if (queryToken !== this.lastSeenQueryToken) {
|
||||
this.lastLoadRequestLoadedBookCount = undefined;
|
||||
this.lastSeenQueryToken = queryToken;
|
||||
}
|
||||
|
||||
const items = this.books();
|
||||
const loadedBookCount = this.loadedBookCount() ?? items.length;
|
||||
const lastVirtualItem = this.rowVirtualizer.getVirtualItems().at(-1);
|
||||
if (!lastVirtualItem || items.length === 0) return;
|
||||
if (lastVirtualItem.index < items.length - PAGE_LOAD_AHEAD_ROWS) return;
|
||||
if (items.length >= this.virtualRowCount() || this.isFetchingNextPage()) return;
|
||||
if (this.lastLoadRequestLoadedBookCount === loadedBookCount) {
|
||||
this.lastLoadRequestLoadedBookCount = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastLoadRequestLoadedBookCount = loadedBookCount;
|
||||
this.loadNextPage.emit();
|
||||
});
|
||||
|
||||
private defaultColumnSize(field: string): number {
|
||||
const defaultSize = DEFAULT_COLUMN_SIZES[field];
|
||||
if (defaultSize !== undefined) return defaultSize;
|
||||
if (RATING_FIELDS.has(field)) return DEFAULT_RATING_COLUMN_SIZE;
|
||||
if (field.endsWith('ReviewCount')) return DEFAULT_REVIEW_COUNT_COLUMN_SIZE;
|
||||
return DEFAULT_TEXT_COLUMN_SIZE;
|
||||
}
|
||||
|
||||
private minColumnSize(field: string): number {
|
||||
return MIN_COLUMN_SIZES[field] ?? DEFAULT_MIN_COLUMN_SIZE;
|
||||
}
|
||||
|
||||
private maxColumnSize(field: string): number {
|
||||
return MAX_COLUMN_SIZES[field] ?? DEFAULT_MAX_COLUMN_SIZE;
|
||||
}
|
||||
|
||||
isRowSelected(book: Book): boolean {
|
||||
return this.bookSelectionService.isBookSelected(book);
|
||||
}
|
||||
|
||||
startColumnResize(header: Header<typeof features, Book, unknown>, event: MouseEvent | TouchEvent): void {
|
||||
event.stopPropagation();
|
||||
if (event.cancelable) {
|
||||
event.preventDefault();
|
||||
}
|
||||
header.getResizeHandler()(event);
|
||||
}
|
||||
|
||||
scrollToTop(): void {
|
||||
const scrollElement = this.scrollElement()?.nativeElement;
|
||||
if (scrollElement) {
|
||||
scrollElement.scrollTop = 0;
|
||||
}
|
||||
this.rowVirtualizer.scrollToOffset(0);
|
||||
}
|
||||
|
||||
onHeaderCheckboxChange(checked: boolean): void {
|
||||
if (checked) {
|
||||
this.selectAllRequested.emit();
|
||||
return;
|
||||
}
|
||||
|
||||
this.bookSelectionService.deselectAll();
|
||||
}
|
||||
|
||||
onBookSelectionChange(change: BookTableSelectionChange): void {
|
||||
this.bookSelectionService.handleBookSelection(change.book, change.checked);
|
||||
}
|
||||
|
||||
showCoverPreview(preview: BookTableRowCoverPreview): void {
|
||||
this.coverPreview.set(preview);
|
||||
}
|
||||
|
||||
clearCoverPreview(): void {
|
||||
this.coverPreview.set(null);
|
||||
}
|
||||
|
||||
hideCoverPreview(bookId: number): void {
|
||||
if (this.coverPreview()?.book.id === bookId) {
|
||||
this.clearCoverPreview();
|
||||
}
|
||||
}
|
||||
|
||||
isMetadataLockPending(bookId: number): boolean {
|
||||
return this.pendingLockBookIds().has(bookId);
|
||||
}
|
||||
|
||||
toggleMetadataLock(metadata: BookMetadata): void {
|
||||
if (this.isMetadataLockPending(metadata.bookId)) return;
|
||||
|
||||
const lockAction = isMetadataFullyLocked(metadata) ? 'UNLOCK' : 'LOCK';
|
||||
this.setMetadataLockPending(metadata.bookId, true);
|
||||
|
||||
this.bookMetadataManageService.toggleAllLock(new Set([metadata.bookId]), lockAction)
|
||||
.pipe(
|
||||
finalize(() => this.setMetadataLockPending(metadata.bookId, false)),
|
||||
takeUntilDestroyed(this.destroyRef)
|
||||
)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedSummary') : this.t.translate('book.table.toast.metadataUnlockedSummary'),
|
||||
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedDetail') : this.t.translate('book.table.toast.metadataUnlockedDetail'),
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedSummary') : this.t.translate('book.table.toast.unlockFailedSummary'),
|
||||
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedDetail') : this.t.translate('book.table.toast.unlockFailedDetail'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private setMetadataLockPending(bookId: number, pending: boolean): void {
|
||||
this.pendingLockBookIds.update(current => {
|
||||
if (current.has(bookId) === pending) return current;
|
||||
|
||||
const next = new Set(current);
|
||||
if (pending) {
|
||||
next.add(bookId);
|
||||
} else {
|
||||
next.delete(bookId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookMetadata} from '../../../model/book.model';
|
||||
import {LOCK_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
|
||||
|
||||
describe('book-table helpers', () => {
|
||||
it('uses the explicit allMetadataLocked value when present', () => {
|
||||
expect(isMetadataFullyLocked({bookId: 1, allMetadataLocked: true})).toBe(true);
|
||||
expect(isMetadataFullyLocked({bookId: 1, allMetadataLocked: false, titleLocked: true})).toBe(false);
|
||||
});
|
||||
|
||||
it('does not infer a full lock from partial metadata', () => {
|
||||
expect(isMetadataFullyLocked({bookId: 1, titleLocked: true, authorsLocked: true})).toBe(false);
|
||||
});
|
||||
|
||||
it('requires every metadata lock field to be true when the explicit flag is absent', () => {
|
||||
const metadata = {
|
||||
bookId: 1,
|
||||
...Object.fromEntries(LOCK_FIELDS.map(field => [field, true])),
|
||||
} satisfies BookMetadata;
|
||||
|
||||
expect(isMetadataFullyLocked(metadata)).toBe(true);
|
||||
expect(isMetadataFullyLocked({...metadata, titleLocked: false})).toBe(false);
|
||||
});
|
||||
});
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
import {BookMetadata} from '../../../model/book.model';
|
||||
|
||||
const RATING_FIELD_KEYS = [
|
||||
'rating',
|
||||
'amazonRating',
|
||||
'goodreadsRating',
|
||||
'hardcoverRating',
|
||||
'ranobedbRating',
|
||||
'lubimyczytacRating',
|
||||
'audibleRating',
|
||||
] satisfies readonly (keyof BookMetadata)[];
|
||||
|
||||
export const RATING_FIELDS = new Set<keyof BookMetadata>(RATING_FIELD_KEYS);
|
||||
|
||||
export const LOCK_FIELDS = [
|
||||
'titleLocked',
|
||||
'subtitleLocked',
|
||||
'publisherLocked',
|
||||
'publishedDateLocked',
|
||||
'descriptionLocked',
|
||||
'seriesNameLocked',
|
||||
'seriesNumberLocked',
|
||||
'seriesTotalLocked',
|
||||
'isbn13Locked',
|
||||
'isbn10Locked',
|
||||
'openlibraryIdLocked',
|
||||
'asinLocked',
|
||||
'comicvineIdLocked',
|
||||
'goodreadsIdLocked',
|
||||
'hardcoverIdLocked',
|
||||
'hardcoverBookIdLocked',
|
||||
'googleIdLocked',
|
||||
'pageCountLocked',
|
||||
'languageLocked',
|
||||
'amazonRatingLocked',
|
||||
'amazonReviewCountLocked',
|
||||
'goodreadsRatingLocked',
|
||||
'goodreadsReviewCountLocked',
|
||||
'hardcoverRatingLocked',
|
||||
'hardcoverReviewCountLocked',
|
||||
'lubimyczytacIdLocked',
|
||||
'lubimyczytacRatingLocked',
|
||||
'ranobedbIdLocked',
|
||||
'ranobedbRatingLocked',
|
||||
'audibleIdLocked',
|
||||
'audibleRatingLocked',
|
||||
'audibleReviewCountLocked',
|
||||
'applebooksIdLocked',
|
||||
'applebooksRatingLocked',
|
||||
'applebooksReviewCountLocked',
|
||||
'authorsLocked',
|
||||
'categoriesLocked',
|
||||
'moodsLocked',
|
||||
'tagsLocked',
|
||||
'coverLocked',
|
||||
'audiobookCoverLocked',
|
||||
'reviewsLocked',
|
||||
'narratorLocked',
|
||||
'abridgedLocked',
|
||||
'ageRatingLocked',
|
||||
'contentRatingLocked',
|
||||
] satisfies readonly (keyof BookMetadata)[];
|
||||
|
||||
export function isMetadataFullyLocked(metadata: BookMetadata): boolean {
|
||||
if (typeof metadata.allMetadataLocked === 'boolean') {
|
||||
return metadata.allMetadataLocked;
|
||||
}
|
||||
return LOCK_FIELDS.every(field => metadata[field] === true);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import {computed, signal, untracked} from '@angular/core';
|
||||
|
||||
export type DeferredRenderMode = 'reset' | 'refresh';
|
||||
|
||||
export class DeferredRenderState<T> {
|
||||
private readonly _value = signal<T | undefined>(undefined);
|
||||
readonly value = this._value.asReadonly();
|
||||
|
||||
private readonly _isRefreshing = signal(false);
|
||||
readonly isRefreshing = this._isRefreshing.asReadonly();
|
||||
|
||||
readonly hasValue = computed(() => this._value() !== undefined);
|
||||
|
||||
private activeRequestId = 0;
|
||||
|
||||
begin(mode: DeferredRenderMode): number {
|
||||
this.activeRequestId += 1;
|
||||
|
||||
if (mode === 'reset') {
|
||||
this._value.set(undefined);
|
||||
this._isRefreshing.set(false);
|
||||
} else {
|
||||
this._isRefreshing.set(untracked(() => this._value() !== undefined));
|
||||
}
|
||||
|
||||
return this.activeRequestId;
|
||||
}
|
||||
|
||||
commit(requestId: number, value: T): boolean {
|
||||
if (requestId !== this.activeRequestId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._value.set(value);
|
||||
this._isRefreshing.set(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
cancel(requestId: number): void {
|
||||
if (requestId !== this.activeRequestId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._isRefreshing.set(false);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {FilterLabelHelper} from './filter-label.helper';
|
||||
|
||||
describe('FilterLabelHelper', () => {
|
||||
it('returns friendly names for known filter types and capitalizes unknown names', () => {
|
||||
expect(FilterLabelHelper.getFilterTypeName('personalRating')).toBe('Personal Rating');
|
||||
expect(FilterLabelHelper.getFilterTypeName('customFilter')).toBe('CustomFilter');
|
||||
});
|
||||
|
||||
it('maps numeric ids to configured range labels', () => {
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 1)).toBe('1–10 MB');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 3)).toBe('200–400 pages');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 0)).toBe('Outstanding (95–100%)');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 7)).toBe('7');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 5)).toBe('4.5+');
|
||||
});
|
||||
|
||||
it('falls back to the raw value when a numeric id is not recognized', () => {
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 999)).toBe('999');
|
||||
expect(FilterLabelHelper.getFilterDisplayValue('tag', 'favorite')).toBe('favorite');
|
||||
});
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingOptions10, ratingRanges} from './book-filter/book-filter.config';
|
||||
|
||||
export class FilterLabelHelper {
|
||||
private static readonly FILTER_TYPE_MAP: Record<string, string> = {
|
||||
author: 'Author',
|
||||
category: 'Genre',
|
||||
series: 'Series',
|
||||
publisher: 'Publisher',
|
||||
readStatus: 'Read Status',
|
||||
personalRating: 'Personal Rating',
|
||||
publishedDate: 'Year Published',
|
||||
matchScore: 'Metadata Match Score',
|
||||
language: 'Language',
|
||||
bookType: 'Book Type',
|
||||
shelfStatus: 'Shelf Status',
|
||||
fileSize: 'File Size',
|
||||
pageCount: 'Page Count',
|
||||
amazonRating: 'Amazon Rating',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
lubimyczytacRating: 'Lubimyczytac Rating',
|
||||
ranobedbRating: 'RanobeDB Rating',
|
||||
audibleRating: 'Audible Rating',
|
||||
mood: 'Mood',
|
||||
tag: 'Tag',
|
||||
};
|
||||
|
||||
static getFilterTypeName(filterType: string): string {
|
||||
return this.FILTER_TYPE_MAP[filterType] || this.capitalize(filterType);
|
||||
}
|
||||
|
||||
static getFilterDisplayValue(filterType: string, value: string | number): string {
|
||||
const numericValue = typeof value === 'string' ? Number(value) : value;
|
||||
|
||||
switch (filterType.toLowerCase()) {
|
||||
case 'filesize': {
|
||||
const fileSizeRange = fileSizeRanges.find(r => r.id === numericValue);
|
||||
if (fileSizeRange) return fileSizeRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'pagecount': {
|
||||
const pageCountRange = pageCountRanges.find(r => r.id === numericValue);
|
||||
if (pageCountRange) return pageCountRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'matchscore': {
|
||||
const matchScoreRange = matchScoreRanges.find(r => r.id === numericValue);
|
||||
if (matchScoreRange) return matchScoreRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'personalrating': {
|
||||
const personalRating = ratingOptions10.find(r => r.id === numericValue);
|
||||
if (personalRating) return personalRating.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'amazonrating':
|
||||
case 'goodreadsrating':
|
||||
case 'hardcoverrating':
|
||||
case 'lubimyczytacrating':
|
||||
case 'ranobedbrating':
|
||||
case 'audiblerating': {
|
||||
const ratingRange = ratingRanges.find(r => r.id === numericValue);
|
||||
if (ratingRange) return ratingRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
default:
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static capitalize(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {filterBooksBySearchTerm, normalizeSearchTerm} from './HeaderFilter';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
fileName: `Book ${id}.epub`,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Title ${id}`,
|
||||
seriesName: `Series ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
categories: [`Category ${id}`],
|
||||
isbn10: `ISBN10-${id}`,
|
||||
isbn13: `ISBN13-${id}`
|
||||
},
|
||||
primaryFile: {id, bookId: id, fileName: `Book ${id}.epub`, bookType: 'EPUB'},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('HeaderFilter', () => {
|
||||
it('normalizes unicode, punctuation, whitespace, and empty input', () => {
|
||||
expect(normalizeSearchTerm('')).toBe('');
|
||||
expect(normalizeSearchTerm(' Ætna øresund! ')).toBe('aetna oresund');
|
||||
expect(normalizeSearchTerm('Łódź / Straße')).toBe('lodz strasse');
|
||||
});
|
||||
|
||||
it('keeps the full book list for short terms and filters by searchable fields', () => {
|
||||
const books = [
|
||||
makeBook(1),
|
||||
makeBook(2, {
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'The Other Title',
|
||||
seriesName: 'Other Series',
|
||||
authors: ['Different Author'],
|
||||
categories: ['Biography'],
|
||||
isbn10: '999',
|
||||
isbn13: '888'
|
||||
},
|
||||
primaryFile: {id: 2, bookId: 2, fileName: 'Notes.txt', bookType: 'EPUB'}
|
||||
}),
|
||||
makeBook(3, {
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Completely Different',
|
||||
seriesName: 'Third Series',
|
||||
authors: ['Series Match'],
|
||||
categories: ['History'],
|
||||
isbn10: '111',
|
||||
isbn13: '222'
|
||||
},
|
||||
primaryFile: {id: 3, bookId: 3, fileName: 'Search Target.epub', bookType: 'EPUB'}
|
||||
})
|
||||
];
|
||||
|
||||
expect(filterBooksBySearchTerm(books, '')).toBe(books);
|
||||
expect(filterBooksBySearchTerm(books, 'a')).toBe(books);
|
||||
|
||||
expect(filterBooksBySearchTerm(books, 'other title').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, 'other series').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, 'series match').map(book => book.id)).toEqual([3]);
|
||||
expect(filterBooksBySearchTerm(books, 'biography').map(book => book.id)).toEqual([2]);
|
||||
expect(filterBooksBySearchTerm(books, '222').map(book => book.id)).toEqual([3]);
|
||||
expect(filterBooksBySearchTerm(books, 'search target').map(book => book.id)).toEqual([3]);
|
||||
});
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
import {Book} from '../../../model/book.model';
|
||||
|
||||
export function normalizeSearchTerm(str: string): string {
|
||||
if (!str) return '';
|
||||
// Normalize Unicode combining characters (e.g., é -> e)
|
||||
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||||
s = s.replace(/ø/gi, 'o')
|
||||
.replace(/ł/gi, 'l')
|
||||
.replace(/æ/gi, 'ae')
|
||||
.replace(/œ/gi, 'oe')
|
||||
.replace(/ß/g, 'ss');
|
||||
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
|
||||
s = s.replace(/\s+/g, ' ').trim();
|
||||
return s.toLowerCase();
|
||||
}
|
||||
|
||||
export function filterBooksBySearchTerm(books: Book[], term: string): Book[] {
|
||||
const normalizedTerm = normalizeSearchTerm(term || '').trim();
|
||||
if (normalizedTerm.length < 2) {
|
||||
return books;
|
||||
}
|
||||
|
||||
return books.filter(book => {
|
||||
const title = book.metadata?.title || '';
|
||||
const series = book.metadata?.seriesName || '';
|
||||
const authors = book.metadata?.authors || [];
|
||||
const categories = book.metadata?.categories || [];
|
||||
const isbn = book.metadata?.isbn10 || '';
|
||||
const isbn13 = book.metadata?.isbn13 || '';
|
||||
const fileName = book.primaryFile?.fileName || '';
|
||||
|
||||
const matchesTitle = normalizeSearchTerm(title).includes(normalizedTerm);
|
||||
const matchesSeries = normalizeSearchTerm(series).includes(normalizedTerm);
|
||||
const matchesAuthor = authors.some(author => normalizeSearchTerm(author).includes(normalizedTerm));
|
||||
const matchesCategory = categories.some(category => normalizeSearchTerm(category).includes(normalizedTerm));
|
||||
const matchesIsbn = normalizeSearchTerm(isbn).includes(normalizedTerm) || normalizeSearchTerm(isbn13).includes(normalizedTerm);
|
||||
const matchesFileName = normalizeSearchTerm(fileName).includes(normalizedTerm);
|
||||
|
||||
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn || matchesFileName;
|
||||
});
|
||||
}
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
|
||||
import {SeriesCollapseFilter} from './SeriesCollapseFilter';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {Book} from '../../../model/book.model';
|
||||
|
||||
function makeBook(id: number, seriesName?: string, seriesNumber?: number): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`,
|
||||
seriesName,
|
||||
seriesNumber
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('SeriesCollapseFilter', () => {
|
||||
let userService: {currentUser: ReturnType<typeof vi.fn>; getCurrentUser: ReturnType<typeof vi.fn>; updateUserSetting: ReturnType<typeof vi.fn>};
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let service: SeriesCollapseFilter;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({id: 1})),
|
||||
getCurrentUser: vi.fn(() => null),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageService = {add: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SeriesCollapseFilter,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MessageService, useValue: messageService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(SeriesCollapseFilter);
|
||||
});
|
||||
|
||||
it('returns books unchanged when collapse is disabled or series expansion is forced', () => {
|
||||
const books = [makeBook(1), makeBook(2, 'Series', 2)];
|
||||
|
||||
expect(service.collapseBooks(books, false, false)).toBe(books);
|
||||
expect(service.collapseBooks([], false, true)).toEqual([]);
|
||||
expect(service.collapseBooks(books, true, true)).toBe(books);
|
||||
});
|
||||
|
||||
it('collapses series into grouped books with the lowest numbered entry first', () => {
|
||||
const books = [
|
||||
makeBook(1, 'Series', 2),
|
||||
makeBook(2, 'Series', 1),
|
||||
makeBook(3),
|
||||
makeBook(4, 'Other Series', 5)
|
||||
];
|
||||
|
||||
const collapsed = service.collapseBooks(books, false, true);
|
||||
|
||||
expect(collapsed).toEqual([
|
||||
makeBook(3),
|
||||
{
|
||||
...makeBook(2, 'Series', 1),
|
||||
seriesBooks: [books[0], books[1]],
|
||||
seriesCount: 2
|
||||
},
|
||||
{
|
||||
...makeBook(4, 'Other Series', 5),
|
||||
seriesBooks: [books[3]],
|
||||
seriesCount: 1
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
it('persists context-aware and global preferences with legacy fallbacks', () => {
|
||||
const user = {
|
||||
id: 1,
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1,
|
||||
seriesCollapse: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 99,
|
||||
preferences: {
|
||||
sortKey: 'title',
|
||||
sortDir: 'ASC',
|
||||
view: 'TABLE',
|
||||
coverSize: 1,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
userService.getCurrentUser.mockReturnValue(user);
|
||||
|
||||
service.setContext('LIBRARY', 99);
|
||||
expect(service.seriesCollapsed()).toBe(false);
|
||||
|
||||
service.setCollapsed(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({
|
||||
overrides: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entityType: 'LIBRARY',
|
||||
entityId: 99,
|
||||
preferences: expect.objectContaining({
|
||||
seriesCollapsed: true
|
||||
})
|
||||
})
|
||||
])
|
||||
}));
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved'
|
||||
}));
|
||||
|
||||
userService.updateUserSetting.mockClear();
|
||||
messageService.add.mockClear();
|
||||
|
||||
service.setContext(null, null);
|
||||
service.setCollapsed(false);
|
||||
vi.advanceTimersByTime(500);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(1, 'entityViewPreferences', expect.objectContaining({
|
||||
global: expect.objectContaining({
|
||||
seriesCollapsed: false
|
||||
})
|
||||
}));
|
||||
});
|
||||
});
|
||||
-169
@@ -1,169 +0,0 @@
|
||||
import {effect, inject, Injectable, signal} from '@angular/core';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SeriesCollapseFilter {
|
||||
private static readonly PERSIST_DELAY_MS = 500;
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
|
||||
private readonly _seriesCollapsed = signal(false);
|
||||
readonly seriesCollapsed = this._seriesCollapsed.asReadonly();
|
||||
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
||||
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (user) {
|
||||
this.applyPreference();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setContext(type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null, id: number | null): void {
|
||||
if (type && id) {
|
||||
this.currentContext = {type, id};
|
||||
} else {
|
||||
this.currentContext = null;
|
||||
}
|
||||
this.applyPreference();
|
||||
}
|
||||
|
||||
setCollapsed(value: boolean): void {
|
||||
this._seriesCollapsed.set(value);
|
||||
this.schedulePersist(value);
|
||||
}
|
||||
|
||||
private applyPreference(): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const prefs = user?.userSettings?.entityViewPreferences;
|
||||
|
||||
let collapsed = false;
|
||||
|
||||
if (prefs) {
|
||||
// Backward compatibility: check for old 'seriesCollapse' field
|
||||
const legacyGlobalSeriesCollapse = (prefs.global as { seriesCollapse?: boolean }).seriesCollapse;
|
||||
collapsed = prefs.global?.seriesCollapsed ?? legacyGlobalSeriesCollapse ?? false;
|
||||
|
||||
if (this.currentContext) {
|
||||
const override = prefs.overrides?.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
if (override) {
|
||||
const legacyOverrideSeriesCollapse = (override.preferences as { seriesCollapse?: boolean }).seriesCollapse;
|
||||
if (override.preferences.seriesCollapsed !== undefined) {
|
||||
collapsed = override.preferences.seriesCollapsed;
|
||||
} else if (legacyOverrideSeriesCollapse !== undefined) {
|
||||
collapsed = legacyOverrideSeriesCollapse;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this._seriesCollapsed() !== collapsed) {
|
||||
this._seriesCollapsed.set(collapsed);
|
||||
}
|
||||
}
|
||||
|
||||
collapseBooks(books: Book[], forceExpandSeries?: boolean, isSeriesCollapsed: boolean = this.seriesCollapsed()): Book[] {
|
||||
const shouldCollapse = forceExpandSeries ? false : isSeriesCollapsed;
|
||||
if (!shouldCollapse || books.length === 0) return books;
|
||||
|
||||
const sourceBooks = [...books];
|
||||
const seriesMap = new Map<string, Book[]>();
|
||||
const collapsedBooks: Book[] = [];
|
||||
|
||||
for (const book of sourceBooks) {
|
||||
const seriesName = book.metadata?.seriesName?.trim();
|
||||
if (seriesName) {
|
||||
if (!seriesMap.has(seriesName)) {
|
||||
seriesMap.set(seriesName, []);
|
||||
}
|
||||
seriesMap.get(seriesName)!.push(book);
|
||||
} else {
|
||||
collapsedBooks.push(book);
|
||||
}
|
||||
}
|
||||
|
||||
for (const group of seriesMap.values()) {
|
||||
const sortedGroup = group.slice().sort((a, b) => {
|
||||
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||
return aNum - bNum;
|
||||
});
|
||||
const firstBook = sortedGroup[0];
|
||||
collapsedBooks.push({
|
||||
...firstBook,
|
||||
seriesBooks: group,
|
||||
seriesCount: group.length
|
||||
});
|
||||
}
|
||||
|
||||
return collapsedBooks;
|
||||
}
|
||||
|
||||
private schedulePersist(isCollapsed: boolean): void {
|
||||
if (this.persistTimeout) {
|
||||
clearTimeout(this.persistTimeout);
|
||||
}
|
||||
|
||||
this.persistTimeout = setTimeout(() => {
|
||||
this.persistCollapsePreference(isCollapsed);
|
||||
}, SeriesCollapseFilter.PERSIST_DELAY_MS);
|
||||
}
|
||||
|
||||
private persistCollapsePreference(isCollapsed: boolean): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
if (!user) return;
|
||||
|
||||
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1.0,
|
||||
seriesCollapsed: false
|
||||
},
|
||||
overrides: []
|
||||
});
|
||||
|
||||
if (!prefs.overrides) {
|
||||
prefs.overrides = [];
|
||||
}
|
||||
|
||||
if (this.currentContext) {
|
||||
let override = prefs.overrides.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
|
||||
if (!override) {
|
||||
override = {
|
||||
entityType: this.currentContext.type,
|
||||
entityId: this.currentContext.id,
|
||||
preferences: {
|
||||
...prefs.global,
|
||||
seriesCollapsed: isCollapsed
|
||||
}
|
||||
};
|
||||
prefs.overrides.push(override);
|
||||
} else {
|
||||
override.preferences.seriesCollapsed = isCollapsed;
|
||||
}
|
||||
} else {
|
||||
prefs.global.seriesCollapsed = isCollapsed;
|
||||
}
|
||||
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved',
|
||||
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}${this.currentContext ? ' for this view' : ' globally'}.`,
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||
import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service';
|
||||
|
||||
describe('SidebarFilterTogglePrefService', () => {
|
||||
let originalInnerWidth: number;
|
||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||
let localStorageService: {
|
||||
get: ReturnType<typeof vi.fn>;
|
||||
set: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
const setViewport = (width: number) => {
|
||||
Object.defineProperty(window, 'innerWidth', {
|
||||
configurable: true,
|
||||
value: width,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalInnerWidth = window.innerWidth;
|
||||
messageService = {add: vi.fn()};
|
||||
localStorageService = {
|
||||
get: vi.fn(() => null),
|
||||
set: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setViewport(originalInnerWidth);
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
const createService = () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SidebarFilterTogglePrefService,
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: LocalStorageService, useValue: localStorageService},
|
||||
{provide: TranslocoService, useValue: {translate: (key: string) => key}},
|
||||
],
|
||||
});
|
||||
|
||||
return TestBed.inject(SidebarFilterTogglePrefService);
|
||||
};
|
||||
|
||||
it('loads the stored preference on wide screens', () => {
|
||||
setViewport(1280);
|
||||
localStorageService.get.mockReturnValue(false);
|
||||
|
||||
const service = createService();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.get).toHaveBeenCalledWith('showSidebarFilter');
|
||||
});
|
||||
|
||||
it('forces the filter closed on narrow screens', () => {
|
||||
setViewport(640);
|
||||
|
||||
const service = createService();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('toggles the visibility and persists the updated value', () => {
|
||||
setViewport(1280);
|
||||
const service = createService();
|
||||
|
||||
service.toggle();
|
||||
|
||||
expect(service.showFilter()).toBe(false);
|
||||
expect(localStorageService.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||
});
|
||||
|
||||
it('shows an error toast when persistence fails', () => {
|
||||
setViewport(1280);
|
||||
localStorageService.set.mockImplementation(() => {
|
||||
throw new Error('storage failed');
|
||||
});
|
||||
const service = createService();
|
||||
|
||||
service.setShowFilter(false);
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'book.filterPref.toast.saveFailedSummary',
|
||||
detail: 'book.filterPref.toast.saveFailedDetail',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
import {inject, Injectable, signal} from '@angular/core';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SidebarFilterTogglePrefService {
|
||||
|
||||
private readonly STORAGE_KEY = 'showSidebarFilter';
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly localStorageService = inject(LocalStorageService);
|
||||
|
||||
private readonly _showFilter = signal(true);
|
||||
readonly showFilter = this._showFilter.asReadonly();
|
||||
|
||||
constructor() {
|
||||
const isNarrow = window.innerWidth <= 768;
|
||||
this._showFilter.set(!isNarrow);
|
||||
this.loadFromStorage();
|
||||
}
|
||||
|
||||
toggle(): void {
|
||||
this.setShowFilter(!this.showFilter());
|
||||
}
|
||||
|
||||
setShowFilter(value: boolean): void {
|
||||
if (this._showFilter() !== value) {
|
||||
this._showFilter.set(value);
|
||||
this.savePreference(value);
|
||||
}
|
||||
}
|
||||
|
||||
private savePreference(value: boolean): void {
|
||||
try {
|
||||
this.localStorageService.set(this.STORAGE_KEY, value);
|
||||
} catch {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.filterPref.toast.saveFailedSummary'),
|
||||
detail: this.t.translate('book.filterPref.toast.saveFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadFromStorage(): void {
|
||||
const isNarrow = window.innerWidth <= 768;
|
||||
if (isNarrow) {
|
||||
this._showFilter.set(false);
|
||||
} else {
|
||||
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
|
||||
this._showFilter.set(saved !== null ? saved : true);
|
||||
}
|
||||
}
|
||||
}
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {
|
||||
doesBookMatchFilter,
|
||||
doesBookMatchReadStatus,
|
||||
filterBooksByFilters,
|
||||
isAgeRatingInRange,
|
||||
isFileSizeInRange,
|
||||
isMatchScoreInRange,
|
||||
isPageCountInRange,
|
||||
isRatingInRange,
|
||||
isRatingInRange10
|
||||
} from './sidebar-filter';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
readStatus: ReadStatus.UNREAD,
|
||||
fileSizeKb: 1500,
|
||||
metadataMatchScore: 87,
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Title ${id}`,
|
||||
authors: [`Author ${id}`],
|
||||
categories: [`Category ${id}`],
|
||||
seriesName: `Series ${id}`,
|
||||
publisher: 'Publisher',
|
||||
publishedDate: '2024-02-01',
|
||||
pageCount: 230,
|
||||
language: 'en',
|
||||
tags: ['tag-a'],
|
||||
moods: ['mood-a'],
|
||||
amazonRating: 4.3,
|
||||
goodreadsRating: 4.1,
|
||||
hardcoverRating: 4.2,
|
||||
narrator: 'Narrator',
|
||||
ageRating: 16,
|
||||
contentRating: 'PG-13',
|
||||
comicMetadata: {
|
||||
characters: ['hero'],
|
||||
teams: ['team-a'],
|
||||
locations: ['earth'],
|
||||
pencillers: ['Penciller'],
|
||||
inkers: ['Inker'],
|
||||
colorists: ['Colorist'],
|
||||
letterers: ['Letterer'],
|
||||
coverArtists: ['Cover'],
|
||||
editors: ['Editor']
|
||||
}
|
||||
},
|
||||
shelves: [{id: 7, name: 'Favorites'}],
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('sidebar-filter', () => {
|
||||
it('covers the numeric helper ranges and read status matching', () => {
|
||||
expect(isRatingInRange(null, 1)).toBe(false);
|
||||
expect(isRatingInRange(4.3, '4')).toBe(true);
|
||||
expect(isRatingInRange10(4.4, 4)).toBe(true);
|
||||
expect(isFileSizeInRange(undefined, 1)).toBe(false);
|
||||
expect(isFileSizeInRange(1500, 1)).toBe(true);
|
||||
expect(isPageCountInRange(230, '3')).toBe(true);
|
||||
expect(isAgeRatingInRange(16, 16)).toBe(true);
|
||||
expect(isAgeRatingInRange(12, 10)).toBe(true);
|
||||
expect(isMatchScoreInRange(87, 2)).toBe(true);
|
||||
expect(isMatchScoreInRange(87, 9)).toBe(false);
|
||||
expect(doesBookMatchReadStatus(makeBook(1), [ReadStatus.UNREAD])).toBe(true);
|
||||
expect(doesBookMatchReadStatus(makeBook(1, {readStatus: undefined}), [ReadStatus.UNSET])).toBe(true);
|
||||
});
|
||||
|
||||
it('matches all filter branches across or, and, and not modes', () => {
|
||||
const book = makeBook(1);
|
||||
const books = [book, makeBook(2, {
|
||||
readStatus: ReadStatus.READING,
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Other',
|
||||
authors: ['Other Author'],
|
||||
categories: ['Other Category'],
|
||||
seriesName: 'Other Series',
|
||||
publisher: 'Other Publisher',
|
||||
publishedDate: '2021-01-01',
|
||||
pageCount: 50,
|
||||
language: 'fr',
|
||||
tags: ['other-tag'],
|
||||
moods: ['other-mood'],
|
||||
amazonRating: 3.1,
|
||||
goodreadsRating: 3.2,
|
||||
hardcoverRating: 3.3,
|
||||
narrator: 'Someone Else',
|
||||
ageRating: 12,
|
||||
contentRating: 'R',
|
||||
comicMetadata: {
|
||||
characters: ['villain'],
|
||||
teams: ['team-b'],
|
||||
locations: ['mars'],
|
||||
pencillers: ['Alt Penciller'],
|
||||
inkers: ['Alt Inker'],
|
||||
colorists: ['Alt Colorist'],
|
||||
letterers: ['Alt Letterer'],
|
||||
coverArtists: ['Alt Cover'],
|
||||
editors: ['Alt Editor']
|
||||
}
|
||||
},
|
||||
shelves: []
|
||||
})];
|
||||
|
||||
expect(doesBookMatchFilter(book, 'author', ['Author 1'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'category', ['Category 1'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'series', ['Series 1'], 'not')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'bookType', ['PHYSICAL'], 'or')).toBe(false);
|
||||
expect(doesBookMatchFilter(book, 'readStatus', [ReadStatus.UNREAD], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'publisher', ['Publisher'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'matchScore', [2], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'library', [1], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'shelf', [7], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'shelfStatus', ['shelved'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(makeBook(3, {shelves: []}), 'shelfStatus', ['unshelved'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'tag', ['tag-a'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'publishedDate', ['2024'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'fileSize', [1], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'amazonRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'goodreadsRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'hardcoverRating', [4], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'language', ['en'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'pageCount', [3], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'mood', ['mood-a'], 'and')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'ageRating', ['16'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'contentRating', ['PG-13'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'narrator', ['Narrator'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicCharacter', ['hero'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicTeam', ['team-a'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicLocation', ['earth'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'comicCreator', ['Penciller:penciller'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'unknown', ['x'], 'or')).toBe(false);
|
||||
|
||||
expect(doesBookMatchFilter(makeBook(4, {isPhysical: true}), 'bookType', ['PHYSICAL'], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'author', [], 'or')).toBe(true);
|
||||
expect(doesBookMatchFilter(book, 'author', [], 'and')).toBe(false);
|
||||
|
||||
expect(filterBooksByFilters(books, null, 'or')).toBe(books);
|
||||
expect(filterBooksByFilters(books, {author: ['Author 1']}, 'or')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Other Author']}, 'not')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Author 1'], category: ['Category 1']}, 'and')).toEqual([book]);
|
||||
expect(filterBooksByFilters(books, {author: ['Other Author'], category: ['Category 1']}, 'or', 'author')).toEqual([book]);
|
||||
});
|
||||
});
|
||||
@@ -1,232 +0,0 @@
|
||||
import {ageRatingRanges, fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
||||
|
||||
export function isRatingInRange(rating: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (rating == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = ratingRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return rating >= range.min && rating < range.max;
|
||||
}
|
||||
|
||||
export function isRatingInRange10(rating: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (rating == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
return Math.round(rating) === numericId;
|
||||
}
|
||||
|
||||
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string | number): boolean {
|
||||
if (fileSizeKb == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = fileSizeRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return fileSizeKb >= range.min && fileSizeKb < range.max;
|
||||
}
|
||||
|
||||
export function isPageCountInRange(pageCount: number | undefined, rangeId: string | number): boolean {
|
||||
if (pageCount == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = pageCountRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return pageCount >= range.min && pageCount < range.max;
|
||||
}
|
||||
|
||||
export function isMatchScoreInRange(score: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (score == null) return false;
|
||||
const normalizedScore = score > 1 ? score / 100 : score;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = matchScoreRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return normalizedScore >= range.min && normalizedScore < range.max;
|
||||
}
|
||||
|
||||
export function isAgeRatingInRange(ageRating: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (ageRating == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = ageRatingRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return ageRating >= range.min && ageRating < range.max;
|
||||
}
|
||||
|
||||
export function doesBookMatchReadStatus(book: Book, selected: unknown[]): boolean {
|
||||
const status = book.readStatus ?? ReadStatus.UNSET;
|
||||
return selected.includes(status);
|
||||
}
|
||||
|
||||
export function doesBookMatchFilter(
|
||||
book: Book,
|
||||
filterType: string,
|
||||
filterValues: unknown[],
|
||||
mode: BookFilterMode
|
||||
): boolean {
|
||||
if (!Array.isArray(filterValues) || filterValues.length === 0) {
|
||||
return mode === 'or';
|
||||
}
|
||||
|
||||
const effectiveMode = mode === 'not' ? 'or' : mode;
|
||||
|
||||
switch (filterType) {
|
||||
case 'author':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.authors?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.authors?.includes(val as string));
|
||||
case 'category':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.categories?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.categories?.includes(val as string));
|
||||
case 'series':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.seriesName?.trim() === val)
|
||||
: filterValues.every(val => book.metadata?.seriesName?.trim() === val);
|
||||
case 'bookType':
|
||||
return book.isPhysical ? filterValues.includes('PHYSICAL') : filterValues.includes(book.primaryFile?.bookType);
|
||||
case 'readStatus':
|
||||
return doesBookMatchReadStatus(book, filterValues);
|
||||
case 'personalRating':
|
||||
return filterValues.some(range => isRatingInRange10(book.personalRating, range as string | number));
|
||||
case 'publisher':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.publisher === val)
|
||||
: filterValues.every(val => book.metadata?.publisher === val);
|
||||
case 'matchScore':
|
||||
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range as string | number));
|
||||
case 'library':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => val == book.libraryId)
|
||||
: filterValues.every(val => val == book.libraryId);
|
||||
case 'shelf':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.shelves?.some(s => s.id == val))
|
||||
: filterValues.every(val => book.shelves?.some(s => s.id == val));
|
||||
case 'shelfStatus': {
|
||||
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||
return filterValues.includes(shelved);
|
||||
}
|
||||
case 'tag':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.tags?.includes(val as string));
|
||||
case 'publishedDate': {
|
||||
const bookYear = book.metadata?.publishedDate
|
||||
? new Date(book.metadata.publishedDate).getFullYear()
|
||||
: null;
|
||||
return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false;
|
||||
}
|
||||
case 'fileSize':
|
||||
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range as string | number));
|
||||
case 'amazonRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range as string | number));
|
||||
case 'goodreadsRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range as string | number));
|
||||
case 'hardcoverRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range as string | number));
|
||||
case 'lubimyczytacRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.lubimyczytacRating, range as string | number));
|
||||
case 'ranobedbRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.ranobedbRating, range as string | number));
|
||||
case 'audibleRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.audibleRating, range as string | number));
|
||||
case 'language':
|
||||
return filterValues.includes(book.metadata?.language);
|
||||
case 'pageCount':
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount ?? undefined, range as string | number));
|
||||
case 'mood':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.moods?.includes(val as string));
|
||||
case 'ageRating':
|
||||
return filterValues.some(range => isAgeRatingInRange(book.metadata?.ageRating, range as string | number));
|
||||
case 'contentRating':
|
||||
return filterValues.includes(book.metadata?.contentRating);
|
||||
case 'narrator':
|
||||
return filterValues.includes(book.metadata?.narrator);
|
||||
case 'comicCharacter':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.characters?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.characters?.includes(val as string));
|
||||
case 'comicTeam':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.teams?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.teams?.includes(val as string));
|
||||
case 'comicLocation':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.locations?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.locations?.includes(val as string));
|
||||
case 'comicCreator': {
|
||||
const comic = book.metadata?.comicMetadata;
|
||||
if (!comic) return false;
|
||||
const allCreators: string[] = [];
|
||||
const roles: [string[] | undefined, string][] = [
|
||||
[comic.pencillers, 'penciller'],
|
||||
[comic.inkers, 'inker'],
|
||||
[comic.colorists, 'colorist'],
|
||||
[comic.letterers, 'letterer'],
|
||||
[comic.coverArtists, 'coverArtist'],
|
||||
[comic.editors, 'editor']
|
||||
];
|
||||
for (const [names, role] of roles) {
|
||||
if (names) {
|
||||
for (const name of names) {
|
||||
allCreators.push(`${name}:${role}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => allCreators.includes(val as string))
|
||||
: filterValues.every(val => allCreators.includes(val as string));
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function filterBooksByFilters(
|
||||
books: Book[],
|
||||
activeFilters: Record<string, unknown[]> | null,
|
||||
mode: BookFilterMode,
|
||||
excludeFilterType?: string
|
||||
): Book[] {
|
||||
if (!activeFilters) return books;
|
||||
|
||||
const filterEntries = Object.entries(activeFilters)
|
||||
.filter(([type]) => type !== excludeFilterType);
|
||||
|
||||
if (filterEntries.length === 0) return books;
|
||||
|
||||
return books.filter(book => matchesAllFilters(book, filterEntries, mode));
|
||||
}
|
||||
|
||||
function matchesAllFilters(
|
||||
book: Book,
|
||||
filterEntries: [string, unknown[]][],
|
||||
mode: BookFilterMode
|
||||
): boolean {
|
||||
if (mode === 'or') {
|
||||
for (const [filterType, filterValues] of filterEntries) {
|
||||
if (doesBookMatchFilter(book, filterType, filterValues, mode)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mode === 'not') {
|
||||
for (const [filterType, filterValues] of filterEntries) {
|
||||
if (doesBookMatchFilter(book, filterType, filterValues, mode)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
for (const [filterType, filterValues] of filterEntries) {
|
||||
if (!doesBookMatchFilter(book, filterType, filterValues, mode)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import {describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {CdkDragDrop} from '@angular/cdk/drag-drop';
|
||||
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
import {BookSorter} from './BookSorter';
|
||||
|
||||
describe('BookSorter', () => {
|
||||
it('uses default labels when no transloco service is provided', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
|
||||
expect(sorter.sortOptions[0]).toMatchObject({
|
||||
field: 'title',
|
||||
label: 'Title',
|
||||
direction: SortDirection.ASCENDING
|
||||
});
|
||||
});
|
||||
|
||||
it('uses translated labels when transloco is available', () => {
|
||||
const transloco = {
|
||||
translate: vi.fn((key: string) => `translated:${key}`)
|
||||
} as unknown as TranslocoService;
|
||||
|
||||
const sorter = new BookSorter(() => undefined, transloco);
|
||||
|
||||
expect(sorter.sortOptions[0].label).toBe('translated:book.sorting.options.title');
|
||||
});
|
||||
|
||||
it('supports legacy selectedSort getter and setter', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
const sort: SortOption = {label: 'Title', field: 'title', direction: SortDirection.ASCENDING};
|
||||
|
||||
sorter.selectedSort = sort;
|
||||
expect(sorter.selectedSort).toEqual(sort);
|
||||
|
||||
sorter.selectedSort = undefined;
|
||||
expect(sorter.selectedSortCriteria).toEqual([]);
|
||||
});
|
||||
|
||||
it('sorts by a field and toggles the primary direction on repeat', () => {
|
||||
const onSortChange = vi.fn();
|
||||
const sorter = new BookSorter(onSortChange);
|
||||
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSortCriteria).toEqual([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING}
|
||||
]);
|
||||
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSortCriteria[0].direction).toBe(SortDirection.DESCENDING);
|
||||
expect(onSortChange).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('adds, removes, toggles, and reorders criteria', () => {
|
||||
const onSortChange = vi.fn();
|
||||
const sorter = new BookSorter(onSortChange);
|
||||
|
||||
sorter.addSortCriterion('title');
|
||||
sorter.addSortCriterion('author');
|
||||
sorter.addSortCriterion('title');
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title', 'author']);
|
||||
|
||||
sorter.toggleCriterionDirection(1);
|
||||
expect(sorter.selectedSortCriteria[1].direction).toBe(SortDirection.DESCENDING);
|
||||
|
||||
sorter.reorderCriteria({
|
||||
previousIndex: 1,
|
||||
currentIndex: 0
|
||||
} as unknown as CdkDragDrop<SortOption[]>);
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['author', 'title']);
|
||||
|
||||
sorter.removeSortCriterion(0);
|
||||
expect(sorter.selectedSortCriteria.map((criterion) => criterion.field)).toEqual(['title']);
|
||||
});
|
||||
|
||||
it('omits already-used fields from available options and marks the primary icon', () => {
|
||||
const sorter = new BookSorter(() => undefined);
|
||||
|
||||
sorter.setSortCriteria([
|
||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING}
|
||||
]);
|
||||
|
||||
const titleOption = sorter.sortOptions.find((option) => option.field === 'title') as SortOption & {icon?: string};
|
||||
|
||||
expect(sorter.getAvailableSortOptions().some((option) => option.field === 'title')).toBe(false);
|
||||
expect(titleOption.icon).toBe('pi pi-arrow-up');
|
||||
});
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
export const SORT_OPTION_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
title: 'book.sorting.options.title',
|
||||
fileName: 'book.sorting.options.fileName',
|
||||
filePath: 'book.sorting.options.filePath',
|
||||
author: 'book.sorting.options.author',
|
||||
authorSurnameVorname: 'book.sorting.options.authorSurnameVorname',
|
||||
seriesName: 'book.sorting.options.seriesName',
|
||||
seriesNumber: 'book.sorting.options.seriesNumber',
|
||||
lastReadTime: 'book.sorting.options.lastReadTime',
|
||||
personalRating: 'book.sorting.options.personalRating',
|
||||
addedOn: 'book.sorting.options.addedOn',
|
||||
fileSizeKb: 'book.sorting.options.fileSizeKb',
|
||||
locked: 'book.sorting.options.locked',
|
||||
publisher: 'book.sorting.options.publisher',
|
||||
publishedDate: 'book.sorting.options.publishedDate',
|
||||
readStatus: 'book.sorting.options.readStatus',
|
||||
dateFinished: 'book.sorting.options.dateFinished',
|
||||
readingProgress: 'book.sorting.options.readingProgress',
|
||||
bookType: 'book.sorting.options.bookType',
|
||||
amazonRating: 'book.sorting.options.amazonRating',
|
||||
amazonReviewCount: 'book.sorting.options.amazonReviewCount',
|
||||
goodreadsRating: 'book.sorting.options.goodreadsRating',
|
||||
goodreadsReviewCount: 'book.sorting.options.goodreadsReviewCount',
|
||||
hardcoverRating: 'book.sorting.options.hardcoverRating',
|
||||
hardcoverReviewCount: 'book.sorting.options.hardcoverReviewCount',
|
||||
ranobedbRating: 'book.sorting.options.ranobedbRating',
|
||||
narrator: 'book.sorting.options.narrator',
|
||||
pageCount: 'book.sorting.options.pageCount',
|
||||
random: 'book.sorting.options.random'
|
||||
};
|
||||
|
||||
const SORT_FIELDS: { field: string; defaultLabel: string }[] = [
|
||||
{field: 'title', defaultLabel: 'Title'},
|
||||
{field: 'fileName', defaultLabel: 'File Name'},
|
||||
{field: 'filePath', defaultLabel: 'File Path'},
|
||||
{field: 'author', defaultLabel: 'Author'},
|
||||
{field: 'authorSurnameVorname', defaultLabel: 'Author (Surname)'},
|
||||
{field: 'seriesName', defaultLabel: 'Series Name'},
|
||||
{field: 'seriesNumber', defaultLabel: 'Series Number'},
|
||||
{field: 'lastReadTime', defaultLabel: 'Last Read'},
|
||||
{field: 'personalRating', defaultLabel: 'Personal Rating'},
|
||||
{field: 'addedOn', defaultLabel: 'Added On'},
|
||||
{field: 'fileSizeKb', defaultLabel: 'File Size'},
|
||||
{field: 'locked', defaultLabel: 'Locked'},
|
||||
{field: 'publisher', defaultLabel: 'Publisher'},
|
||||
{field: 'publishedDate', defaultLabel: 'Published Date'},
|
||||
{field: 'readStatus', defaultLabel: 'Read Status'},
|
||||
{field: 'dateFinished', defaultLabel: 'Date Finished'},
|
||||
{field: 'readingProgress', defaultLabel: 'Reading Progress'},
|
||||
{field: 'bookType', defaultLabel: 'Book Type'},
|
||||
{field: 'amazonRating', defaultLabel: 'Amazon Rating'},
|
||||
{field: 'amazonReviewCount', defaultLabel: 'Amazon #'},
|
||||
{field: 'goodreadsRating', defaultLabel: 'Goodreads Rating'},
|
||||
{field: 'goodreadsReviewCount', defaultLabel: 'Goodreads #'},
|
||||
{field: 'hardcoverRating', defaultLabel: 'Hardcover Rating'},
|
||||
{field: 'hardcoverReviewCount', defaultLabel: 'Hardcover #'},
|
||||
{field: 'ranobedbRating', defaultLabel: 'Ranobedb Rating'},
|
||||
{field: 'narrator', defaultLabel: 'Narrator'},
|
||||
{field: 'pageCount', defaultLabel: 'Pages'},
|
||||
{field: 'random', defaultLabel: 'Random'},
|
||||
];
|
||||
|
||||
export class BookSorter {
|
||||
selectedSortCriteria: SortOption[] = [];
|
||||
|
||||
sortOptions: SortOption[];
|
||||
|
||||
constructor(private onSortChange: (criteria: SortOption[]) => void, translocoService?: TranslocoService) {
|
||||
this.sortOptions = SORT_FIELDS.map(({field, defaultLabel}) => {
|
||||
const key = SORT_OPTION_LABEL_KEYS[field];
|
||||
const label = key && translocoService ? translocoService.translate(key) : defaultLabel;
|
||||
return {label, field, direction: SortDirection.ASCENDING};
|
||||
});
|
||||
}
|
||||
|
||||
// For backward compatibility - get first sort option
|
||||
get selectedSort(): SortOption | undefined {
|
||||
return this.selectedSortCriteria[0];
|
||||
}
|
||||
|
||||
// For backward compatibility - set from single sort option
|
||||
set selectedSort(sort: SortOption | undefined) {
|
||||
if (sort) {
|
||||
this.selectedSortCriteria = [sort];
|
||||
} else {
|
||||
this.selectedSortCriteria = [];
|
||||
}
|
||||
}
|
||||
|
||||
setSortCriteria(criteria: SortOption[]): void {
|
||||
this.selectedSortCriteria = [...criteria];
|
||||
this.updateSortOptions();
|
||||
}
|
||||
|
||||
// Quick sort by field - toggles direction if already selected as primary sort
|
||||
sortBooks(field: string): void {
|
||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!existingSort) return;
|
||||
|
||||
// If this field is the first (primary) sort, toggle its direction
|
||||
if (this.selectedSortCriteria.length > 0 && this.selectedSortCriteria[0].field === field) {
|
||||
this.selectedSortCriteria[0] = {
|
||||
...this.selectedSortCriteria[0],
|
||||
direction: this.selectedSortCriteria[0].direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
} else {
|
||||
// Set as the only sort criterion (single click behavior)
|
||||
this.selectedSortCriteria = [{
|
||||
label: existingSort.label,
|
||||
field: existingSort.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
}];
|
||||
}
|
||||
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
addSortCriterion(field: string): void {
|
||||
// Don't add if already exists
|
||||
if (this.selectedSortCriteria.some(c => c.field === field)) return;
|
||||
|
||||
const option = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!option) return;
|
||||
|
||||
this.selectedSortCriteria.push({
|
||||
label: option.label,
|
||||
field: option.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
});
|
||||
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
removeSortCriterion(index: number): void {
|
||||
if (index < 0 || index >= this.selectedSortCriteria.length) return;
|
||||
|
||||
this.selectedSortCriteria.splice(index, 1);
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
toggleCriterionDirection(index: number): void {
|
||||
if (index < 0 || index >= this.selectedSortCriteria.length) return;
|
||||
|
||||
const criterion = this.selectedSortCriteria[index];
|
||||
this.selectedSortCriteria[index] = {
|
||||
...criterion,
|
||||
direction: criterion.direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
reorderCriteria(event: CdkDragDrop<SortOption[]>): void {
|
||||
moveItemInArray(this.selectedSortCriteria, event.previousIndex, event.currentIndex);
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
getAvailableSortOptions(): SortOption[] {
|
||||
const usedFields = new Set(this.selectedSortCriteria.map(c => c.field));
|
||||
return this.sortOptions.filter(opt => !usedFields.has(opt.field));
|
||||
}
|
||||
|
||||
updateSortOptions(): void {
|
||||
const primaryField = this.selectedSortCriteria[0]?.field;
|
||||
const primaryDirection = this.selectedSortCriteria[0]?.direction;
|
||||
|
||||
const directionIcon = primaryDirection === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
|
||||
this.sortOptions = this.sortOptions.map((option) => ({
|
||||
...option,
|
||||
icon: option.field === primaryField ? directionIcon : '',
|
||||
}));
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.sorting'">
|
||||
<div class="multi-sort-container">
|
||||
<div class="multi-sort-header">
|
||||
<span class="header-title">{{ t('sortOrder') }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="sort-criteria-list"
|
||||
cdkDropList
|
||||
[cdkDropListData]="sortCriteria"
|
||||
(cdkDropListDropped)="onDrop($event)">
|
||||
@for (criterion of sortCriteria; track criterion.field; let i = $index) {
|
||||
<div class="sort-criterion" cdkDrag>
|
||||
<div class="criterion-drag-handle" cdkDragHandle>
|
||||
<i class="pi pi-bars"></i>
|
||||
</div>
|
||||
<span class="criterion-rank">{{ i + 1 }}.</span>
|
||||
<span class="criterion-label">{{ criterion.label }}</span>
|
||||
<div class="criterion-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="direction-btn"
|
||||
(click)="onToggleDirection(i)"
|
||||
[pTooltip]="getDirectionTooltip(criterion.direction)"
|
||||
tooltipPosition="top">
|
||||
<i [class]="getDirectionIcon(criterion.direction)"></i>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="remove-btn"
|
||||
(click)="onRemove(i)"
|
||||
[pTooltip]="t('removeTooltip')"
|
||||
tooltipPosition="top"
|
||||
[disabled]="sortCriteria.length === 1">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (unusedOptions.length > 0) {
|
||||
<div class="add-sort-section">
|
||||
<p-select
|
||||
[options]="unusedOptions"
|
||||
[(ngModel)]="selectedField"
|
||||
optionLabel="label"
|
||||
optionValue="field"
|
||||
[placeholder]="t('addSortFieldPlaceholder')"
|
||||
[style]="{ width: '100%' }"
|
||||
size="small"
|
||||
appendTo="body"
|
||||
(onChange)="onAddField()">
|
||||
</p-select>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (showSaveButton) {
|
||||
<div class="save-sort-section">
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
[label]="t('saveAsDefault')"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[style]="{ width: '100%' }"
|
||||
(onClick)="onSave()">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
-150
@@ -1,150 +0,0 @@
|
||||
.multi-sort-container {
|
||||
width: 280px;
|
||||
padding: 0.4375rem;
|
||||
}
|
||||
|
||||
.multi-sort-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 0.6563rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
margin-bottom: 0.6563rem;
|
||||
}
|
||||
|
||||
.header-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.7875rem;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.sort-criteria-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4375rem;
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.sort-criterion {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
padding: 0.4375rem;
|
||||
background-color: var(--overlay-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
cursor: move;
|
||||
transition: background-color 0.15s ease, box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--ground-background);
|
||||
}
|
||||
}
|
||||
|
||||
.cdk-drag-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
padding: 0.4375rem;
|
||||
background-color: var(--card-background);
|
||||
border: 1px solid var(--primary-color);
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 5px 15px rgb(0 0 0 / 25%);
|
||||
}
|
||||
|
||||
.cdk-drag-placeholder {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.cdk-drag-animating {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.sort-criteria-list.cdk-drop-list-dragging .sort-criterion:not(.cdk-drag-placeholder) {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.criterion-drag-handle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-secondary-color);
|
||||
cursor: grab;
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.7438rem;
|
||||
}
|
||||
}
|
||||
|
||||
.criterion-rank {
|
||||
font-weight: 600;
|
||||
color: var(--primary-color);
|
||||
min-width: 1.0938rem;
|
||||
}
|
||||
|
||||
.criterion-label {
|
||||
flex: 1;
|
||||
font-size: var(--app-text-sm);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.criterion-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.2188rem;
|
||||
}
|
||||
|
||||
.direction-btn,
|
||||
.remove-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.5313rem;
|
||||
height: 1.5313rem;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background-color: transparent;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.7438rem;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background-color: var(--ground-background);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.direction-btn {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.remove-btn {
|
||||
color: var(--p-red-500);
|
||||
}
|
||||
|
||||
.add-sort-section {
|
||||
margin-top: 0.6563rem;
|
||||
padding-top: 0.6563rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.save-sort-section {
|
||||
margin-top: 0.6563rem;
|
||||
padding-top: 0.6563rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
// TODO(seam): This popover needs an Optimus UI overlay and drag-drop harness so the
|
||||
// multi-sort reorder and apply flows can be tested against real emitted events.
|
||||
describe.skip('MultiSortPopoverComponent', () => {
|
||||
it('needs an overlay harness for drag-drop reorder and sort application flows', () => {
|
||||
expect.hasAssertions();
|
||||
});
|
||||
});
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
import {ChangeDetectionStrategy, Component, EventEmitter, inject, Input, Output} from '@angular/core';
|
||||
import {SortDirection, SortOption} from '../../../../model/sort.model';
|
||||
import {CdkDrag, CdkDragDrop, CdkDragHandle, CdkDropList, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
import {Select} from '@openng/optimus-ui/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {Button} from '@openng/optimus-ui/button';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-multi-sort-popover',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
CdkDropList,
|
||||
CdkDrag,
|
||||
CdkDragHandle,
|
||||
Select,
|
||||
FormsModule,
|
||||
Tooltip,
|
||||
Button,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './multi-sort-popover.component.html',
|
||||
styleUrl: './multi-sort-popover.component.scss'
|
||||
})
|
||||
export class MultiSortPopoverComponent {
|
||||
private readonly t = inject(TranslocoService);
|
||||
@Input() sortCriteria: SortOption[] = [];
|
||||
@Input() availableSortOptions: SortOption[] = [];
|
||||
@Input() showSaveButton = false;
|
||||
|
||||
@Output() criteriaChange = new EventEmitter<SortOption[]>();
|
||||
@Output() saveSortConfig = new EventEmitter<SortOption[]>();
|
||||
|
||||
selectedField: string | null = null;
|
||||
|
||||
get unusedOptions(): SortOption[] {
|
||||
const usedFields = new Set(this.sortCriteria.map(c => c.field));
|
||||
return this.availableSortOptions.filter(opt => !usedFields.has(opt.field));
|
||||
}
|
||||
|
||||
onDrop(event: CdkDragDrop<SortOption[]>): void {
|
||||
const criteria = [...this.sortCriteria];
|
||||
moveItemInArray(criteria, event.previousIndex, event.currentIndex);
|
||||
this.sortCriteria = criteria;
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onToggleDirection(index: number): void {
|
||||
this.sortCriteria = this.sortCriteria.map((c, i) =>
|
||||
i === index
|
||||
? {...c, direction: c.direction === SortDirection.ASCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING}
|
||||
: c
|
||||
);
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onRemove(index: number): void {
|
||||
this.sortCriteria = this.sortCriteria.filter((_, i) => i !== index);
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onAddField(): void {
|
||||
if (!this.selectedField) return;
|
||||
const option = this.availableSortOptions.find(o => o.field === this.selectedField);
|
||||
if (!option) return;
|
||||
this.sortCriteria = [...this.sortCriteria, {
|
||||
label: option.label,
|
||||
field: option.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
}];
|
||||
this.selectedField = null;
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onSave(): void {
|
||||
this.saveSortConfig.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
getDirectionIcon(direction: SortDirection): string {
|
||||
return direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
}
|
||||
|
||||
getDirectionTooltip(direction: SortDirection): string {
|
||||
return direction === SortDirection.ASCENDING
|
||||
? this.t.translate('book.sorting.ascendingTooltip')
|
||||
: this.t.translate('book.sorting.descendingTooltip');
|
||||
}
|
||||
|
||||
protected readonly SortDirection = SortDirection;
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||
|
||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('TableColumnPreferenceService', () => {
|
||||
let service: TableColumnPreferenceService;
|
||||
let userService: { getCurrentUser: ReturnType<typeof vi.fn>; updateUserSetting: ReturnType<typeof vi.fn> };
|
||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
userService = {
|
||||
getCurrentUser: vi.fn(),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string) => `t:${key}`)
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TableColumnPreferenceService,
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: TranslocoService, useValue: translocoService}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(TableColumnPreferenceService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('merges saved preferences with all available columns', () => {
|
||||
const savedPrefs: TableColumnPreference[] = [
|
||||
{field: 'title', visible: false, order: 4},
|
||||
{field: 'authors', visible: true, order: 1},
|
||||
{field: 'fileName', visible: true, order: 0}
|
||||
];
|
||||
|
||||
service.initPreferences(savedPrefs);
|
||||
|
||||
expect(service.preferences().find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: false,
|
||||
order: 4
|
||||
});
|
||||
expect(service.preferences().find(pref => pref.field === 'authors')).toEqual({
|
||||
field: 'authors',
|
||||
visible: true,
|
||||
order: 1
|
||||
});
|
||||
expect(service.allColumns[0]).toEqual({
|
||||
field: 'readStatus',
|
||||
header: 't:book.columnPref.columns.readStatus'
|
||||
});
|
||||
expect(service.visibleColumns.map(column => column.field).slice(0, 2)).toEqual(['readStatus', 'fileName']);
|
||||
});
|
||||
|
||||
it('falls back to defaults when no saved preferences exist', () => {
|
||||
service.initPreferences(undefined);
|
||||
|
||||
expect(service.preferences().length).toBe(service.allColumns.length);
|
||||
expect(service.visibleColumns[0]).toEqual({
|
||||
field: 'readStatus',
|
||||
header: 't:book.columnPref.columns.readStatus'
|
||||
});
|
||||
});
|
||||
|
||||
it('skips persistence when there is no current user', () => {
|
||||
userService.getCurrentUser.mockReturnValue(null);
|
||||
|
||||
service.saveVisibleColumns([{field: 'title'}]);
|
||||
|
||||
expect(userService.updateUserSetting).not.toHaveBeenCalled();
|
||||
expect(messageService.add).not.toHaveBeenCalled();
|
||||
expect(service.preferences().find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: true,
|
||||
order: 0
|
||||
});
|
||||
});
|
||||
|
||||
it('saves preferences and shows a success toast for the current user', () => {
|
||||
userService.getCurrentUser.mockReturnValue({id: 42});
|
||||
|
||||
service.saveVisibleColumns([{field: 'title'}, {field: 'authors'}]);
|
||||
|
||||
expect(userService.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', expect.any(Array));
|
||||
const savedPrefs = userService.updateUserSetting.mock.calls[0][2] as TableColumnPreference[];
|
||||
expect(savedPrefs.find(pref => pref.field === 'title')).toEqual({
|
||||
field: 'title',
|
||||
visible: true,
|
||||
order: 0
|
||||
});
|
||||
expect(savedPrefs.find(pref => pref.field === 'authors')).toEqual({
|
||||
field: 'authors',
|
||||
visible: true,
|
||||
order: 1
|
||||
});
|
||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 't:book.columnPref.toast.savedSummary',
|
||||
detail: 't:book.columnPref.toast.savedDetail',
|
||||
life: 1500
|
||||
}));
|
||||
});
|
||||
});
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
import {inject, Injectable, signal} from '@angular/core';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TableColumnPreferenceService {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private readonly _preferences = signal<TableColumnPreference[]>([]);
|
||||
readonly preferences = this._preferences.asReadonly();
|
||||
|
||||
private readonly allAvailableFields = [
|
||||
'readStatus', 'title', 'authors', 'publisher', 'seriesName', 'seriesNumber',
|
||||
'categories', 'publishedDate', 'lastReadTime', 'addedOn', 'fileName', 'fileSizeKb',
|
||||
'language', 'isbn', 'pageCount', 'amazonRating', 'amazonReviewCount',
|
||||
'goodreadsRating', 'goodreadsReviewCount', 'hardcoverRating', 'hardcoverReviewCount',
|
||||
'ranobedbRating',
|
||||
];
|
||||
|
||||
private readonly fallbackPreferences: TableColumnPreference[] = this.allAvailableFields.map((field, index) => ({
|
||||
field,
|
||||
visible: true,
|
||||
order: index
|
||||
}));
|
||||
|
||||
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
|
||||
const effectivePrefs = savedPrefs?.length ? savedPrefs : this.fallbackPreferences;
|
||||
this._preferences.set(this.mergeWithAllColumns(effectivePrefs));
|
||||
}
|
||||
|
||||
get allColumns(): { field: string; header: string }[] {
|
||||
return this.allAvailableFields.map(field => ({
|
||||
field,
|
||||
header: this.t.translate(`book.columnPref.columns.${field}`)
|
||||
}));
|
||||
}
|
||||
|
||||
get visibleColumns(): { field: string; header: string }[] {
|
||||
return this.preferences()
|
||||
.filter(pref => pref.visible)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(pref => ({
|
||||
field: pref.field,
|
||||
header: this.t.translate(`book.columnPref.columns.${pref.field}`)
|
||||
}));
|
||||
}
|
||||
|
||||
saveVisibleColumns(selectedColumns: { field: string }[]): void {
|
||||
const selectedFieldSet = new Set(selectedColumns.map(c => c.field));
|
||||
|
||||
const updatedPreferences: TableColumnPreference[] = this.allAvailableFields.map((field, index) => {
|
||||
const selectionIndex = selectedColumns.findIndex(c => c.field === field);
|
||||
return {
|
||||
field,
|
||||
visible: selectedFieldSet.has(field),
|
||||
order: selectionIndex >= 0 ? selectionIndex : index
|
||||
};
|
||||
});
|
||||
|
||||
this._preferences.set(updatedPreferences);
|
||||
|
||||
const currentUser = this.userService.getCurrentUser();
|
||||
if (!currentUser) return;
|
||||
|
||||
this.userService.updateUserSetting(currentUser.id, 'tableColumnPreference', updatedPreferences);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.columnPref.toast.savedSummary'),
|
||||
detail: this.t.translate('book.columnPref.toast.savedDetail'),
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
|
||||
private mergeWithAllColumns(savedPrefs: TableColumnPreference[]): TableColumnPreference[] {
|
||||
const savedPrefMap = new Map(savedPrefs.map(p => [p.field, p]));
|
||||
|
||||
return this.allAvailableFields.map((field, index) => {
|
||||
const saved = savedPrefMap.get(field);
|
||||
return {
|
||||
field,
|
||||
visible: saved?.visible ?? true,
|
||||
order: saved?.order ?? index
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ 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 {BookDialogHelperService} from '../../service/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';
|
||||
|
||||
@@ -65,7 +65,7 @@ import {
|
||||
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 {BookDialogHelperService} from '../../service/book-dialog-helper.service';
|
||||
import {FileDownloadService} from '../../../../shared/service/file-download.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {
|
||||
|
||||
+11
-1
@@ -132,11 +132,21 @@
|
||||
}
|
||||
|
||||
.cover-container:hover .info-btn,
|
||||
.cover-container:hover .read-btn {
|
||||
.cover-container:hover .read-btn,
|
||||
.book-card:focus-within .info-btn,
|
||||
.book-card:focus-within .read-btn {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
@media (hover: none) {
|
||||
.info-btn,
|
||||
.read-btn {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-container.center-info-btn .info-btn {
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
+19
-20
@@ -5,19 +5,19 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {User, UserService} from '../../../../settings/user-management/user.service';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model';
|
||||
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {BookCardComponent} from './book-card.component';
|
||||
import {BookFileService} from '../../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
|
||||
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
|
||||
import {EmailService} from '../../../settings/email-v2/email.service';
|
||||
import {User, UserService} from '../../../settings/user-management/user.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {AdditionalFile, Book, ReadStatus} from '../../model/book.model';
|
||||
import {BookDialogHelperService} from '../../service/book-dialog-helper.service';
|
||||
import {LegacyBookCardComponent} from './legacy-book-card.component';
|
||||
import {BookFileService} from '../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
|
||||
|
||||
function makeBook(overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
@@ -85,7 +85,6 @@ function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User {
|
||||
sidebarLibrarySorting: {} as never,
|
||||
sidebarShelfSorting: {} as never,
|
||||
sidebarMagicShelfSorting: {} as never,
|
||||
filterMode: 'and',
|
||||
enableSeriesView: false,
|
||||
entityViewPreferences: {global: {} as never, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
@@ -94,10 +93,10 @@ function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User {
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookCardComponent', () => {
|
||||
let component: BookCardComponent;
|
||||
let fixture: ComponentFixture<BookCardComponent>;
|
||||
let ref: ComponentRef<BookCardComponent>;
|
||||
describe('LegacyBookCardComponent', () => {
|
||||
let component: LegacyBookCardComponent;
|
||||
let fixture: ComponentFixture<LegacyBookCardComponent>;
|
||||
let ref: ComponentRef<LegacyBookCardComponent>;
|
||||
let bookService: {
|
||||
readBook: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
@@ -209,7 +208,7 @@ describe('BookCardComponent', () => {
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [BookCardComponent, getTranslocoModule()],
|
||||
imports: [LegacyBookCardComponent, getTranslocoModule()],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
providers: [
|
||||
{provide: ActivatedRoute, useValue: {}},
|
||||
@@ -246,7 +245,7 @@ describe('BookCardComponent', () => {
|
||||
})),
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(BookCardComponent);
|
||||
fixture = TestBed.createComponent(LegacyBookCardComponent);
|
||||
ref = fixture.componentRef;
|
||||
component = fixture.componentInstance;
|
||||
|
||||
+23
-23
@@ -1,41 +1,41 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, inject, input, output, signal} from '@angular/core';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
|
||||
import {AdditionalFile, Book, BookType, ReadStatus} from '../../model/book.model';
|
||||
import {ConfirmationService, MenuItem, MessageService} from '@openng/optimus-ui/api';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {BookFileService} from '../../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookFileService} from '../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {CheckboxChangeEvent, Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../../settings/email-v2/email.service';
|
||||
import {TieredMenu} from '@openng/optimus-ui/tieredmenu';
|
||||
import {Router, RouterLink} from '@angular/router';
|
||||
import {readStatusLabels} from '../book-filter/book-filter.config';
|
||||
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {READ_STATUS_LABELS} from '../../model/book-value-labels';
|
||||
import {ResetProgressTypes} from '../../../../shared/constants/reset-progress-type';
|
||||
import {ReadStatusHelper} from '../../helpers/read-status.helper';
|
||||
import {BookDialogHelperService} from '../../service/book-dialog-helper.service';
|
||||
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {ButtonDirective} from '@openng/optimus-ui/button';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card',
|
||||
templateUrl: './book-card.component.html',
|
||||
styleUrls: ['./book-card.component.scss'],
|
||||
selector: 'app-legacy-book-card',
|
||||
templateUrl: './legacy-book-card.component.html',
|
||||
styleUrls: ['./legacy-book-card.component.scss'],
|
||||
imports: [ButtonDirective, Checkbox, FormsModule, NgClass, TieredMenu, Tooltip, RouterLink, TranslocoPipe, CoverComponent],
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class BookCardComponent {
|
||||
export class LegacyBookCardComponent {
|
||||
|
||||
// --- Inputs ---
|
||||
readonly book = input.required<Book>();
|
||||
@@ -180,7 +180,7 @@ export class BookCardComponent {
|
||||
readonly readingUrl = computed(() => this.urlHelper.getBookPrimaryReadingUrl(this.book()));
|
||||
|
||||
private buildReadStatusMenuItems(): void {
|
||||
this.readStatusMenuItems.set(Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
this.readStatusMenuItems.set(Object.entries(READ_STATUS_LABELS).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.bookService.updateBookReadStatus(this.book().id, status as ReadStatus).subscribe({
|
||||
@@ -513,7 +513,7 @@ export class BookCardComponent {
|
||||
{
|
||||
label: this.t.translate('book.card.menu.readStatus'),
|
||||
icon: 'pi pi-book',
|
||||
items: Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
items: Object.entries(READ_STATUS_LABELS).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.bookService.updateBookReadStatus(this.book().id, status as ReadStatus).subscribe({
|
||||
-2
@@ -6,8 +6,6 @@ import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {type LibraryShelfMenuTarget} from '../../../../shared/layout/navigation/library-shelf-menu-target.model';
|
||||
import {libraryShelfMenuAvailable, LibraryShelfMenuItemsComponent} from './library-shelf-menu-items.component';
|
||||
|
||||
export type {LibraryShelfMenuTarget} from '../../../../shared/layout/navigation/library-shelf-menu-target.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-shelf-menu',
|
||||
standalone: true,
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
@use '../../../../../shared/styles/panel-shared' as panel;
|
||||
@use '../../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.lock-unlock-container {
|
||||
display: flex;
|
||||
+3
-3
@@ -3,13 +3,13 @@ import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LoadingService} from '../../../../../core/services/loading.service';
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {
|
||||
createDynamicDialogHarness,
|
||||
createMessageServiceProvider,
|
||||
createMessageServiceSpy,
|
||||
} from '../../../../../core/testing/dialog-testing';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
} from '../../../../core/testing/dialog-testing';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog.component';
|
||||
|
||||
describe('LockUnlockMetadataDialogComponent', () => {
|
||||
+3
-3
@@ -4,12 +4,12 @@ import {FormsModule} from '@angular/forms';
|
||||
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {Divider} from '@openng/optimus-ui/divider';
|
||||
import {LoadingService} from '../../../../../core/services/loading.service';
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {finalize} from 'rxjs';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {MetadataProviderFieldsService} from '../../../../../shared/metadata';
|
||||
import {MetadataProviderFieldsService} from '../../../../shared/metadata';
|
||||
|
||||
@Component({
|
||||
selector: 'app-lock-unlock-metadata-dialog',
|
||||
@@ -285,7 +285,7 @@
|
||||
[style.--series-grid-card-height.px]="seriesGridCardHeight()"
|
||||
[style.--series-grid-gap.px]="seriesGridGap()">
|
||||
@for (book of books; track book.id; let index = $index) {
|
||||
<app-book-card
|
||||
<app-legacy-book-card
|
||||
[index]="index"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
@@ -296,7 +296,7 @@
|
||||
[isSelected]="isBookSelected(book)"
|
||||
[useSquareCovers]="seriesCardsUseSquareCovers"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</app-legacy-book-card>
|
||||
}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -557,7 +557,7 @@ $meta-card-colors: (
|
||||
}
|
||||
}
|
||||
|
||||
.series-items-grid > app-book-card {
|
||||
.series-items-grid > app-legacy-book-card {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: var(--series-grid-card-height);
|
||||
|
||||
@@ -7,7 +7,7 @@ import {finalize, map, take} from "rxjs/operators";
|
||||
import {Book, BookType, computeSeriesReadStatus, ReadStatus} from "../../model/book.model";
|
||||
import {BookService} from "../../service/book.service";
|
||||
import {BookMetadataManageService} from "../../service/book-metadata-manage.service";
|
||||
import {BookCardComponent} from "../book-browser/book-card/book-card.component";
|
||||
import {LegacyBookCardComponent} from "../legacy-book-card/legacy-book-card.component";
|
||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from "@openng/optimus-ui/tabs";
|
||||
import {ProgressSpinner} from "@openng/optimus-ui/progressspinner";
|
||||
import {ProgressBar} from "@openng/optimus-ui/progressbar";
|
||||
@@ -16,7 +16,7 @@ import {ConfirmationService, MenuItem, MessageService} from "@openng/optimus-ui/
|
||||
import {UserService} from "../../../settings/user-management/user.service";
|
||||
import {BookMenuService} from "../../service/book-menu.service";
|
||||
import {LoadingService} from "../../../../core/services/loading.service";
|
||||
import {BookDialogHelperService} from "../book-browser/book-dialog-helper.service";
|
||||
import {BookDialogHelperService} from "../../service/book-dialog-helper.service";
|
||||
import {TaskHelperService} from "../../../settings/task-management/task-helper.service";
|
||||
import {MetadataRefreshType} from "../../../metadata/model/request/metadata-refresh-type.enum";
|
||||
import {TieredMenu} from "@openng/optimus-ui/tieredmenu";
|
||||
@@ -26,7 +26,7 @@ import {Tooltip} from "@openng/optimus-ui/tooltip";
|
||||
import {Divider} from "@openng/optimus-ui/divider";
|
||||
import {TagComponent} from "../../../../shared/components/tag/tag.component";
|
||||
import {AfterViewChecked, ChangeDetectionStrategy, Component, computed, effect, ElementRef, inject, signal, viewChild} from '@angular/core';
|
||||
import {BookCardOverlayPreferenceService} from '../book-browser/book-card-overlay-preference.service';
|
||||
import {BookCardOverlayPreferenceService} from '../legacy-book-card/book-card-overlay-preference.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {LanguageResolverService} from '../../../../shared/service/language-resolver.service';
|
||||
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
|
||||
@@ -77,7 +77,7 @@ interface SeriesStats {
|
||||
FormsModule,
|
||||
NgStyle,
|
||||
NgClass,
|
||||
BookCardComponent,
|
||||
LegacyBookCardComponent,
|
||||
ProgressSpinner,
|
||||
ProgressBar,
|
||||
Tabs,
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import {Book} from '../../model/book.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../../service/book-dialog-helper.service';
|
||||
import {ShelfAssignerComponent} from './shelf-assigner.component';
|
||||
|
||||
interface CurrentUserLike {
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ import {Shelf} from '../../model/shelf.model';
|
||||
import {Button} from '@openng/optimus-ui/button';
|
||||
import {Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../../service/book-dialog-helper.service';
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
|
||||
describe('BookDialogHelperService', () => {
|
||||
+21
-21
@@ -1,10 +1,10 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog';
|
||||
import {DialogLauncherService, DialogSize, DialogStyle} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {type BookSenderSource} from '../book-sender/book-sender.component';
|
||||
import {type BookFileAttacherSourceBook} from '../book-file-attacher/book-file-attacher.component';
|
||||
import {DialogLauncherService, DialogSize, DialogStyle} from '../../../shared/services/dialog-launcher.service';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {Book} from '../model/book.model';
|
||||
import {type BookSenderSource} from '../components/book-sender/book-sender.component';
|
||||
import {type BookFileAttacherSourceBook} from '../components/book-file-attacher/book-file-attacher.component';
|
||||
|
||||
interface MetadataRefreshDialogContext {
|
||||
metadataRefreshType: MetadataRefreshType;
|
||||
@@ -23,7 +23,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openBookDetailsDialog(bookId: number): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BookMetadataCenterComponent} = await import('../../../metadata/component/book-metadata-center/book-metadata-center.component');
|
||||
const {BookMetadataCenterComponent} = await import('../../metadata/component/book-metadata-center/book-metadata-center.component');
|
||||
return this.openDialog(BookMetadataCenterComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `book-details-dialog ${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -47,7 +47,7 @@ export class BookDialogHelperService {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
const {ShelfAssignerComponent} = await import('../shelf-assigner/shelf-assigner.component');
|
||||
const {ShelfAssignerComponent} = await import('../components/shelf-assigner/shelf-assigner.component');
|
||||
return this.openDialog(ShelfAssignerComponent, {
|
||||
showHeader: false,
|
||||
data: data,
|
||||
@@ -58,7 +58,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openShelfCreatorDialog(): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {ShelfCreatorComponent} = await import('../shelf-creator/shelf-creator.component');
|
||||
const {ShelfCreatorComponent} = await import('../components/shelf-creator/shelf-creator.component');
|
||||
return this.openDialog(ShelfCreatorComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
@@ -68,7 +68,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openLockUnlockMetadataDialog(bookIds: Set<number>): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {LockUnlockMetadataDialogComponent} = await import('./lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component');
|
||||
const {LockUnlockMetadataDialogComponent} = await import('../components/lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component');
|
||||
return this.openDialog(LockUnlockMetadataDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
@@ -88,7 +88,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openMetadataRefreshDialogWithContext(context: MetadataRefreshDialogContext): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {MultiBookMetadataFetchComponent} = await import('../../../metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component');
|
||||
const {MultiBookMetadataFetchComponent} = await import('../../metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component');
|
||||
return this.openDialog(MultiBookMetadataFetchComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -103,7 +103,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openBulkMetadataEditDialog(bookIds: Set<number>): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BulkMetadataUpdateComponent} = await import('../../../metadata/component/bulk-metadata-update/bulk-metadata-update-component');
|
||||
const {BulkMetadataUpdateComponent} = await import('../../metadata/component/bulk-metadata-update/bulk-metadata-update-component');
|
||||
return this.openDialog(BulkMetadataUpdateComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -116,7 +116,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openMultibookMetadataEditorDialog(bookIds: Set<number>): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {MultiBookMetadataEditorComponent} = await import('../../../metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component');
|
||||
const {MultiBookMetadataEditorComponent} = await import('../../metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component');
|
||||
return this.openDialog(MultiBookMetadataEditorComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -129,7 +129,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openFileMoverDialog(bookIds: Set<number>): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {FileMoverComponent} = await import('../../../../shared/components/file-mover/file-mover-component');
|
||||
const {FileMoverComponent} = await import('../../../shared/components/file-mover/file-mover-component');
|
||||
return this.openDialog(FileMoverComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -143,7 +143,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openCustomSendDialog(book: BookSenderSource): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BookSenderComponent} = await import('../book-sender/book-sender.component');
|
||||
const {BookSenderComponent} = await import('../components/book-sender/book-sender.component');
|
||||
return this.openDialog(BookSenderComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.SM} ${DialogStyle.MINIMAL}`,
|
||||
@@ -156,7 +156,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openCoverSearchDialog(bookId: number, coverType?: 'ebook' | 'audiobook'): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {CoverSearchComponent} = await import('../../../metadata/component/cover-search/cover-search.component');
|
||||
const {CoverSearchComponent} = await import('../../metadata/component/cover-search/cover-search.component');
|
||||
return this.openDialog(CoverSearchComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -170,7 +170,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openAdditionalFileUploaderDialog(book: Book): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {AdditionalFileUploaderComponent} = await import('../additional-file-uploader/additional-file-uploader.component');
|
||||
const {AdditionalFileUploaderComponent} = await import('../components/additional-file-uploader/additional-file-uploader.component');
|
||||
return this.openDialog(AdditionalFileUploaderComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
@@ -183,7 +183,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openBookFileAttacherDialog(sourceBook: Book): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BookFileAttacherComponent} = await import('../book-file-attacher/book-file-attacher.component');
|
||||
const {BookFileAttacherComponent} = await import('../components/book-file-attacher/book-file-attacher.component');
|
||||
return this.openDialog(BookFileAttacherComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
@@ -198,7 +198,7 @@ export class BookDialogHelperService {
|
||||
sourceBooks: readonly BookFileAttacherSourceBook[],
|
||||
): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BookFileAttacherComponent} = await import('../book-file-attacher/book-file-attacher.component');
|
||||
const {BookFileAttacherComponent} = await import('../components/book-file-attacher/book-file-attacher.component');
|
||||
return this.openDialog(BookFileAttacherComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
@@ -211,7 +211,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openDuplicateMergerDialog(libraryId: number): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {DuplicateMergerComponent} = await import('../duplicate-merger/duplicate-merger.component');
|
||||
const {DuplicateMergerComponent} = await import('../components/duplicate-merger/duplicate-merger.component');
|
||||
return this.openDialog(DuplicateMergerComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
|
||||
@@ -224,7 +224,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openAddPhysicalBookDialog(libraryId?: number): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {AddPhysicalBookDialogComponent} = await import('../add-physical-book-dialog/add-physical-book-dialog.component');
|
||||
const {AddPhysicalBookDialogComponent} = await import('../components/add-physical-book-dialog/add-physical-book-dialog.component');
|
||||
return this.openDialog(AddPhysicalBookDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
@@ -237,7 +237,7 @@ export class BookDialogHelperService {
|
||||
|
||||
async openBulkIsbnImportDialog(libraryId?: number): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BulkIsbnImportDialogComponent} = await import('../bulk-isbn-import-dialog/bulk-isbn-import-dialog.component');
|
||||
const {BulkIsbnImportDialogComponent} = await import('../components/bulk-isbn-import-dialog/bulk-isbn-import-dialog.component');
|
||||
return this.openDialog(BulkIsbnImportDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
@@ -3,7 +3,7 @@ import {Router} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
import {BookNavigationService} from './book-navigation.service';
|
||||
|
||||
const navigate = vi.fn(() => Promise.resolve(true));
|
||||
|
||||
@@ -3,7 +3,7 @@ import {Router} from '@angular/router';
|
||||
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {type BookFileResponse, type BookFileType, type BookSummary} from '../data/book-response.models';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
|
||||
export interface BookNavigationState {
|
||||
bookIds: number[];
|
||||
|
||||
@@ -9,7 +9,7 @@ import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
import {LibraryService} from './library.service';
|
||||
import {LibraryShelfMenuService} from './library-shelf-menu.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
|
||||
@@ -9,7 +9,7 @@ import {DialogLauncherService} from '../../../shared/services/dialog-launcher.se
|
||||
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||
import {LibraryService} from './library.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MessageService } from '@openng/optimus-ui/api';
|
||||
import { createQueryClientHarness } from '../../core/testing/query-testing';
|
||||
import { getTranslocoModule } from '../../core/testing/transloco-testing';
|
||||
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
|
||||
import { BookDialogHelperService } from '../book/service/book-dialog-helper.service';
|
||||
import { BookPage } from '../book/data/book-query.models';
|
||||
import { BookQueryService } from '../book/data/book-query.service';
|
||||
import { BookSummary } from '../book/data/book-response.models';
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Router } from '@angular/router';
|
||||
import { TranslocoService } from '@jsverse/transloco';
|
||||
import { injectQuery, QueryClient } from '@tanstack/angular-query-experimental';
|
||||
|
||||
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
|
||||
import { BookDialogHelperService } from '../book/service/book-dialog-helper.service';
|
||||
import { BookPageParams, EMPTY_FACET_SELECTION } from '../book/data/book-query-params';
|
||||
import { BookSummary } from '../book/data/book-response.models';
|
||||
import { BookQueryService } from '../book/data/book-query.service';
|
||||
|
||||
+2
-2
@@ -20,13 +20,13 @@
|
||||
<div class="dashboard-scroller-strip">
|
||||
@for (book of books(); track book.id; let i = $index) {
|
||||
<div class="dashboard-scroller-card" [ngClass]="{'square-card': useSquareCovers()}">
|
||||
<app-book-card
|
||||
<app-legacy-book-card
|
||||
[book]="book"
|
||||
[index]="i"
|
||||
[forceEbookMode]="forceEbookMode()"
|
||||
[useSquareCovers]="useSquareCovers()"
|
||||
[overlayPreferenceService]="overlayPreferenceService()">
|
||||
</app-book-card>
|
||||
</app-legacy-book-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
+3
-3
@@ -2,8 +2,8 @@ import {ChangeDetectionStrategy, Component, computed, input} from '@angular/core
|
||||
import {NgClass} from '@angular/common';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {ScrollerType} from '../../models/dashboard-config.model';
|
||||
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import {LegacyBookCardComponent} from '../../../book/components/legacy-book-card/legacy-book-card.component';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/legacy-book-card/book-card-overlay-preference.service';
|
||||
import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
@@ -12,7 +12,7 @@ import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
|
||||
templateUrl: './dashboard-scroller.component.html',
|
||||
styleUrls: ['./dashboard-scroller.component.scss'],
|
||||
imports: [
|
||||
BookCardComponent,
|
||||
LegacyBookCardComponent,
|
||||
NgClass,
|
||||
TranslocoDirective,
|
||||
TranslocoPipe
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import {ScrollerConfig, ScrollerType} from '../../models/dashboard-config.model'
|
||||
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {LibraryService} from '../../../book/service/library.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/legacy-book-card/book-card-overlay-preference.service';
|
||||
import {DashboardBookService} from '../../services/dashboard-book.service';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ import {DatePicker} from "@openng/optimus-ui/datepicker";
|
||||
import {Textarea} from "@openng/optimus-ui/textarea";
|
||||
import {Select} from "@openng/optimus-ui/select";
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service";
|
||||
import {BookDialogHelperService} from "../../../../book/service/book-dialog-helper.service";
|
||||
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
||||
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ import {AppSettingsService} from '../../../../../shared/service/app-settings.ser
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../../../../book/service/book-dialog-helper.service';
|
||||
import {LibraryService} from '../../../../book/service/library.service';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {AuthorService} from '../../../../author-browser/service/author.service';
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/const
|
||||
import {DatePicker} from '@openng/optimus-ui/datepicker';
|
||||
import {ProgressSpinner} from '@openng/optimus-ui/progressspinner';
|
||||
import {TieredMenu} from '@openng/optimus-ui/tieredmenu';
|
||||
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
||||
import {BookDialogHelperService} from '../../../../book/service/book-dialog-helper.service';
|
||||
import {LibraryService} from '../../../../book/service/library.service';
|
||||
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ function createUserSettings(): UserSettings {
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ function createUserSettings(): UserSettings {
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
|
||||
-1
@@ -19,7 +19,6 @@ describe('ReaderPreferencesService', () => {
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
|
||||
-1
@@ -18,7 +18,6 @@ describe('SettingsApplicationModeComponent', () => {
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
|
||||
|
||||
@@ -45,7 +45,6 @@ function buildUserSettings(overrides: Partial<UserSettings> = {}): UserSettings
|
||||
sidebarLibrarySorting: {field: 'name', order: 'ASC'},
|
||||
sidebarShelfSorting: {field: 'name', order: 'ASC'},
|
||||
sidebarMagicShelfSorting: {field: 'name', order: 'ASC'},
|
||||
filterMode: 'and',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {
|
||||
@@ -216,24 +215,24 @@ describe('UserService', () => {
|
||||
await flushCurrentUserQuery();
|
||||
service.setInitialUser(buildUser({
|
||||
id: 21,
|
||||
userSettings: buildUserSettings({filterMode: 'and'}),
|
||||
userSettings: buildUserSettings({metadataCenterViewMode: 'route'}),
|
||||
}));
|
||||
await flushCurrentUserQuery();
|
||||
|
||||
service.updateUserSetting(21, 'filterMode', 'or');
|
||||
service.updateUserSetting(21, 'metadataCenterViewMode', 'dialog');
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/21/settings'));
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual({key: 'filterMode', value: 'or'});
|
||||
expect(request.request.body).toEqual({key: 'metadataCenterViewMode', value: 'dialog'});
|
||||
expect(request.request.headers.get('Content-Type')).toBe('application/json');
|
||||
request.flush('');
|
||||
await flushCurrentUserQuery();
|
||||
|
||||
expect(service.currentUser()?.userSettings.filterMode).toBe('or');
|
||||
expect(service.currentUser()?.userSettings.metadataCenterViewMode).toBe('dialog');
|
||||
expect(queryClientHarness.queryClient.getQueryData<User>(CURRENT_USER_QUERY_KEY)).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 21,
|
||||
userSettings: expect.objectContaining({filterMode: 'or'}),
|
||||
userSettings: expect.objectContaining({metadataCenterViewMode: 'dialog'}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -60,7 +60,6 @@ export interface PerBookSetting {
|
||||
}
|
||||
|
||||
export type PageSpread = 'off' | 'even' | 'odd';
|
||||
export type BookFilterMode = 'and' | 'or' | 'single' | 'not';
|
||||
|
||||
|
||||
export enum CbxPageViewMode {
|
||||
@@ -224,77 +223,6 @@ export interface TableColumnPreference {
|
||||
order: number;
|
||||
}
|
||||
|
||||
export type VisibleFilterType =
|
||||
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
|
||||
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
|
||||
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
|
||||
| 'goodreadsRating' | 'hardcoverRating' | 'lubimyczytacRating' | 'ranobedbRating'
|
||||
| 'audibleRating' | 'language' | 'pageCount' | 'mood'
|
||||
| 'ageRating' | 'contentRating'
|
||||
| 'narrator'
|
||||
| 'comicCharacter' | 'comicTeam' | 'comicLocation' | 'comicCreator';
|
||||
|
||||
export const DEFAULT_VISIBLE_FILTERS: VisibleFilterType[] = [
|
||||
'author', 'category', 'series', 'bookType', 'readStatus',
|
||||
'personalRating', 'amazonRating', 'goodreadsRating', 'hardcoverRating',
|
||||
'lubimyczytacRating', 'ranobedbRating', 'audibleRating',
|
||||
'library', 'shelf', 'tag', 'ageRating', 'contentRating',
|
||||
'matchScore', 'publisher', 'publishedDate', 'fileSize',
|
||||
'pageCount', 'shelfStatus', 'language', 'mood', 'narrator',
|
||||
'comicCharacter', 'comicTeam', 'comicLocation', 'comicCreator'
|
||||
];
|
||||
|
||||
// Translation key for each filter option — use book.filter.labels.<value>
|
||||
export const ALL_FILTER_OPTION_VALUES: VisibleFilterType[] = [
|
||||
'author', 'category', 'series', 'bookType', 'readStatus',
|
||||
'personalRating', 'library', 'tag', 'ageRating', 'contentRating',
|
||||
'matchScore', 'publisher', 'publishedDate', 'fileSize', 'shelf',
|
||||
'shelfStatus', 'language', 'pageCount', 'mood', 'amazonRating',
|
||||
'goodreadsRating', 'hardcoverRating', 'lubimyczytacRating', 'ranobedbRating',
|
||||
'audibleRating', 'narrator',
|
||||
'comicCharacter', 'comicTeam', 'comicLocation', 'comicCreator'
|
||||
];
|
||||
|
||||
export const ALL_FILTER_OPTIONS: { label: string; value: VisibleFilterType }[] = [
|
||||
{ label: 'Author', value: 'author' },
|
||||
{ label: 'Genre', value: 'category' },
|
||||
{ label: 'Series', value: 'series' },
|
||||
{ label: 'Book Type', value: 'bookType' },
|
||||
{ label: 'Read Status', value: 'readStatus' },
|
||||
{ label: 'Personal Rating', value: 'personalRating' },
|
||||
{ label: 'Library', value: 'library' },
|
||||
{ label: 'Tag', value: 'tag' },
|
||||
{ label: 'Age Rating', value: 'ageRating' },
|
||||
{ label: 'Content Rating', value: 'contentRating' },
|
||||
{ label: 'Metadata Match Score', value: 'matchScore' },
|
||||
{ label: 'Publisher', value: 'publisher' },
|
||||
{ label: 'Published Year', value: 'publishedDate' },
|
||||
{ label: 'File Size', value: 'fileSize' },
|
||||
{ label: 'Shelf', value: 'shelf' },
|
||||
{ label: 'Shelf Status', value: 'shelfStatus' },
|
||||
{ label: 'Language', value: 'language' },
|
||||
{ label: 'Page Count', value: 'pageCount' },
|
||||
{ label: 'Mood', value: 'mood' },
|
||||
{ label: 'Amazon Rating', value: 'amazonRating' },
|
||||
{ label: 'Goodreads Rating', value: 'goodreadsRating' },
|
||||
{ label: 'Hardcover Rating', value: 'hardcoverRating' },
|
||||
{ label: 'Lubimyczytac Rating', value: 'lubimyczytacRating' },
|
||||
{ label: 'RanobeDB Rating', value: 'ranobedbRating' },
|
||||
{ label: 'Audible Rating', value: 'audibleRating' },
|
||||
{ label: 'Narrator', value: 'narrator' },
|
||||
{ label: 'Comic Character', value: 'comicCharacter' },
|
||||
{ label: 'Comic Team', value: 'comicTeam' },
|
||||
{ label: 'Comic Location', value: 'comicLocation' },
|
||||
{ label: 'Comic Creator', value: 'comicCreator' }
|
||||
];
|
||||
|
||||
export const DEFAULT_VISIBLE_SORT_FIELDS: string[] = [
|
||||
'title', 'seriesName', 'fileName', 'filePath',
|
||||
'author', 'authorSurnameVorname', 'seriesNumber',
|
||||
'lastReadTime', 'personalRating', 'addedOn',
|
||||
'fileSizeKb', 'locked', 'publisher', 'publishedDate', 'pageCount', 'random'
|
||||
];
|
||||
|
||||
export interface UserSettings {
|
||||
perBookSetting: PerBookSetting;
|
||||
pdfReaderSetting: PdfReaderSetting;
|
||||
@@ -305,9 +233,6 @@ export interface UserSettings {
|
||||
sidebarLibrarySorting: SidebarLibrarySorting;
|
||||
sidebarShelfSorting: SidebarShelfSorting;
|
||||
sidebarMagicShelfSorting: SidebarMagicShelfSorting;
|
||||
filterMode: BookFilterMode;
|
||||
visibleFilters?: VisibleFilterType[];
|
||||
visibleSortFields?: string[];
|
||||
metadataCenterViewMode: 'route' | 'dialog';
|
||||
enableSeriesView: boolean;
|
||||
entityViewPreferences: EntityViewPreferences;
|
||||
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
<ng-container *transloco="let t; prefix: 'settingsView.filter'">
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-filter"></i>
|
||||
{{ t('sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="setting-item">
|
||||
<div class="setting-header-standalone">
|
||||
<span class="setting-label">{{ t('filterMode') }}</span>
|
||||
</div>
|
||||
<p class="setting-description">{{ t('filterModeDesc') }}</p>
|
||||
<div class="setting-options">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="filterModes"
|
||||
[(ngModel)]="selectedFilterMode"
|
||||
(ngModelChange)="onFilterModeChange()"
|
||||
appendTo="body">
|
||||
</p-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-header-standalone">
|
||||
<span class="setting-label">{{ t('visibleFilters') }}</span>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
{{ t('visibleFiltersDesc', {min: minFilters, max: maxFilters}) }}
|
||||
<span class="filter-count">({{ selectionCountText }})</span>
|
||||
</p>
|
||||
<div class="filter-order-editor">
|
||||
<div
|
||||
#filterList
|
||||
class="filter-order-list"
|
||||
cdkDropList
|
||||
[cdkDropListData]="selectedVisibleFilters"
|
||||
(cdkDropListDropped)="onDrop($event)">
|
||||
@for (f of selectedVisibleFilters; track f; let i = $index) {
|
||||
<div class="filter-order-row" cdkDrag>
|
||||
<div class="filter-drag-handle" cdkDragHandle>
|
||||
<i class="pi pi-bars"></i>
|
||||
</div>
|
||||
<span class="filter-rank">{{ i + 1 }}.</span>
|
||||
<span class="filter-label">{{ getFilterLabel(f) }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="remove-filter-btn"
|
||||
(click)="removeFilter(i)"
|
||||
[disabled]="selectedVisibleFilters.length <= minFilters"
|
||||
[pTooltip]="'common.remove' | transloco"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="filter-actions-row">
|
||||
@if (availableFilters.length > 0 && selectedVisibleFilters.length < maxFilters) {
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="availableFilters"
|
||||
[(ngModel)]="selectedAddFilter"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('addFilter')"
|
||||
[style]="{ width: '200px' }"
|
||||
appendTo="body"
|
||||
(onChange)="addFilter()">
|
||||
</p-select>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
class="reset-btn"
|
||||
(click)="resetToDefaults()"
|
||||
[pTooltip]="t('resetToDefaults')"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-refresh"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
-196
@@ -1,196 +0,0 @@
|
||||
@use '../../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.settings-card {
|
||||
@include settings.settings-card;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
@include settings.settings-section-header;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
@include settings.settings-section-title;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.section-body {
|
||||
@include settings.settings-section-body;
|
||||
}
|
||||
|
||||
.setting-item {
|
||||
@include settings.settings-item;
|
||||
}
|
||||
|
||||
.setting-header-standalone {
|
||||
@include settings.settings-item-header-standalone;
|
||||
}
|
||||
|
||||
.setting-label {
|
||||
@include settings.settings-label;
|
||||
}
|
||||
|
||||
.setting-description {
|
||||
@include settings.settings-item-description;
|
||||
}
|
||||
|
||||
.setting-options {
|
||||
@include settings.settings-options;
|
||||
|
||||
p-select {
|
||||
min-width: 200px;
|
||||
|
||||
@media (width <= 768px) {
|
||||
min-width: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.filter-count {
|
||||
font-weight: 500;
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
|
||||
// Filter order editor styles
|
||||
.filter-order-editor {
|
||||
margin-top: 0.6563rem;
|
||||
}
|
||||
|
||||
.filter-order-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4375rem;
|
||||
min-height: 40px;
|
||||
max-height: 320px;
|
||||
max-width: 350px;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 0.6563rem;
|
||||
}
|
||||
|
||||
.filter-order-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
padding: 0.4375rem 0.6563rem;
|
||||
background-color: var(--overlay-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
cursor: move;
|
||||
transition: background-color 0.15s ease, box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--ground-background);
|
||||
}
|
||||
}
|
||||
|
||||
.cdk-drag-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
padding: 0.3063rem 0.6563rem;
|
||||
background-color: var(--card-background);
|
||||
border: 1px solid var(--primary-color);
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 5px 15px rgb(0 0 0 / 25%);
|
||||
}
|
||||
|
||||
.cdk-drag-placeholder {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.cdk-drag-animating {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.filter-order-list.cdk-drop-list-dragging .filter-order-row:not(.cdk-drag-placeholder) {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.filter-drag-handle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-secondary-color);
|
||||
cursor: grab;
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.7438rem;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-rank {
|
||||
font-weight: 600;
|
||||
color: var(--primary-color);
|
||||
min-width: 1.5313rem;
|
||||
}
|
||||
|
||||
.filter-label {
|
||||
flex: 1;
|
||||
font-size: var(--app-text-sm);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.remove-filter-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.5313rem;
|
||||
height: 1.5313rem;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background-color: transparent;
|
||||
color: var(--p-red-500);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.7438rem;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background-color: var(--ground-background);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-actions-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4375rem;
|
||||
}
|
||||
|
||||
.reset-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.5313rem;
|
||||
height: 1.5313rem;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background-color: transparent;
|
||||
color: var(--text-secondary-color);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease, color 0.15s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.7438rem;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: var(--ground-background);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Real coverage here needs seams around signal-backed user-preference
|
||||
// hydration, drag/drop reorder behavior, and Optimus UI selection widgets so filter persistence can
|
||||
// be asserted without the full view-preferences runtime.
|
||||
describe.skip('FilterPreferencesComponent', () => {
|
||||
it('needs preference seams to verify bootstrap, reset, and save behavior for filter visibility state', () => {
|
||||
// TODO(seam): Cover the effect-driven settings sync once user preferences can be injected through deterministic doubles.
|
||||
});
|
||||
|
||||
it('needs drag/drop seams to verify ordering and selection changes without CDK/Optimus UI widget runtime coupling', () => {
|
||||
// TODO(seam): Cover reorder and toggle flows after the drag-drop and pick-list interactions are isolated behind a testable adapter.
|
||||
});
|
||||
});
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
import {Component, effect, ElementRef, inject, viewChild} from '@angular/core';
|
||||
import {Select} from '@openng/optimus-ui/select';
|
||||
import {ALL_FILTER_OPTION_VALUES, ALL_FILTER_OPTIONS, BookFilterMode, DEFAULT_VISIBLE_FILTERS, User, UserService, UserSettings, VisibleFilterType} from '../../user-management/user.service';
|
||||
import {FILTER_LABEL_KEYS} from '../../../book/components/book-browser/book-filter/book-filter.config';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {CdkDrag, CdkDragDrop, CdkDragHandle, CdkDropList, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
import {Tooltip} from '@openng/optimus-ui/tooltip';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
const MIN_VISIBLE_FILTERS = 5;
|
||||
const MAX_VISIBLE_FILTERS = 50;
|
||||
type MutableSettingsBranch = Record<string, unknown>;
|
||||
|
||||
@Component({
|
||||
selector: 'app-filter-preferences',
|
||||
imports: [
|
||||
Select,
|
||||
FormsModule,
|
||||
CdkDropList,
|
||||
CdkDrag,
|
||||
CdkDragHandle,
|
||||
Tooltip,
|
||||
TranslocoDirective,
|
||||
TranslocoPipe
|
||||
],
|
||||
templateUrl: './filter-preferences.component.html',
|
||||
styleUrl: './filter-preferences.component.scss'
|
||||
})
|
||||
export class FilterPreferencesComponent {
|
||||
|
||||
readonly filterModes = [
|
||||
{label: 'And', value: 'and'},
|
||||
{label: 'Or', value: 'or'},
|
||||
{label: 'Single', value: 'single'},
|
||||
];
|
||||
|
||||
readonly allFilterOptions = ALL_FILTER_OPTIONS;
|
||||
readonly minFilters = MIN_VISIBLE_FILTERS;
|
||||
readonly maxFilters = MAX_VISIBLE_FILTERS;
|
||||
|
||||
selectedFilterMode: BookFilterMode = 'and';
|
||||
selectedVisibleFilters: VisibleFilterType[] = [...DEFAULT_VISIBLE_FILTERS];
|
||||
|
||||
private readonly filterList = viewChild<ElementRef<HTMLElement>>('filterList');
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private currentUser: User | null = null;
|
||||
private hasInitialized = false;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (!user) return;
|
||||
|
||||
this.currentUser = user;
|
||||
if (!this.hasInitialized) {
|
||||
this.hasInitialized = true;
|
||||
this.loadPreferences(user.userSettings);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadPreferences(settings: UserSettings): void {
|
||||
this.selectedFilterMode = settings.filterMode ?? 'and';
|
||||
this.selectedVisibleFilters = settings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
|
||||
}
|
||||
|
||||
private updatePreference(path: string[], value: unknown): void {
|
||||
if (!this.currentUser) return;
|
||||
|
||||
let target = this.currentUser.userSettings as unknown as MutableSettingsBranch;
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
const next = target[path[i]];
|
||||
if (!next || typeof next !== 'object') {
|
||||
target[path[i]] = {};
|
||||
}
|
||||
target = target[path[i]] as MutableSettingsBranch;
|
||||
}
|
||||
target[path.at(-1)!] = value;
|
||||
|
||||
const [rootKey] = path;
|
||||
const updatedValue = this.currentUser.userSettings[rootKey as keyof UserSettings];
|
||||
this.userService.updateUserSetting(this.currentUser.id, rootKey, updatedValue);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsView.sidebarSort.prefsUpdated'),
|
||||
detail: this.t.translate('settingsView.sidebarSort.prefsUpdatedDetail'),
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
|
||||
onFilterModeChange(): void {
|
||||
this.updatePreference(['filterMode'], this.selectedFilterMode);
|
||||
}
|
||||
|
||||
selectedAddFilter: string | null = null;
|
||||
|
||||
get availableFilters(): {label: string; value: string}[] {
|
||||
const used = new Set(this.selectedVisibleFilters);
|
||||
return ALL_FILTER_OPTION_VALUES
|
||||
.filter(v => !used.has(v))
|
||||
.map(v => ({label: this.getFilterLabel(v), value: v}));
|
||||
}
|
||||
|
||||
getFilterLabel(value: string): string {
|
||||
const key = FILTER_LABEL_KEYS[value as keyof typeof FILTER_LABEL_KEYS];
|
||||
return key ? this.t.translate(key) : value;
|
||||
}
|
||||
|
||||
onDrop(event: CdkDragDrop<VisibleFilterType[]>): void {
|
||||
moveItemInArray(this.selectedVisibleFilters, event.previousIndex, event.currentIndex);
|
||||
this.updatePreference(['visibleFilters'], this.selectedVisibleFilters);
|
||||
}
|
||||
|
||||
addFilter(): void {
|
||||
if (this.selectedAddFilter) {
|
||||
this.selectedVisibleFilters.push(this.selectedAddFilter as VisibleFilterType);
|
||||
this.selectedAddFilter = null;
|
||||
this.updatePreference(['visibleFilters'], this.selectedVisibleFilters);
|
||||
requestAnimationFrame(() => {
|
||||
const el = this.filterList()?.nativeElement;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
removeFilter(index: number): void {
|
||||
if (this.selectedVisibleFilters.length > MIN_VISIBLE_FILTERS) {
|
||||
this.selectedVisibleFilters.splice(index, 1);
|
||||
this.updatePreference(['visibleFilters'], this.selectedVisibleFilters);
|
||||
}
|
||||
}
|
||||
|
||||
resetToDefaults(): void {
|
||||
this.selectedVisibleFilters = [...DEFAULT_VISIBLE_FILTERS];
|
||||
this.updatePreference(['visibleFilters'], this.selectedVisibleFilters);
|
||||
}
|
||||
|
||||
get selectionCountText(): string {
|
||||
return this.t.translate('settingsView.filter.selectionCount', {count: this.selectedVisibleFilters.length, total: this.allFilterOptions.length});
|
||||
}
|
||||
}
|
||||
-2
@@ -16,8 +16,6 @@
|
||||
<div class="section-divider"><hr></div>
|
||||
<app-view-preferences></app-view-preferences>
|
||||
<div class="section-divider"><hr></div>
|
||||
<app-filter-preferences></app-filter-preferences>
|
||||
<div class="section-divider"><hr></div>
|
||||
<app-sidebar-sorting-preferences></app-sidebar-sorting-preferences>
|
||||
<div class="section-divider"><hr></div>
|
||||
<app-meta-center-view-mode-component></app-meta-center-view-mode-component>
|
||||
|
||||
-2
@@ -5,7 +5,6 @@ import {TableModule} from '@openng/optimus-ui/table';
|
||||
import {ViewPreferencesComponent} from './view-preferences/view-preferences.component';
|
||||
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences/sidebar-sorting-preferences.component';
|
||||
import {MetaCenterViewModeComponent} from './meta-center-view-mode/meta-center-view-mode-component';
|
||||
import {FilterPreferencesComponent} from './filter-preferences/filter-preferences.component';
|
||||
import {DisplayPreferencesComponent} from './display-preferences/display-preferences.component';
|
||||
import {DashboardPreferencesComponent} from './dashboard-preferences/dashboard-preferences.component';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
@@ -22,7 +21,6 @@ import {LayoutService, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH} from '../../../shar
|
||||
ViewPreferencesComponent,
|
||||
SidebarSortingPreferencesComponent,
|
||||
MetaCenterViewModeComponent,
|
||||
FilterPreferencesComponent,
|
||||
DisplayPreferencesComponent,
|
||||
DashboardPreferencesComponent,
|
||||
TranslocoDirective,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { MessageService } from '@openng/optimus-ui/api';
|
||||
|
||||
import { getTranslocoModule } from '../../../core/testing/transloco-testing';
|
||||
import { BookDialogHelperService } from '../../../features/book/components/book-browser/book-dialog-helper.service';
|
||||
import { BookDialogHelperService } from '../../../features/book/service/book-dialog-helper.service';
|
||||
import { BookService } from '../../../features/book/service/book.service';
|
||||
import { LibraryHealthService } from '../../../features/book/service/library-health.service';
|
||||
import { LibraryService } from '../../../features/book/service/library.service';
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user