refactor(ebook-reader): optimize destruction handling and improve reactive subscriptions (#478)
This commit is contained in:
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
<ng-container *transloco="let t; prefix: 'authorBrowser.detail'">
|
<ng-container *transloco="let t; prefix: 'authorBrowser.detail'">
|
||||||
@if (loading) {
|
@if (loading()) {
|
||||||
<div class="loading-state">
|
<div class="loading-state">
|
||||||
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
|
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
|
||||||
</p-progressSpinner>
|
</p-progressSpinner>
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (!loading && author(); as author) {
|
@if (!loading() && author(); as author) {
|
||||||
<div class="author-wrapper">
|
<div class="author-wrapper">
|
||||||
<p-tabs [value]="tab" lazy="true" scrollable>
|
<p-tabs [value]="tab" lazy="true" scrollable>
|
||||||
<p-tablist>
|
<p-tablist>
|
||||||
|
|||||||
+2
-2
@@ -144,7 +144,7 @@ describe('AuthorDetailComponent', () => {
|
|||||||
|
|
||||||
expect(getAuthorDetails).toHaveBeenCalledWith(42);
|
expect(getAuthorDetails).toHaveBeenCalledWith(42);
|
||||||
expect(component.tab).toBe('series');
|
expect(component.tab).toBe('series');
|
||||||
expect(component.loading).toBe(false);
|
expect(component.loading()).toBe(false);
|
||||||
expect(component.author()).toEqual({...baseAuthor, id: 42, name: 'Grace Hopper'});
|
expect(component.author()).toEqual({...baseAuthor, id: 42, name: 'Grace Hopper'});
|
||||||
expect(setPageTitle).toHaveBeenCalledWith('Grace Hopper');
|
expect(setPageTitle).toHaveBeenCalledWith('Grace Hopper');
|
||||||
});
|
});
|
||||||
@@ -158,7 +158,7 @@ describe('AuthorDetailComponent', () => {
|
|||||||
component.ngOnInit();
|
component.ngOnInit();
|
||||||
|
|
||||||
expect(component.tab).toBe('books');
|
expect(component.tab).toBe('books');
|
||||||
expect(component.loading).toBe(false);
|
expect(component.loading()).toBe(false);
|
||||||
expect(component.author()).toBeNull();
|
expect(component.author()).toBeNull();
|
||||||
expect(setPageTitle).not.toHaveBeenCalled();
|
expect(setPageTitle).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|||||||
+3
-3
@@ -85,7 +85,7 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
private readonly viewportWidth = signal(0);
|
private readonly viewportWidth = signal(0);
|
||||||
private viewportResizeObserver: ResizeObserver | undefined;
|
private viewportResizeObserver: ResizeObserver | undefined;
|
||||||
|
|
||||||
loading = true;
|
loading = signal(true);
|
||||||
tab = 'books';
|
tab = 'books';
|
||||||
isExpanded = false;
|
isExpanded = false;
|
||||||
isOverflowing = false;
|
isOverflowing = false;
|
||||||
@@ -199,11 +199,11 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
this.authorService.getAuthorDetails(authorId).subscribe({
|
this.authorService.getAuthorDetails(authorId).subscribe({
|
||||||
next: (author) => {
|
next: (author) => {
|
||||||
this.authorState.set(author);
|
this.authorState.set(author);
|
||||||
this.loading = false;
|
this.loading.set(false);
|
||||||
this.pageTitle.setPageTitle(author.name);
|
this.pageTitle.setPageTitle(author.name);
|
||||||
},
|
},
|
||||||
error: () => {
|
error: () => {
|
||||||
this.loading = false;
|
this.loading.set(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-14
@@ -8,7 +8,7 @@
|
|||||||
<div class="entity-info">
|
<div class="entity-info">
|
||||||
<p class="entity-title">
|
<p class="entity-title">
|
||||||
@if (entityType === EntityType.ALL_BOOKS) {
|
@if (entityType === EntityType.ALL_BOOKS) {
|
||||||
@if (currentFilterLabel() && rawFilterParamFromUrl) {
|
@if (currentFilterLabel() && rawFilterParamFromUrl()) {
|
||||||
{{ currentFilterLabel() }}
|
{{ currentFilterLabel() }}
|
||||||
} @else if (isFilterActive() || hasSearchTerm()) {
|
} @else if (isFilterActive() || hasSearchTerm()) {
|
||||||
{{ computedFilterLabel() }}
|
{{ computedFilterLabel() }}
|
||||||
@@ -70,7 +70,7 @@
|
|||||||
<p-multiSelect
|
<p-multiSelect
|
||||||
optionLabel="header"
|
optionLabel="header"
|
||||||
[options]="columnPreferenceService.allColumns"
|
[options]="columnPreferenceService.allColumns"
|
||||||
[(ngModel)]="visibleColumns"
|
[ngModel]="visibleColumns()"
|
||||||
(ngModelChange)="onVisibleColumnsChange($event)"
|
(ngModelChange)="onVisibleColumnsChange($event)"
|
||||||
display="chip"
|
display="chip"
|
||||||
[placeholder]="t('placeholder.selectColumns')"
|
[placeholder]="t('placeholder.selectColumns')"
|
||||||
@@ -85,14 +85,14 @@
|
|||||||
[label]="t('labels.save')"
|
[label]="t('labels.save')"
|
||||||
outlined
|
outlined
|
||||||
size="small"
|
size="small"
|
||||||
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns)"></p-button>
|
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns())"></p-button>
|
||||||
</div>
|
</div>
|
||||||
</p-popover>
|
</p-popover>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
|
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
|
||||||
<i
|
<i
|
||||||
[ngClass]="viewIcon()"
|
[class]="viewIcon()"
|
||||||
[pTooltip]="t('tooltip.toggleView')"
|
[pTooltip]="t('tooltip.toggleView')"
|
||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</i>
|
</i>
|
||||||
@@ -180,14 +180,14 @@
|
|||||||
[pTooltip]="t('tooltip.selectSorting')"
|
[pTooltip]="t('tooltip.selectSorting')"
|
||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</i>
|
</i>
|
||||||
@if (sortCriteriaCount > 1) {
|
@if (sortCriteriaCount() > 1) {
|
||||||
<p-badge [value]="sortCriteriaCount.toString()" class="sort-badge"/>
|
<p-badge [value]="sortCriteriaCount().toString()" class="sort-badge"/>
|
||||||
}
|
}
|
||||||
</a>
|
</a>
|
||||||
<p-popover #sortPopover [dismissable]="true" appendTo="body">
|
<p-popover #sortPopover [dismissable]="true" appendTo="body">
|
||||||
<app-multi-sort-popover
|
<app-multi-sort-popover
|
||||||
[sortCriteria]="this.bookSorter.selectedSortCriteria"
|
[sortCriteria]="this.bookSorter.selectedSortCriteria"
|
||||||
[availableSortOptions]="visibleSortOptions"
|
[availableSortOptions]="visibleSortOptions()"
|
||||||
[showSaveButton]="canSaveSort()"
|
[showSaveButton]="canSaveSort()"
|
||||||
(criteriaChange)="onSortCriteriaChange($event)"
|
(criteriaChange)="onSortCriteriaChange($event)"
|
||||||
(saveSortConfig)="onSaveSortConfig($event)">
|
(saveSortConfig)="onSaveSortConfig($event)">
|
||||||
@@ -215,7 +215,7 @@
|
|||||||
type="text"
|
type="text"
|
||||||
pInputText
|
pInputText
|
||||||
[placeholder]="t('placeholder.search')"
|
[placeholder]="t('placeholder.search')"
|
||||||
[(ngModel)]="bookTitle"
|
[ngModel]="bookTitle()"
|
||||||
(ngModelChange)="onSearchTermChange($event)"
|
(ngModelChange)="onSearchTermChange($event)"
|
||||||
class="search-input-full"
|
class="search-input-full"
|
||||||
/>
|
/>
|
||||||
@@ -237,11 +237,11 @@
|
|||||||
type="text"
|
type="text"
|
||||||
pInputText
|
pInputText
|
||||||
[placeholder]="t('placeholder.search')"
|
[placeholder]="t('placeholder.search')"
|
||||||
[(ngModel)]="bookTitle"
|
[ngModel]="bookTitle()"
|
||||||
(ngModelChange)="onSearchTermChange($event)"
|
(ngModelChange)="onSearchTermChange($event)"
|
||||||
class="search-input"
|
class="search-input"
|
||||||
/>
|
/>
|
||||||
@if (bookTitle) {
|
@if (bookTitle()) {
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-times"
|
icon="pi pi-times"
|
||||||
[text]="true"
|
[text]="true"
|
||||||
@@ -314,7 +314,7 @@
|
|||||||
[preselectedBookIds]="selectedBooks()"
|
[preselectedBookIds]="selectedBooks()"
|
||||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||||
[sortOption]="this.bookSorter.selectedSort!"
|
[sortOption]="this.bookSorter.selectedSort!"
|
||||||
[visibleColumns]="visibleColumns"
|
[visibleColumns]="visibleColumns()"
|
||||||
></app-book-table>
|
></app-book-table>
|
||||||
}
|
}
|
||||||
@if (currentViewMode() === 'grid') {
|
@if (currentViewMode() === 'grid') {
|
||||||
@@ -330,7 +330,7 @@
|
|||||||
[index]="i"
|
[index]="i"
|
||||||
[book]="book"
|
[book]="book"
|
||||||
[isCheckboxEnabled]="true"
|
[isCheckboxEnabled]="true"
|
||||||
[seriesViewEnabled]="seriesViewEnabled"
|
[seriesViewEnabled]="seriesViewEnabled()"
|
||||||
[onBookSelect]="onBookCardSelect"
|
[onBookSelect]="onBookCardSelect"
|
||||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||||
(checkboxClick)="onCheckboxClicked($event)"
|
(checkboxClick)="onCheckboxClicked($event)"
|
||||||
@@ -358,7 +358,7 @@
|
|||||||
<div class="footer-center">
|
<div class="footer-center">
|
||||||
@if (entityType(); as entityType) {
|
@if (entityType(); as entityType) {
|
||||||
<div class="action-buttons-group">
|
<div class="action-buttons-group">
|
||||||
@if (hasMetadataMenuItems) {
|
@if (hasMetadataMenuItems()) {
|
||||||
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
||||||
<p-button
|
<p-button
|
||||||
(click)="menu.toggle($event)"
|
(click)="menu.toggle($event)"
|
||||||
@@ -418,7 +418,7 @@
|
|||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
}
|
||||||
@if (hasMoreActionsItems) {
|
@if (hasMoreActionsItems()) {
|
||||||
<div class="more-actions-wrapper">
|
<div class="more-actions-wrapper">
|
||||||
<p-button
|
<p-button
|
||||||
(click)="menu.toggle($event)"
|
(click)="menu.toggle($event)"
|
||||||
|
|||||||
+62
-14
@@ -10,7 +10,7 @@ import {BookService} from '../../service/book.service';
|
|||||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||||
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {SortDirection} from '../../model/sort.model';
|
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||||
@@ -112,6 +112,8 @@ interface BookBrowserHarness {
|
|||||||
updateFilters: ReturnType<typeof vi.fn>;
|
updateFilters: ReturnType<typeof vi.fn>;
|
||||||
updateFilterMode: ReturnType<typeof vi.fn>;
|
updateFilterMode: ReturnType<typeof vi.fn>;
|
||||||
updateMultiSort: ReturnType<typeof vi.fn>;
|
updateMultiSort: ReturnType<typeof vi.fn>;
|
||||||
|
parseQueryParams: ReturnType<typeof vi.fn>;
|
||||||
|
syncQueryParams: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
routeSnapshot: {
|
routeSnapshot: {
|
||||||
routeConfig: {path: string};
|
routeConfig: {path: string};
|
||||||
@@ -129,8 +131,8 @@ function createHarness(options?: {
|
|||||||
}): BookBrowserHarness {
|
}): BookBrowserHarness {
|
||||||
const books = signal<Book[]>(
|
const books = signal<Book[]>(
|
||||||
options?.books ?? [
|
options?.books ?? [
|
||||||
makeBook(1, 1, 'Alpha', '2024-01-01T00:00:00Z'),
|
|
||||||
makeBook(2, 1, 'Zulu', '2024-02-01T00:00:00Z'),
|
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'),
|
makeBook(3, 2, 'Bravo', '2024-03-01T00:00:00Z'),
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
@@ -143,7 +145,17 @@ function createHarness(options?: {
|
|||||||
const paramMap$ = new BehaviorSubject(convertToParamMap({libraryId: '1'}));
|
const paramMap$ = new BehaviorSubject(convertToParamMap({libraryId: '1'}));
|
||||||
const queryParamMap$ = new BehaviorSubject(convertToParamMap({}));
|
const queryParamMap$ = new BehaviorSubject(convertToParamMap({}));
|
||||||
const url$ = new BehaviorSubject<unknown[]>([]);
|
const url$ = new BehaviorSubject<unknown[]>([]);
|
||||||
|
const defaultSort: SortOption = {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'};
|
||||||
const queryParamsService = {
|
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),
|
shouldForceExpandSeries: vi.fn(() => false),
|
||||||
updateViewMode: vi.fn(),
|
updateViewMode: vi.fn(),
|
||||||
updateFilters: vi.fn(),
|
updateFilters: vi.fn(),
|
||||||
@@ -157,6 +169,7 @@ function createHarness(options?: {
|
|||||||
params: {libraryId: '1'},
|
params: {libraryId: '1'},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
TestBed.resetTestingModule();
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
SortService,
|
SortService,
|
||||||
@@ -206,6 +219,35 @@ function createHarness(options?: {
|
|||||||
setCollapsed: vi.fn((value: boolean) => seriesCollapsed.set(value)),
|
setCollapsed: vi.fn((value: boolean) => seriesCollapsed.set(value)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: SortService,
|
||||||
|
useValue: {
|
||||||
|
applySort: vi.fn((b: Book[]) => b),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: BookSelectionService,
|
||||||
|
useValue: {
|
||||||
|
selectedBooks: signal([]),
|
||||||
|
selectedCount: signal(0),
|
||||||
|
deselectAll: vi.fn(),
|
||||||
|
setCurrentBooks: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: BookNavigationService,
|
||||||
|
useValue: {
|
||||||
|
setAvailableBookIds: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: BookBrowserScrollService,
|
||||||
|
useValue: {
|
||||||
|
createKey: vi.fn(() => 'test-key'),
|
||||||
|
savePosition: vi.fn(),
|
||||||
|
getPosition: vi.fn(() => 0),
|
||||||
|
},
|
||||||
|
},
|
||||||
{provide: ConfirmationService, useValue: {confirm: vi.fn()}},
|
{provide: ConfirmationService, useValue: {confirm: vi.fn()}},
|
||||||
{provide: TaskHelperService, useValue: {}},
|
{provide: TaskHelperService, useValue: {}},
|
||||||
{
|
{
|
||||||
@@ -255,12 +297,14 @@ function createHarness(options?: {
|
|||||||
if (f.libraryId) result = result.filter(b => b.libraryId === f.libraryId);
|
if (f.libraryId) result = result.filter(b => b.libraryId === f.libraryId);
|
||||||
|
|
||||||
const s = _sort();
|
const s = _sort();
|
||||||
const dir = s.dir === 'asc' ? 1 : -1;
|
|
||||||
result = [...result].sort((a, b) => {
|
result = [...result].sort((a, b) => {
|
||||||
if (s.field === 'title') return dir * ((a.metadata?.title ?? '') as string).localeCompare((b.metadata?.title ?? '') as string);
|
const aVal = s.field === 'title' ? (a.metadata?.title ?? '') : (a.addedOn ?? '');
|
||||||
if (s.field === 'addedOn') return dir * (a.addedOn ?? '').localeCompare(b.addedOn ?? '');
|
const bVal = s.field === 'title' ? (b.metadata?.title ?? '') : (b.addedOn ?? '');
|
||||||
return 0;
|
return String(aVal).localeCompare(String(bVal));
|
||||||
});
|
});
|
||||||
|
if (s.dir === 'desc') {
|
||||||
|
result.reverse();
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -384,7 +428,7 @@ describe('BookBrowserComponent', () => {
|
|||||||
|
|
||||||
component.onViewModeChange(VIEW_MODES.TABLE);
|
component.onViewModeChange(VIEW_MODES.TABLE);
|
||||||
|
|
||||||
expect(component.currentViewMode()).toBe(VIEW_MODES.TABLE);
|
expect((component as unknown as {currentViewMode: () => string}).currentViewMode()).toBe(VIEW_MODES.TABLE);
|
||||||
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
|
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -404,7 +448,7 @@ describe('BookBrowserComponent', () => {
|
|||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
expect(component.books()?.map(book => book.id)).toEqual([1, 2]);
|
expect(component.books()?.map(book => book.id)).toEqual([1, 2]);
|
||||||
expect(component.hasRenderedBooks()).toBe(true);
|
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(true);
|
||||||
expect(component.isBooksRefreshing()).toBe(false);
|
expect(component.isBooksRefreshing()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -420,12 +464,12 @@ describe('BookBrowserComponent', () => {
|
|||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
expect(component.books()).toBeUndefined();
|
expect(component.books()).toBeUndefined();
|
||||||
expect(component.hasRenderedBooks()).toBe(false);
|
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(false);
|
||||||
|
|
||||||
vi.runOnlyPendingTimers();
|
vi.runOnlyPendingTimers();
|
||||||
|
|
||||||
expect(component.books()?.map(book => book.id)).toEqual([3]);
|
expect(component.books()?.map(book => book.id)).toEqual([3]);
|
||||||
expect(component.hasRenderedBooks()).toBe(true);
|
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hides loading placeholders when the books query is in an error state', () => {
|
it('hides loading placeholders when the books query is in an error state', () => {
|
||||||
@@ -434,9 +478,14 @@ describe('BookBrowserComponent', () => {
|
|||||||
isBooksLoading: true,
|
isBooksLoading: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(component.showBooksLoadingPlaceholder()).toBe(false);
|
const comp = component as unknown as {
|
||||||
expect(component.showGridLoadingPlaceholder()).toBe(false);
|
showBooksLoadingPlaceholder: () => boolean;
|
||||||
expect(component.showTableLoadingPlaceholder()).toBe(false);
|
showGridLoadingPlaceholder: () => boolean;
|
||||||
|
showTableLoadingPlaceholder: () => boolean;
|
||||||
|
};
|
||||||
|
expect(comp.showBooksLoadingPlaceholder()).toBe(false);
|
||||||
|
expect(comp.showGridLoadingPlaceholder()).toBe(false);
|
||||||
|
expect(comp.showTableLoadingPlaceholder()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('calls SeriesCollapseFilter.collapseBooks when computing pipelineInputs', () => {
|
it('calls SeriesCollapseFilter.collapseBooks when computing pipelineInputs', () => {
|
||||||
@@ -473,7 +522,6 @@ describe('BookBrowserComponent', () => {
|
|||||||
removeEventListener: vi.fn(),
|
removeEventListener: vi.fn(),
|
||||||
} as unknown as HTMLElement;
|
} as unknown as HTMLElement;
|
||||||
|
|
||||||
component.currentViewMode.set(VIEW_MODES.GRID);
|
|
||||||
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
|
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
|
||||||
|
|
||||||
// Trigger initial check
|
// Trigger initial check
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, OnDestroy, computed, effect, inject, OnInit, signal, untracked, ViewChild} from '@angular/core';
|
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, untracked, ViewChild} from '@angular/core';
|
||||||
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||||
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
||||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||||
@@ -79,7 +79,7 @@ export enum EntityType {
|
|||||||
],
|
],
|
||||||
providers: [SeriesCollapseFilter],
|
providers: [SeriesCollapseFilter],
|
||||||
})
|
})
|
||||||
export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
export class BookBrowserComponent implements AfterViewInit {
|
||||||
|
|
||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
|
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
|
||||||
@@ -112,6 +112,21 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.loadMobileColumnsPreference();
|
||||||
|
this.setupRouteChangeHandlers();
|
||||||
|
this.setupQueryParamSubscription();
|
||||||
|
this.setupScrollPositionTracking();
|
||||||
|
|
||||||
|
this.destroyRef.onDestroy(() => {
|
||||||
|
if (this.scrollContainer) {
|
||||||
|
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
||||||
|
}
|
||||||
|
this.containerResizeObserver?.disconnect();
|
||||||
|
this.sentinelObserver?.disconnect();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private readonly defaultSortCriteria: SortOption[] = [{
|
private readonly defaultSortCriteria: SortOption[] = [{
|
||||||
field: 'addedOn',
|
field: 'addedOn',
|
||||||
direction: SortDirection.DESCENDING,
|
direction: SortDirection.DESCENDING,
|
||||||
@@ -140,6 +155,15 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
private readonly selectedFilter = signal<Record<string, string[]> | null>(null);
|
private readonly selectedFilter = signal<Record<string, string[]> | null>(null);
|
||||||
private readonly selectedFilterMode = signal<BookFilterMode>('and');
|
private readonly selectedFilterMode = signal<BookFilterMode>('and');
|
||||||
private readonly sortCriteria = signal<SortOption[]>(this.defaultSortCriteria);
|
private readonly sortCriteria = signal<SortOption[]>(this.defaultSortCriteria);
|
||||||
|
|
||||||
|
readonly screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
|
||||||
|
readonly currentViewMode = signal<string | undefined>(undefined);
|
||||||
|
readonly bookTitle = signal('');
|
||||||
|
readonly visibleColumns = signal<{ field: string; header: string }[]>([]);
|
||||||
|
readonly visibleSortOptions = signal<SortOption[]>([]);
|
||||||
|
readonly currentFilterLabel = signal<string | null>(null);
|
||||||
|
readonly rawFilterParamFromUrl = signal<string | null>(null);
|
||||||
|
readonly mobileColumnCount = signal(3);
|
||||||
private readonly seriesCollapsed = this.seriesCollapseFilter.seriesCollapsed;
|
private readonly seriesCollapsed = this.seriesCollapseFilter.seriesCollapsed;
|
||||||
readonly selectedBooks = this.bookSelectionService.selectedBooks;
|
readonly selectedBooks = this.bookSelectionService.selectedBooks;
|
||||||
readonly selectedCount = this.bookSelectionService.selectedCount;
|
readonly selectedCount = this.bookSelectionService.selectedCount;
|
||||||
@@ -344,10 +368,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
|
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
|
||||||
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
|
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
|
||||||
parsedFilters: Record<string, string[]> = {};
|
parsedFilters: Record<string, string[]> = {};
|
||||||
bookTitle = '';
|
|
||||||
dynamicDialogRef: DynamicDialogRef | undefined | null;
|
dynamicDialogRef: DynamicDialogRef | undefined | null;
|
||||||
EntityType = EntityType;
|
EntityType = EntityType;
|
||||||
|
|
||||||
private readonly activeLang = toSignal(this.t.langChanges$, {
|
private readonly activeLang = toSignal(this.t.langChanges$, {
|
||||||
initialValue: this.t.getActiveLang()
|
initialValue: this.t.getActiveLang()
|
||||||
});
|
});
|
||||||
@@ -382,17 +404,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
? this.t.translate('book.browser.labels.activeFilters', {count: filterEntries.length})
|
? this.t.translate('book.browser.labels.activeFilters', {count: filterEntries.length})
|
||||||
: filterSummary;
|
: filterSummary;
|
||||||
});
|
});
|
||||||
|
|
||||||
readonly currentFilterLabel = computed(() => this.computedFilterLabel());
|
|
||||||
|
|
||||||
rawFilterParamFromUrl: string | null = null;
|
|
||||||
visibleColumns: { field: string; header: string }[] = [];
|
|
||||||
entityViewPreferences: EntityViewPreferences | undefined;
|
entityViewPreferences: EntityViewPreferences | undefined;
|
||||||
currentViewMode = signal<string | undefined>(undefined);
|
|
||||||
lastAppliedSortCriteria: SortOption[] = [];
|
lastAppliedSortCriteria: SortOption[] = [];
|
||||||
visibleSortOptions: SortOption[] = [];
|
|
||||||
screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
|
|
||||||
mobileColumnCount = signal(3);
|
|
||||||
|
|
||||||
private readonly MOBILE_BREAKPOINT = 768;
|
private readonly MOBILE_BREAKPOINT = 768;
|
||||||
private readonly CARD_ASPECT_RATIO = 7 / 5;
|
private readonly CARD_ASPECT_RATIO = 7 / 5;
|
||||||
@@ -576,7 +589,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
readonly showBooksLoadingPlaceholder = computed(() =>
|
readonly showBooksLoadingPlaceholder = computed(() =>
|
||||||
!this.booksError() && !this.hasRenderedBooks()
|
!this.booksError() && (this.isBooksLoading() || !this.hasRenderedBooks())
|
||||||
);
|
);
|
||||||
|
|
||||||
readonly showTableLoadingPlaceholder = computed(() =>
|
readonly showTableLoadingPlaceholder = computed(() =>
|
||||||
@@ -603,24 +616,24 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
|
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
|
||||||
});
|
});
|
||||||
|
|
||||||
get seriesViewEnabled(): boolean {
|
readonly seriesViewEnabled = computed(() => Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView));
|
||||||
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
|
|
||||||
}
|
|
||||||
|
|
||||||
get hasMetadataMenuItems(): boolean {
|
readonly hasMetadataMenuItems = computed(() => (this.metadataMenuItems?.length ?? 0) > 0);
|
||||||
return (this.metadataMenuItems?.length ?? 0) > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
get hasMoreActionsItems(): boolean {
|
readonly hasMoreActionsItems = computed(() => (this.moreActionsMenuItems?.length ?? 0) > 0);
|
||||||
return (this.moreActionsMenuItems?.length ?? 0) > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
readonly canSaveSort = computed(() => {
|
||||||
this.loadMobileColumnsPreference();
|
const entityType = this.entityType();
|
||||||
this.setupRouteChangeHandlers();
|
return entityType === EntityType.LIBRARY ||
|
||||||
this.setupQueryParamSubscription();
|
entityType === EntityType.SHELF ||
|
||||||
this.setupScrollPositionTracking();
|
entityType === EntityType.MAGIC_SHELF ||
|
||||||
}
|
entityType === EntityType.ALL_BOOKS ||
|
||||||
|
entityType === EntityType.UNSHELVED;
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly hasSearchTerm = computed(() => this.searchTerm().trim().length > 0);
|
||||||
|
|
||||||
|
readonly sortCriteriaCount = computed(() => this.bookSorter.selectedSortCriteria.length);
|
||||||
|
|
||||||
ngAfterViewInit(): void {
|
ngAfterViewInit(): void {
|
||||||
if (this.bookFilterComponent) {
|
if (this.bookFilterComponent) {
|
||||||
@@ -629,14 +642,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
|
||||||
if (this.scrollContainer) {
|
|
||||||
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
|
||||||
}
|
|
||||||
this.containerResizeObserver?.disconnect();
|
|
||||||
this.sentinelObserver?.disconnect();
|
|
||||||
}
|
|
||||||
|
|
||||||
private onScroll = (): void => {
|
private onScroll = (): void => {
|
||||||
this.checkAndFetchIfNeeded();
|
this.checkAndFetchIfNeeded();
|
||||||
};
|
};
|
||||||
@@ -687,7 +692,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
private setupRouteChangeHandlers(): void {
|
private setupRouteChangeHandlers(): void {
|
||||||
this.activatedRoute.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
|
this.activatedRoute.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
|
||||||
this.searchTerm.set('');
|
this.searchTerm.set('');
|
||||||
this.bookTitle = '';
|
this.bookTitle.set('');
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
this.clearFilter();
|
this.clearFilter();
|
||||||
this.scrollToTop();
|
this.scrollToTop();
|
||||||
@@ -750,14 +755,18 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
this.selectedFilter.set(parseResult.filters);
|
this.selectedFilter.set(parseResult.filters);
|
||||||
|
|
||||||
if (this.bookFilterComponent) {
|
if (this.bookFilterComponent) {
|
||||||
this.bookFilterComponent.setFilters(parseResult.filters);
|
this.bookFilterComponent.setFilters?.(parseResult.filters);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.rawFilterParamFromUrl = filterParams;
|
if (Object.keys(parseResult.filters).length > 0) {
|
||||||
|
this.currentFilterLabel.set(this.computedFilterLabel());
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rawFilterParamFromUrl.set(filterParams);
|
||||||
this.settingFiltersFromUrl = false;
|
this.settingFiltersFromUrl = false;
|
||||||
} else {
|
} else {
|
||||||
this.clearFilter();
|
this.clearFilter();
|
||||||
this.rawFilterParamFromUrl = null;
|
this.rawFilterParamFromUrl.set(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.parsedFilters = parseResult.filters;
|
this.parsedFilters = parseResult.filters;
|
||||||
@@ -765,11 +774,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
|
|
||||||
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
|
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
|
||||||
this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference);
|
this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference);
|
||||||
this.visibleColumns = this.columnPreferenceService.visibleColumns;
|
this.visibleColumns.set(this.columnPreferenceService.visibleColumns);
|
||||||
|
|
||||||
const visibleFields = currentUser.userSettings?.visibleSortFields ?? DEFAULT_VISIBLE_SORT_FIELDS;
|
const visibleFields = currentUser.userSettings?.visibleSortFields ?? DEFAULT_VISIBLE_SORT_FIELDS;
|
||||||
const sortOptionsByField = new Map(this.bookSorter.sortOptions.map(o => [o.field, o]));
|
const sortOptionsByField = new Map(this.bookSorter.sortOptions.map(o => [o.field, o]));
|
||||||
this.visibleSortOptions = visibleFields.map(f => sortOptionsByField.get(f)).filter((o): o is SortOption => !!o);
|
this.visibleSortOptions.set(visibleFields.map(f => sortOptionsByField.get(f)).filter((o): o is SortOption => !!o));
|
||||||
|
|
||||||
|
|
||||||
if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) {
|
if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) {
|
||||||
@@ -777,10 +786,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
this.currentViewMode.set(parseResult.viewMode);
|
this.currentViewMode.set(parseResult.viewMode);
|
||||||
|
|
||||||
if (!this.areSortCriteriaEqual(this.lastAppliedSortCriteria, this.bookSorter.selectedSortCriteria)) {
|
|
||||||
this.lastAppliedSortCriteria = [...this.bookSorter.selectedSortCriteria];
|
|
||||||
this.applySortCriteria(this.bookSorter.selectedSortCriteria);
|
this.applySortCriteria(this.bookSorter.selectedSortCriteria);
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
this.queryParamsService.syncQueryParams(
|
this.queryParamsService.syncQueryParams(
|
||||||
@@ -804,8 +810,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
this.selectedFilter.set(normalizedFilters);
|
this.selectedFilter.set(normalizedFilters);
|
||||||
this.rawFilterParamFromUrl = null;
|
this.rawFilterParamFromUrl.set(null);
|
||||||
|
|
||||||
|
const hasSidebarFilters = !!normalizedFilters && Object.keys(normalizedFilters).length > 0;
|
||||||
|
this.currentFilterLabel.set(hasSidebarFilters ? this.computedFilterLabel() : this.t.translate('book.browser.labels.allBooks'));
|
||||||
this.queryParamsService.updateFilters(normalizedFilters);
|
this.queryParamsService.updateFilters(normalizedFilters);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -822,9 +830,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
|
|
||||||
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
|
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
|
||||||
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
|
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
|
||||||
this.visibleColumns = selected.sort(
|
this.visibleColumns.set(selected.sort(
|
||||||
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
|
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
|
||||||
);
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
onCheckboxClicked(event: CheckboxClickEvent): void {
|
onCheckboxClicked(event: CheckboxClickEvent): void {
|
||||||
@@ -913,17 +921,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
this.onMultiSortChange(criteria);
|
this.onMultiSortChange(criteria);
|
||||||
}
|
}
|
||||||
|
|
||||||
readonly canSaveSort = computed(() => {
|
|
||||||
const entityType = this.entityType();
|
|
||||||
return entityType === EntityType.LIBRARY ||
|
|
||||||
entityType === EntityType.SHELF ||
|
|
||||||
entityType === EntityType.MAGIC_SHELF ||
|
|
||||||
entityType === EntityType.ALL_BOOKS ||
|
|
||||||
entityType === EntityType.UNSHELVED;
|
|
||||||
});
|
|
||||||
|
|
||||||
readonly hasSearchTerm = computed(() => this.searchTerm().trim().length > 0);
|
|
||||||
|
|
||||||
onSaveSortConfig(criteria: SortOption[]): void {
|
onSaveSortConfig(criteria: SortOption[]): void {
|
||||||
const entityType = this.entityType();
|
const entityType = this.entityType();
|
||||||
if (!entityType) return;
|
if (!entityType) return;
|
||||||
@@ -998,16 +995,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
get sortCriteriaCount(): number {
|
|
||||||
return this.bookSorter.selectedSortCriteria.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
onSearchTermChange(term: string): void {
|
onSearchTermChange(term: string): void {
|
||||||
this.searchTerm.set(term);
|
this.searchTerm.set(term);
|
||||||
}
|
}
|
||||||
|
|
||||||
clearSearch(): void {
|
clearSearch(): void {
|
||||||
this.bookTitle = '';
|
this.bookTitle.set('');
|
||||||
this.onSearchTermChange('');
|
this.onSearchTermChange('');
|
||||||
this.resetFilters();
|
this.resetFilters();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {BookCardOverlayPreferenceService} from '../book-browser/book-card-overla
|
|||||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||||
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
|
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
|
||||||
import {injectQuery} from '@tanstack/angular-query-experimental';
|
import {injectQuery} from '@tanstack/angular-query-experimental';
|
||||||
|
import {AuthorService} from '../../../author-browser/service/author.service';
|
||||||
|
|
||||||
interface ReadStatusSegment {
|
interface ReadStatusSegment {
|
||||||
status: ReadStatus;
|
status: ReadStatus;
|
||||||
@@ -110,6 +111,7 @@ export class SeriesPageComponent implements AfterViewChecked {
|
|||||||
protected appSettingsService = inject(AppSettingsService);
|
protected appSettingsService = inject(AppSettingsService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
protected urlHelper = inject(UrlHelperService);
|
protected urlHelper = inject(UrlHelperService);
|
||||||
|
private authorService = inject(AuthorService);
|
||||||
|
|
||||||
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
||||||
tab: string = "view";
|
tab: string = "view";
|
||||||
@@ -368,7 +370,14 @@ export class SeriesPageComponent implements AfterViewChecked {
|
|||||||
}
|
}
|
||||||
|
|
||||||
goToAuthorBooks(author: string): void {
|
goToAuthorBooks(author: string): void {
|
||||||
this.handleMetadataClick("author", author);
|
this.authorService.getAuthorByName(author).subscribe({
|
||||||
|
next: (authorDetails) => {
|
||||||
|
this.router.navigate(['/author', authorDetails.id]);
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.handleMetadataClick('author', author);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
goToCategory(category: string): void {
|
goToCategory(category: string): void {
|
||||||
|
|||||||
+10
-10
@@ -1,13 +1,13 @@
|
|||||||
<ng-container *transloco="let t; prefix: 'dashboard.scroller'">
|
<ng-container *transloco="let t; prefix: 'dashboard.scroller'">
|
||||||
<div class="dashboard-scroller-container">
|
<div class="dashboard-scroller-container">
|
||||||
<h2 class="dashboard-scroller-title">
|
<h2 class="dashboard-scroller-title">
|
||||||
{{ title | transloco }}
|
{{ title() | transloco }}
|
||||||
@if (isMagicShelf) {
|
@if (isMagicShelf()) {
|
||||||
<i class="pi pi-sparkles magic-shelf-icon"></i>
|
<i class="pi pi-sparkles magic-shelf-icon"></i>
|
||||||
}
|
}
|
||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
@if (!books || books.length === 0) {
|
@if (books() !== null && books()?.length === 0) {
|
||||||
<div class="dashboard-scroller-no-books">
|
<div class="dashboard-scroller-no-books">
|
||||||
<div class="empty-state-icon">
|
<div class="empty-state-icon">
|
||||||
<i class="pi pi-book"></i>
|
<i class="pi pi-book"></i>
|
||||||
@@ -16,23 +16,23 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (books && books.length > 0) {
|
@if (books() && books()!.length > 0) {
|
||||||
<div class="dashboard-scroller-strip">
|
<div class="dashboard-scroller-strip">
|
||||||
@for (book of books; track book.id; let i = $index) {
|
@for (book of books(); track book.id; let i = $index) {
|
||||||
<div class="dashboard-scroller-card" [ngClass]="{'square-card': useSquareCovers}">
|
<div class="dashboard-scroller-card" [ngClass]="{'square-card': useSquareCovers()}">
|
||||||
<app-book-card
|
<app-book-card
|
||||||
[book]="book"
|
[book]="book"
|
||||||
[index]="i"
|
[index]="i"
|
||||||
[forceEbookMode]="forceEbookMode"
|
[forceEbookMode]="forceEbookMode()"
|
||||||
[useSquareCovers]="useSquareCovers"
|
[useSquareCovers]="useSquareCovers()"
|
||||||
[overlayPreferenceService]="overlayPreferenceService">
|
[overlayPreferenceService]="overlayPreferenceService()">
|
||||||
</app-book-card>
|
</app-book-card>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (books === null) {
|
@if (books() === null) {
|
||||||
<div class="dashboard-scroller-error">
|
<div class="dashboard-scroller-error">
|
||||||
<div class="error-icon">
|
<div class="error-icon">
|
||||||
<i class="pi pi-exclamation-triangle"></i>
|
<i class="pi pi-exclamation-triangle"></i>
|
||||||
|
|||||||
+8
-10
@@ -1,4 +1,4 @@
|
|||||||
import {ChangeDetectionStrategy, Component, Input} from '@angular/core';
|
import {ChangeDetectionStrategy, Component, computed, input} from '@angular/core';
|
||||||
import {NgClass} from '@angular/common';
|
import {NgClass} from '@angular/common';
|
||||||
import {Book} from '../../../book/model/book.model';
|
import {Book} from '../../../book/model/book.model';
|
||||||
import {ScrollerType} from '../../models/dashboard-config.model';
|
import {ScrollerType} from '../../models/dashboard-config.model';
|
||||||
@@ -21,14 +21,12 @@ import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
|
|||||||
})
|
})
|
||||||
export class DashboardScrollerComponent {
|
export class DashboardScrollerComponent {
|
||||||
|
|
||||||
@Input() bookListType: ScrollerType | null = null;
|
readonly bookListType = input<ScrollerType | null>(null);
|
||||||
@Input() title!: string;
|
readonly title = input.required<string>();
|
||||||
@Input() books!: Book[] | null;
|
readonly books = input<Book[] | null>(null);
|
||||||
@Input() isMagicShelf: boolean = false;
|
readonly isMagicShelf = input<boolean>(false);
|
||||||
@Input() useSquareCovers: boolean = false;
|
readonly useSquareCovers = input<boolean>(false);
|
||||||
@Input() overlayPreferenceService!: BookCardOverlayPreferenceService;
|
readonly overlayPreferenceService = input.required<BookCardOverlayPreferenceService>();
|
||||||
|
|
||||||
get forceEbookMode(): boolean {
|
readonly forceEbookMode = computed(() => this.bookListType() === ScrollerType.LAST_READ);
|
||||||
return this.bookListType === ScrollerType.LAST_READ;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -32,7 +32,7 @@
|
|||||||
<p-select
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
[inputId]="'dashboard-scroller-type-' + scroller.id"
|
[inputId]="'dashboard-scroller-type-' + scroller.id"
|
||||||
[options]="availableScrollerTypes"
|
[options]="availableScrollerTypes()"
|
||||||
[(ngModel)]="scroller.type"
|
[(ngModel)]="scroller.type"
|
||||||
(onChange)="onScrollerTypeChange(scroller)"
|
(onChange)="onScrollerTypeChange(scroller)"
|
||||||
[placeholder]="t('selectType')"
|
[placeholder]="t('selectType')"
|
||||||
@@ -58,7 +58,7 @@
|
|||||||
<p-select
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
[inputId]="'dashboard-scroller-sort-field-' + scroller.id"
|
[inputId]="'dashboard-scroller-sort-field-' + scroller.id"
|
||||||
[options]="sortFieldOptions"
|
[options]="sortFieldOptions()"
|
||||||
[(ngModel)]="scroller.sortField"
|
[(ngModel)]="scroller.sortField"
|
||||||
[placeholder]="t('selectField')"
|
[placeholder]="t('selectField')"
|
||||||
appendTo="body">
|
appendTo="body">
|
||||||
@@ -70,7 +70,7 @@
|
|||||||
<p-select
|
<p-select
|
||||||
fluid
|
fluid
|
||||||
[inputId]="'dashboard-scroller-sort-direction-' + scroller.id"
|
[inputId]="'dashboard-scroller-sort-direction-' + scroller.id"
|
||||||
[options]="sortDirectionOptions"
|
[options]="sortDirectionOptions()"
|
||||||
[(ngModel)]="scroller.sortDirection"
|
[(ngModel)]="scroller.sortDirection"
|
||||||
[placeholder]="t('selectDirection')"
|
[placeholder]="t('selectDirection')"
|
||||||
appendTo="body">
|
appendTo="body">
|
||||||
|
|||||||
+41
-41
@@ -32,60 +32,32 @@ export const MAX_ITEMS = 20;
|
|||||||
styleUrls: ['./dashboard-settings.component.scss']
|
styleUrls: ['./dashboard-settings.component.scss']
|
||||||
})
|
})
|
||||||
export class DashboardSettingsComponent {
|
export class DashboardSettingsComponent {
|
||||||
private configService = inject(DashboardConfigService);
|
private readonly configService = inject(DashboardConfigService);
|
||||||
private dialogRef = inject(DynamicDialogRef);
|
private readonly dialogRef = inject(DynamicDialogRef);
|
||||||
private magicShelfService = inject(MagicShelfService);
|
private readonly magicShelfService = inject(MagicShelfService);
|
||||||
private translocoService = inject(TranslocoService);
|
private readonly translocoService = inject(TranslocoService);
|
||||||
private readonly activeLanguage = toSignal(this.translocoService.langChanges$, {
|
private readonly activeLanguage = toSignal(this.translocoService.langChanges$, {
|
||||||
initialValue: this.translocoService.getActiveLang()
|
initialValue: this.translocoService.getActiveLang()
|
||||||
});
|
});
|
||||||
|
|
||||||
config: DashboardConfig = structuredClone(this.configService.config());
|
config: DashboardConfig = structuredClone(this.configService.config());
|
||||||
|
|
||||||
availableScrollerTypes: {label: string; value: ScrollerType}[] = [];
|
readonly availableScrollerTypes = computed(() => {
|
||||||
sortFieldOptions: {label: string; value: string}[] = [];
|
this.activeLanguage(); // Trigger on language change
|
||||||
sortDirectionOptions: {label: string; value: string}[] = [];
|
|
||||||
|
|
||||||
magicShelves = computed(() =>
|
|
||||||
this.magicShelfService.shelves().map(shelf => ({
|
|
||||||
label: shelf.name,
|
|
||||||
value: shelf.id!
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
private magicShelvesMap = computed(() => {
|
|
||||||
const shelfMap = new Map<number, string>();
|
|
||||||
this.magicShelfService.shelves().forEach(shelf => {
|
|
||||||
if (shelf.id) {
|
|
||||||
shelfMap.set(shelf.id, shelf.name);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return shelfMap;
|
|
||||||
});
|
|
||||||
|
|
||||||
readonly MIN_ITEMS = MIN_ITEMS;
|
|
||||||
readonly MAX_ITEMS = MAX_ITEMS;
|
|
||||||
|
|
||||||
private readonly syncTranslatedOptionsEffect = effect(() => {
|
|
||||||
this.activeLanguage();
|
|
||||||
this.buildTranslatedOptions();
|
|
||||||
});
|
|
||||||
|
|
||||||
private readonly syncConfigEffect = effect(() => {
|
|
||||||
this.config = structuredClone(this.configService.config());
|
|
||||||
});
|
|
||||||
|
|
||||||
private buildTranslatedOptions(): void {
|
|
||||||
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
|
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
|
||||||
|
return [
|
||||||
this.availableScrollerTypes = [
|
|
||||||
{label: t('scrollerTypes.lastRead'), value: ScrollerType.LAST_READ},
|
{label: t('scrollerTypes.lastRead'), value: ScrollerType.LAST_READ},
|
||||||
{label: t('scrollerTypes.lastListened'), value: ScrollerType.LAST_LISTENED},
|
{label: t('scrollerTypes.lastListened'), value: ScrollerType.LAST_LISTENED},
|
||||||
{label: t('scrollerTypes.latestAdded'), value: ScrollerType.LATEST_ADDED},
|
{label: t('scrollerTypes.latestAdded'), value: ScrollerType.LATEST_ADDED},
|
||||||
{label: t('scrollerTypes.random'), value: ScrollerType.RANDOM},
|
{label: t('scrollerTypes.random'), value: ScrollerType.RANDOM},
|
||||||
{label: t('scrollerTypes.magicShelf'), value: ScrollerType.MAGIC_SHELF}
|
{label: t('scrollerTypes.magicShelf'), value: ScrollerType.MAGIC_SHELF}
|
||||||
];
|
];
|
||||||
|
});
|
||||||
|
|
||||||
this.sortFieldOptions = [
|
readonly sortFieldOptions = computed(() => {
|
||||||
|
this.activeLanguage();
|
||||||
|
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
|
||||||
|
return [
|
||||||
{label: t('sortFields.title'), value: 'title'},
|
{label: t('sortFields.title'), value: 'title'},
|
||||||
{label: t('sortFields.fileName'), value: 'fileName'},
|
{label: t('sortFields.fileName'), value: 'fileName'},
|
||||||
{label: t('sortFields.filePath'), value: 'filePath'},
|
{label: t('sortFields.filePath'), value: 'filePath'},
|
||||||
@@ -104,12 +76,40 @@ export class DashboardSettingsComponent {
|
|||||||
{label: t('sortFields.bookType'), value: 'bookType'},
|
{label: t('sortFields.bookType'), value: 'bookType'},
|
||||||
{label: t('sortFields.pageCount'), value: 'pageCount'}
|
{label: t('sortFields.pageCount'), value: 'pageCount'}
|
||||||
];
|
];
|
||||||
|
});
|
||||||
|
|
||||||
this.sortDirectionOptions = [
|
readonly sortDirectionOptions = computed(() => {
|
||||||
|
this.activeLanguage();
|
||||||
|
const t = (key: string) => this.translocoService.translate(`dashboard.settings.${key}`);
|
||||||
|
return [
|
||||||
{label: t('sortDirections.asc'), value: 'asc'},
|
{label: t('sortDirections.asc'), value: 'asc'},
|
||||||
{label: t('sortDirections.desc'), value: 'desc'}
|
{label: t('sortDirections.desc'), value: 'desc'}
|
||||||
];
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly magicShelves = computed(() =>
|
||||||
|
this.magicShelfService.shelves().map(shelf => ({
|
||||||
|
label: shelf.name,
|
||||||
|
value: shelf.id!
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
|
||||||
|
private readonly magicShelvesMap = computed(() => {
|
||||||
|
const shelfMap = new Map<number, string>();
|
||||||
|
this.magicShelfService.shelves().forEach(shelf => {
|
||||||
|
if (shelf.id) {
|
||||||
|
shelfMap.set(shelf.id, shelf.name);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
return shelfMap;
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly MIN_ITEMS = MIN_ITEMS;
|
||||||
|
readonly MAX_ITEMS = MAX_ITEMS;
|
||||||
|
|
||||||
|
private readonly syncConfigEffect = effect(() => {
|
||||||
|
this.config = structuredClone(this.configService.config());
|
||||||
|
});
|
||||||
|
|
||||||
getScrollerTitle(scroller: ScrollerConfig): string {
|
getScrollerTitle(scroller: ScrollerConfig): string {
|
||||||
if (scroller.type === ScrollerType.MAGIC_SHELF && scroller.magicShelfId) {
|
if (scroller.type === ScrollerType.MAGIC_SHELF && scroller.magicShelfId) {
|
||||||
|
|||||||
+14
-161
@@ -1,25 +1,19 @@
|
|||||||
import {ChangeDetectionStrategy, Component, computed, inject, OnInit} from '@angular/core';
|
import {ChangeDetectionStrategy, Component, computed, inject} from '@angular/core';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
||||||
import {BookService} from '../../../book/service/book.service';
|
import {BookService} from '../../../book/service/book.service';
|
||||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
import {DashboardConfigService} from '../../services/dashboard-config.service';
|
import {DashboardConfigService} from '../../services/dashboard-config.service';
|
||||||
import {ScrollerConfig, ScrollerType} from '../../models/dashboard-config.model';
|
import {ScrollerConfig, ScrollerType} from '../../models/dashboard-config.model';
|
||||||
import {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 {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
|
||||||
import {SortService} from '../../../book/service/sort.service';
|
|
||||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||||
import {SortDirection, SortOption} from '../../../book/model/sort.model';
|
|
||||||
import {LibraryService} from '../../../book/service/library.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/book-browser/book-card-overlay-preference.service';
|
||||||
|
import {DashboardBookService} from '../../services/dashboard-book.service';
|
||||||
const DEFAULT_MAX_ITEMS = 20;
|
import {Book} from '../../../book/model/book.model';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-main-dashboard',
|
selector: 'app-main-dashboard',
|
||||||
@@ -35,19 +29,17 @@ const DEFAULT_MAX_ITEMS = 20;
|
|||||||
],
|
],
|
||||||
standalone: true
|
standalone: true
|
||||||
})
|
})
|
||||||
export class MainDashboardComponent implements OnInit {
|
export class MainDashboardComponent {
|
||||||
|
|
||||||
private bookService = inject(BookService);
|
private readonly bookService = inject(BookService);
|
||||||
private libraryService = inject(LibraryService);
|
private readonly libraryService = inject(LibraryService);
|
||||||
private dialogLauncher = inject(DialogLauncherService);
|
private readonly dialogLauncher = inject(DialogLauncherService);
|
||||||
protected userService = inject(UserService);
|
protected readonly userService = inject(UserService);
|
||||||
private dashboardConfigService = inject(DashboardConfigService);
|
private readonly dashboardConfigService = inject(DashboardConfigService);
|
||||||
private magicShelfService = inject(MagicShelfService);
|
private readonly dashboardBookService = inject(DashboardBookService);
|
||||||
private ruleEvaluatorService = inject(BookRuleEvaluatorService);
|
private readonly pageTitle = inject(PageTitleService);
|
||||||
private sortService = inject(SortService);
|
|
||||||
private pageTitle = inject(PageTitleService);
|
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
protected overlayPreferenceService = inject(BookCardOverlayPreferenceService);
|
protected readonly overlayPreferenceService = inject(BookCardOverlayPreferenceService);
|
||||||
|
|
||||||
readonly dashboardConfig = this.dashboardConfigService.config;
|
readonly dashboardConfig = this.dashboardConfigService.config;
|
||||||
readonly isBooksLoading = this.bookService.isBooksLoading;
|
readonly isBooksLoading = this.bookService.isBooksLoading;
|
||||||
@@ -59,153 +51,14 @@ export class MainDashboardComponent implements OnInit {
|
|||||||
return this.dashboardConfig().scrollers.filter(s => s.enabled);
|
return this.dashboardConfig().scrollers.filter(s => s.enabled);
|
||||||
});
|
});
|
||||||
|
|
||||||
private readonly scrollerBooksMap = computed(() => {
|
|
||||||
const config = this.dashboardConfig();
|
|
||||||
const books = this.bookService.books();
|
|
||||||
const scrollerMap = new Map<string, Book[]>();
|
|
||||||
|
|
||||||
for (const scroller of config.scrollers) {
|
|
||||||
scrollerMap.set(scroller.id, this.getBooksForConfig(scroller, books, this.magicShelfService.shelves()));
|
|
||||||
}
|
|
||||||
|
|
||||||
return scrollerMap;
|
|
||||||
});
|
|
||||||
|
|
||||||
ScrollerType = ScrollerType;
|
ScrollerType = ScrollerType;
|
||||||
|
|
||||||
ngOnInit(): void {
|
constructor() {
|
||||||
this.pageTitle.setPageTitle(this.t.translate('dashboard.main.pageTitle'));
|
this.pageTitle.setPageTitle(this.t.translate('dashboard.main.pageTitle'));
|
||||||
}
|
}
|
||||||
|
|
||||||
getBooksForScroller(config: ScrollerConfig): Book[] {
|
getBooksForScroller(config: ScrollerConfig): Book[] {
|
||||||
return this.scrollerBooksMap().get(config.id) ?? [];
|
return this.dashboardBookService.scrollerBooksMap().get(config.id) ?? [];
|
||||||
}
|
|
||||||
|
|
||||||
private getBooksForConfig(config: ScrollerConfig, books: Book[], magicShelves: {id?: number | null; filterJson: string}[]): Book[] {
|
|
||||||
switch (config.type) {
|
|
||||||
case ScrollerType.LAST_READ:
|
|
||||||
return this.getLastReadBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
|
||||||
case ScrollerType.LAST_LISTENED:
|
|
||||||
return this.getLastListenedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
|
||||||
case ScrollerType.LATEST_ADDED:
|
|
||||||
return this.getLatestAddedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
|
||||||
case ScrollerType.RANDOM:
|
|
||||||
return this.getRandomBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
|
||||||
case ScrollerType.MAGIC_SHELF:
|
|
||||||
return this.getMagicShelfBooks(config, books, magicShelves);
|
|
||||||
default:
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getLastReadBooks(books: Book[], maxItems: number): Book[] {
|
|
||||||
const recentBooks = books.filter(book =>
|
|
||||||
book.lastReadTime &&
|
|
||||||
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
|
|
||||||
this.hasEbookProgress(book)
|
|
||||||
);
|
|
||||||
|
|
||||||
return recentBooks.sort((a, b) => {
|
|
||||||
const aTime = new Date(a.lastReadTime!).getTime();
|
|
||||||
const bTime = new Date(b.lastReadTime!).getTime();
|
|
||||||
return bTime - aTime;
|
|
||||||
}).slice(0, maxItems);
|
|
||||||
}
|
|
||||||
|
|
||||||
private getLastListenedBooks(books: Book[], maxItems: number): Book[] {
|
|
||||||
const recentBooks = books.filter(book =>
|
|
||||||
book.lastReadTime &&
|
|
||||||
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
|
|
||||||
book.audiobookProgress
|
|
||||||
);
|
|
||||||
|
|
||||||
return recentBooks.sort((a, b) => {
|
|
||||||
const aTime = new Date(a.lastReadTime!).getTime();
|
|
||||||
const bTime = new Date(b.lastReadTime!).getTime();
|
|
||||||
return bTime - aTime;
|
|
||||||
}).slice(0, maxItems);
|
|
||||||
}
|
|
||||||
|
|
||||||
private hasEbookProgress(book: Book): boolean {
|
|
||||||
return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress);
|
|
||||||
}
|
|
||||||
|
|
||||||
private getLatestAddedBooks(books: Book[], maxItems: number): Book[] {
|
|
||||||
const addedBooks = books.filter(book => book.addedOn);
|
|
||||||
|
|
||||||
return addedBooks.sort((a, b) => {
|
|
||||||
const aTime = new Date(a.addedOn!).getTime();
|
|
||||||
const bTime = new Date(b.addedOn!).getTime();
|
|
||||||
return bTime - aTime;
|
|
||||||
}).slice(0, maxItems);
|
|
||||||
}
|
|
||||||
|
|
||||||
private getRandomBooks(books: Book[], maxItems: number): Book[] {
|
|
||||||
const excludedStatuses = new Set<ReadStatus>([
|
|
||||||
ReadStatus.READ,
|
|
||||||
ReadStatus.PARTIALLY_READ,
|
|
||||||
ReadStatus.READING,
|
|
||||||
ReadStatus.PAUSED,
|
|
||||||
ReadStatus.WONT_READ,
|
|
||||||
ReadStatus.ABANDONED
|
|
||||||
]);
|
|
||||||
|
|
||||||
const candidates = books.filter(book =>
|
|
||||||
!book.readStatus || !excludedStatuses.has(book.readStatus)
|
|
||||||
);
|
|
||||||
|
|
||||||
return this.shuffleBooks(candidates, maxItems);
|
|
||||||
}
|
|
||||||
|
|
||||||
private getMagicShelfBooks(
|
|
||||||
config: ScrollerConfig,
|
|
||||||
books: Book[],
|
|
||||||
magicShelves: {id?: number | null; filterJson: string}[]
|
|
||||||
): Book[] {
|
|
||||||
const shelf = magicShelves.find(currentShelf => currentShelf.id === config.magicShelfId);
|
|
||||||
if (!shelf) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
let group: GroupRule;
|
|
||||||
try {
|
|
||||||
group = JSON.parse(shelf.filterJson);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Invalid filter JSON', e);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
let filteredBooks = books.filter(book =>
|
|
||||||
this.ruleEvaluatorService.evaluateGroup(book, group, books)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (config.maxItems) {
|
|
||||||
filteredBooks = filteredBooks.slice(0, config.maxItems);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config.sortField && config.sortDirection) {
|
|
||||||
const sortOption = this.createSortOption(config.sortField, config.sortDirection);
|
|
||||||
return this.sortService.applySort(filteredBooks, sortOption);
|
|
||||||
}
|
|
||||||
|
|
||||||
return filteredBooks;
|
|
||||||
}
|
|
||||||
|
|
||||||
private createSortOption(field: string, direction: string): SortOption {
|
|
||||||
return {
|
|
||||||
field,
|
|
||||||
direction: direction === 'asc' ? SortDirection.ASCENDING : SortDirection.DESCENDING,
|
|
||||||
label: ''
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private shuffleBooks(books: Book[], maxItems: number): Book[] {
|
|
||||||
const shuffled = [...books];
|
|
||||||
for (let i = shuffled.length - 1; i > 0; i--) {
|
|
||||||
const j = Math.floor(Math.random() * (i + 1));
|
|
||||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
|
||||||
}
|
|
||||||
return shuffled.slice(0, maxItems);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
openDashboardSettings(): void {
|
openDashboardSettings(): void {
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import {computed, inject, Injectable} from '@angular/core';
|
||||||
|
import {BookService} from '../../book/service/book.service';
|
||||||
|
import {Book, ReadStatus} from '../../book/model/book.model';
|
||||||
|
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||||
|
import {BookRuleEvaluatorService} from '../../magic-shelf/service/book-rule-evaluator.service';
|
||||||
|
import {SortService} from '../../book/service/sort.service';
|
||||||
|
import {ScrollerConfig, ScrollerType} from '../models/dashboard-config.model';
|
||||||
|
import {SortDirection, SortOption} from '../../book/model/sort.model';
|
||||||
|
import {DashboardConfigService} from './dashboard-config.service';
|
||||||
|
import {GroupRule} from '../../magic-shelf/component/magic-shelf-component';
|
||||||
|
|
||||||
|
const DEFAULT_MAX_ITEMS = 20;
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class DashboardBookService {
|
||||||
|
private readonly bookService = inject(BookService);
|
||||||
|
private readonly magicShelfService = inject(MagicShelfService);
|
||||||
|
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||||
|
private readonly sortService = inject(SortService);
|
||||||
|
private readonly configService = inject(DashboardConfigService);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computed map of scroller ID to its filtered book list.
|
||||||
|
* This centralizes all dashboard filtering logic and keeps it reactive.
|
||||||
|
*/
|
||||||
|
readonly scrollerBooksMap = computed(() => {
|
||||||
|
const config = this.configService.config();
|
||||||
|
const books = this.bookService.books();
|
||||||
|
const shelves = this.magicShelfService.shelves();
|
||||||
|
const scrollerMap = new Map<string, Book[]>();
|
||||||
|
|
||||||
|
for (const scroller of config.scrollers) {
|
||||||
|
if (!scroller.enabled) continue;
|
||||||
|
scrollerMap.set(scroller.id, this.getBooksForConfig(scroller, books, shelves));
|
||||||
|
}
|
||||||
|
|
||||||
|
return scrollerMap;
|
||||||
|
});
|
||||||
|
|
||||||
|
private getBooksForConfig(config: ScrollerConfig, books: Book[], magicShelves: {id?: number | null; filterJson: string}[]): Book[] {
|
||||||
|
switch (config.type) {
|
||||||
|
case ScrollerType.LAST_READ:
|
||||||
|
return this.getLastReadBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
|
case ScrollerType.LAST_LISTENED:
|
||||||
|
return this.getLastListenedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
|
case ScrollerType.LATEST_ADDED:
|
||||||
|
return this.getLatestAddedBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
|
case ScrollerType.RANDOM:
|
||||||
|
return this.getRandomBooks(books, config.maxItems || DEFAULT_MAX_ITEMS);
|
||||||
|
case ScrollerType.MAGIC_SHELF:
|
||||||
|
return this.getMagicShelfBooks(config, books, magicShelves);
|
||||||
|
default:
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getLastReadBooks(books: Book[], maxItems: number): Book[] {
|
||||||
|
const recentBooks = books.filter(book =>
|
||||||
|
book.lastReadTime &&
|
||||||
|
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
|
||||||
|
this.hasEbookProgress(book)
|
||||||
|
);
|
||||||
|
|
||||||
|
return recentBooks.sort((a, b) => {
|
||||||
|
const aTime = new Date(a.lastReadTime!).getTime();
|
||||||
|
const bTime = new Date(b.lastReadTime!).getTime();
|
||||||
|
return bTime - aTime;
|
||||||
|
}).slice(0, maxItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getLastListenedBooks(books: Book[], maxItems: number): Book[] {
|
||||||
|
const recentBooks = books.filter(book =>
|
||||||
|
book.lastReadTime &&
|
||||||
|
(book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) &&
|
||||||
|
book.audiobookProgress
|
||||||
|
);
|
||||||
|
|
||||||
|
return recentBooks.sort((a, b) => {
|
||||||
|
const aTime = new Date(a.lastReadTime!).getTime();
|
||||||
|
const bTime = new Date(b.lastReadTime!).getTime();
|
||||||
|
return bTime - aTime;
|
||||||
|
}).slice(0, maxItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
private hasEbookProgress(book: Book): boolean {
|
||||||
|
return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getLatestAddedBooks(books: Book[], maxItems: number): Book[] {
|
||||||
|
const addedBooks = books.filter(book => book.addedOn);
|
||||||
|
|
||||||
|
return addedBooks.sort((a, b) => {
|
||||||
|
const aTime = new Date(a.addedOn!).getTime();
|
||||||
|
const bTime = new Date(b.addedOn!).getTime();
|
||||||
|
return bTime - aTime;
|
||||||
|
}).slice(0, maxItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getRandomBooks(books: Book[], maxItems: number): Book[] {
|
||||||
|
const excludedStatuses = new Set<ReadStatus>([
|
||||||
|
ReadStatus.READ,
|
||||||
|
ReadStatus.PARTIALLY_READ,
|
||||||
|
ReadStatus.READING,
|
||||||
|
ReadStatus.PAUSED,
|
||||||
|
ReadStatus.WONT_READ,
|
||||||
|
ReadStatus.ABANDONED
|
||||||
|
]);
|
||||||
|
|
||||||
|
const candidates = books.filter(book =>
|
||||||
|
!book.readStatus || !excludedStatuses.has(book.readStatus)
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.shuffleBooks(candidates, maxItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getMagicShelfBooks(
|
||||||
|
config: ScrollerConfig,
|
||||||
|
books: Book[],
|
||||||
|
magicShelves: {id?: number | null; filterJson: string}[]
|
||||||
|
): Book[] {
|
||||||
|
const shelf = magicShelves.find(currentShelf => currentShelf.id === config.magicShelfId);
|
||||||
|
if (!shelf) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
let group: GroupRule;
|
||||||
|
try {
|
||||||
|
group = JSON.parse(shelf.filterJson);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Invalid filter JSON', e);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
let filteredBooks = books.filter(book =>
|
||||||
|
this.ruleEvaluatorService.evaluateGroup(book, group, books)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (config.sortField && config.sortDirection) {
|
||||||
|
const sortOption = this.createSortOption(config.sortField, config.sortDirection);
|
||||||
|
filteredBooks = this.sortService.applySort(filteredBooks, sortOption);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.maxItems) {
|
||||||
|
filteredBooks = filteredBooks.slice(0, config.maxItems);
|
||||||
|
}
|
||||||
|
|
||||||
|
return filteredBooks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private createSortOption(field: string, direction: string): SortOption {
|
||||||
|
return {
|
||||||
|
field,
|
||||||
|
direction: direction === 'asc' ? SortDirection.ASCENDING : SortDirection.DESCENDING,
|
||||||
|
label: ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private shuffleBooks(books: Book[], maxItems: number): Book[] {
|
||||||
|
const shuffled = [...books];
|
||||||
|
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||||
|
}
|
||||||
|
return shuffled.slice(0, maxItems);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
<div #readerRoot class="comic-reader-container" tabindex="0"
|
<div #readerRoot class="comic-reader-container" tabindex="0"
|
||||||
[class.rtl-reading]="readingDirection === CbxReadingDirection.RTL"
|
[class.rtl-reading]="readingDirection() === CbxReadingDirection.RTL"
|
||||||
[class.fullscreen-mode]="isFullscreen" [class.slideshow-active]="isSlideshowActive">
|
[class.fullscreen-mode]="isFullscreen()" [class.slideshow-active]="isSlideshowActive()">
|
||||||
<app-cbx-header [isCurrentPageBookmarked]="isCurrentPageBookmarked"
|
<app-cbx-header [isCurrentPageBookmarked]="isCurrentPageBookmarked()"
|
||||||
[currentPageHasNotes]="currentPageHasNotes"></app-cbx-header>
|
[currentPageHasNotes]="currentPageHasNotes()"></app-cbx-header>
|
||||||
|
|
||||||
<app-cbx-sidebar></app-cbx-sidebar>
|
<app-cbx-sidebar></app-cbx-sidebar>
|
||||||
|
|
||||||
@if (showWebtoonSuggestion) {
|
@if (showWebtoonSuggestion()) {
|
||||||
<div class="webtoon-suggestion-banner" role="region" [attr.aria-label]="'readerCbx.webtoonHint.regionLabel' | transloco">
|
<div class="webtoon-suggestion-banner" role="region" [attr.aria-label]="'readerCbx.webtoonHint.regionLabel' | transloco">
|
||||||
<p class="webtoon-suggestion-text">{{ 'readerCbx.webtoonHint.message' | transloco }}</p>
|
<p class="webtoon-suggestion-text">{{ 'readerCbx.webtoonHint.message' | transloco }}</p>
|
||||||
<div class="webtoon-suggestion-actions">
|
<div class="webtoon-suggestion-actions">
|
||||||
@@ -23,11 +23,11 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (showQuickSettings) {
|
@if (showQuickSettings()) {
|
||||||
<app-cbx-quick-settings></app-cbx-quick-settings>
|
<app-cbx-quick-settings></app-cbx-quick-settings>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (isCurrentPageBookmarked) {
|
@if (isCurrentPageBookmarked()) {
|
||||||
<div class="bookmark-indicator">
|
<div class="bookmark-indicator">
|
||||||
<svg width="48" height="64" viewBox="0 0 48 64">
|
<svg width="48" height="64" viewBox="0 0 48 64">
|
||||||
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red" />
|
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red" />
|
||||||
@@ -35,57 +35,57 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (showNoteDialog) {
|
@if (showNoteDialog()) {
|
||||||
<app-cbx-note-dialog [data]="noteDialogData" (saved)="onNoteSave($event)"
|
<app-cbx-note-dialog [data]="noteDialogData()" (saved)="onNoteSave($event)"
|
||||||
(cancelled)="onNoteCancel()"></app-cbx-note-dialog>
|
(cancelled)="onNoteCancel()"></app-cbx-note-dialog>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (showShortcutsHelp) {
|
@if (showShortcutsHelp()) {
|
||||||
<app-cbx-shortcuts-help (closed)="onShortcutsHelpClose()"></app-cbx-shortcuts-help>
|
<app-cbx-shortcuts-help (closed)="onShortcutsHelpClose()"></app-cbx-shortcuts-help>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (isSlideshowActive) {
|
@if (isSlideshowActive()) {
|
||||||
<div class="slideshow-progress" [class.above-footer]="isFooterVisible"
|
<div class="slideshow-progress" [class.above-footer]="isFooterVisible()"
|
||||||
[style.animation-duration.ms]="slideshowInterval"></div>
|
[style.animation-duration.ms]="slideshowInterval()"></div>
|
||||||
}
|
}
|
||||||
|
|
||||||
<div #magnifierLens class="magnifier-lens"></div>
|
<div #magnifierLens class="magnifier-lens"></div>
|
||||||
|
|
||||||
<div #imageScrollHost class="image-container" [class.magnifier-active]="isMagnifierActive"
|
<div #imageScrollHost class="image-container" [class.magnifier-active]="isMagnifierActive()"
|
||||||
[class.two-page-view]="isTwoPageView && scrollMode === CbxScrollMode.PAGINATED"
|
[class.two-page-view]="isTwoPageView() && scrollMode() === CbxScrollMode.PAGINATED"
|
||||||
[class.infinite-scroll]="scrollMode === CbxScrollMode.INFINITE"
|
[class.infinite-scroll]="scrollMode() === CbxScrollMode.INFINITE"
|
||||||
[class.long-strip]="scrollMode === CbxScrollMode.LONG_STRIP"
|
[class.long-strip]="scrollMode() === CbxScrollMode.LONG_STRIP"
|
||||||
[class.fit-actual-size]="fitMode === CbxFitMode.ACTUAL_SIZE" [class.fit-page]="fitMode === CbxFitMode.FIT_PAGE"
|
[class.fit-actual-size]="fitMode() === CbxFitMode.ACTUAL_SIZE" [class.fit-page]="fitMode() === CbxFitMode.FIT_PAGE"
|
||||||
[class.fit-width]="fitMode === CbxFitMode.FIT_WIDTH" [class.fit-height]="fitMode === CbxFitMode.FIT_HEIGHT"
|
[class.fit-width]="fitMode() === CbxFitMode.FIT_WIDTH" [class.fit-height]="fitMode() === CbxFitMode.FIT_HEIGHT"
|
||||||
[class.fit-auto]="fitMode === CbxFitMode.AUTO" [class.bg-black]="backgroundColor === CbxBackgroundColor.BLACK"
|
[class.fit-auto]="fitMode() === CbxFitMode.AUTO" [class.bg-black]="backgroundColor() === CbxBackgroundColor.BLACK"
|
||||||
[class.bg-gray]="backgroundColor === CbxBackgroundColor.GRAY"
|
[class.bg-gray]="backgroundColor() === CbxBackgroundColor.GRAY"
|
||||||
[class.bg-white]="backgroundColor === CbxBackgroundColor.WHITE" [class.emulate-book]="emulateBook && isTwoPageView"
|
[class.bg-white]="backgroundColor() === CbxBackgroundColor.WHITE" [class.emulate-book]="emulateBook() && isTwoPageView()"
|
||||||
[style.filter]="brightness < 100 ? 'brightness(' + brightness + '%)' : null" (scroll)="onScroll($event)">
|
[style.filter]="brightness() < 100 ? 'brightness(' + brightness() + '%)' : null" (scroll)="onScroll($event)">
|
||||||
@if (!isLoading) {
|
@if (!isLoading()) {
|
||||||
@if (pages.length > 0) {
|
@if (pages().length > 0) {
|
||||||
@if (scrollMode === CbxScrollMode.PAGINATED) {
|
@if (scrollMode() === CbxScrollMode.PAGINATED) {
|
||||||
<div class="pages-wrapper" role="button" tabindex="0" (click)="onImageClick()" (keydown.enter)="onImageClick()"
|
<div class="pages-wrapper" role="button" tabindex="0" (click)="onImageClick()" (keydown.enter)="onImageClick()"
|
||||||
(dblclick)="onImageDoubleClick()">
|
(dblclick)="onImageDoubleClick()">
|
||||||
@if (isPageTransitioning && previousImageUrls.length > 0) {
|
@if (isPageTransitioning() && previousImageUrls().length > 0) {
|
||||||
<div class="previous-page-layer">
|
<div class="previous-page-layer">
|
||||||
@for (url of previousImageUrls; track url) {
|
@for (url of previousImageUrls(); track url) {
|
||||||
<img [src]="url" alt="Previous Page" class="page-image previous-image" />
|
<img [src]="url" alt="Previous Page" class="page-image previous-image" />
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="current-page-layer" [class.fade-in]="isPageTransitioning && imagesLoaded">
|
<div class="current-page-layer" [class.fade-in]="isPageTransitioning() && imagesLoaded()">
|
||||||
@if (shouldUseCanvasRenderer()) {
|
@if (shouldUseCanvasRenderer()) {
|
||||||
<app-canvas-renderer [imageUrl]="currentImageUrls[0]" [splitState]="canvasSplitState"
|
<app-canvas-renderer [imageUrl]="currentImageUrls()[0]" [splitState]="canvasSplitState"
|
||||||
[splitOption]="pageSplitOption">
|
[splitOption]="pageSplitOption()">
|
||||||
</app-canvas-renderer>
|
</app-canvas-renderer>
|
||||||
} @else {
|
} @else {
|
||||||
@for (url of currentImageUrls; track url; let i = $index) {
|
@for (url of currentImageUrls(); track url; let i = $index) {
|
||||||
<img [src]="url" alt="Page Image" class="page-image" (load)="onPageImageLoad($event, currentPage + i)" />
|
<img [src]="url" alt="Page Image" class="page-image" (load)="onPageImageLoad($event, currentPage() + i)" />
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@if (isAtLastPage && nextBookInSeries) {
|
@if (isAtLastPage() && nextBookInSeries) {
|
||||||
<div class="end-of-comic-action">
|
<div class="end-of-comic-action">
|
||||||
<button class="next-book-action-button" (click)="navigateToNextBook()">
|
<button class="next-book-action-button" (click)="navigateToNextBook()">
|
||||||
<span class="action-icon">📖</span>
|
<span class="action-icon">📖</span>
|
||||||
@@ -94,21 +94,21 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
} @else if (scrollMode === CbxScrollMode.LONG_STRIP) {
|
} @else if (scrollMode() === CbxScrollMode.LONG_STRIP) {
|
||||||
<div class="long-strip-wrapper" role="button" tabindex="0" (click)="onImageClick()"
|
<div class="long-strip-wrapper" role="button" tabindex="0" (click)="onImageClick()"
|
||||||
(keydown.enter)="onImageClick()">
|
(keydown.enter)="onImageClick()">
|
||||||
<div class="strip-width-constrain" [style.width]="cbxQuickSettingsState().stripMaxWidthPercent + '%'">
|
<div class="strip-width-constrain" [style.width]="cbxQuickSettingsState().stripMaxWidthPercent + '%'">
|
||||||
@for (item of longStripImages; track item.page) {
|
@for (item of longStripImages(); track item.page) {
|
||||||
<img [src]="item.src" alt="Page {{ item.page + 1 }}" class="long-strip-image" [attr.data-page]="item.page"
|
<img [src]="item.src" alt="Page {{ item.page + 1 }}" class="long-strip-image" [attr.data-page]="item.page"
|
||||||
draggable="false" [attr.loading]="item.page === currentPage ? 'eager' : 'lazy'" decoding="async" (load)="onLongStripImageLoad($event, item.page)" />
|
draggable="false" [attr.loading]="item.page === currentPage() ? 'eager' : 'lazy'" decoding="async" (load)="onLongStripImageLoad($event, item.page)" />
|
||||||
}
|
}
|
||||||
@if (nextBookInSeries) {
|
@if (nextBookInSeries) {
|
||||||
<div class="cbx-continuation-spacer" aria-hidden="true"></div>
|
<div class="cbx-continuation-spacer" aria-hidden="true"></div>
|
||||||
<div class="cbx-continuation-hint" [class.visible]="continuationHintVisible" aria-live="polite">
|
<div class="cbx-continuation-hint" [class.visible]="continuationHintVisible()" aria-live="polite">
|
||||||
{{ 'readerCbx.continuation.scrollForNext' | transloco }}
|
{{ 'readerCbx.continuation.scrollForNext' | transloco }}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (isAtEndOfLongStrip && nextBookInSeries) {
|
@if (isAtEndOfLongStrip() && nextBookInSeries) {
|
||||||
<div class="end-of-comic-action">
|
<div class="end-of-comic-action">
|
||||||
<button class="next-book-action-button" (click)="navigateToNextBook()">
|
<button class="next-book-action-button" (click)="navigateToNextBook()">
|
||||||
<span class="action-icon">📖</span>
|
<span class="action-icon">📖</span>
|
||||||
@@ -122,25 +122,25 @@
|
|||||||
} @else {
|
} @else {
|
||||||
<div class="infinite-scroll-wrapper">
|
<div class="infinite-scroll-wrapper">
|
||||||
<div class="strip-width-constrain" [style.width]="cbxQuickSettingsState().stripMaxWidthPercent + '%'">
|
<div class="strip-width-constrain" [style.width]="cbxQuickSettingsState().stripMaxWidthPercent + '%'">
|
||||||
@for (pageIdx of infiniteScrollPages; track pageIdx) {
|
@for (pageIdx of infiniteScrollPages(); track pageIdx) {
|
||||||
<img [src]="getPageImageUrl(pageIdx)" alt="Page {{ pageIdx + 1 }}" class="page-image"
|
<img [src]="getPageImageUrl(pageIdx)" alt="Page {{ pageIdx + 1 }}" class="page-image"
|
||||||
[attr.data-page]="pageIdx" role="button" tabindex="0" draggable="false"
|
[attr.data-page]="pageIdx" role="button" tabindex="0" draggable="false"
|
||||||
[attr.loading]="pageIdx === currentPage ? 'eager' : 'lazy'" decoding="async"
|
[attr.loading]="pageIdx === currentPage() ? 'eager' : 'lazy'" decoding="async"
|
||||||
(click)="onImageClick()" (keydown.enter)="onImageClick()" (dblclick)="onImageDoubleClick()"
|
(click)="onImageClick()" (keydown.enter)="onImageClick()" (dblclick)="onImageDoubleClick()"
|
||||||
(load)="onPageImageLoad($event, pageIdx)" />
|
(load)="onPageImageLoad($event, pageIdx)" />
|
||||||
}
|
}
|
||||||
@if (isLoadingMore) {
|
@if (isLoadingMore()) {
|
||||||
<div class="loading-more">
|
<div class="loading-more">
|
||||||
<p-progressSpinner class="small-spinner"></p-progressSpinner>
|
<p-progressSpinner class="small-spinner"></p-progressSpinner>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (nextBookInSeries) {
|
@if (nextBookInSeries) {
|
||||||
<div class="cbx-continuation-spacer" aria-hidden="true"></div>
|
<div class="cbx-continuation-spacer" aria-hidden="true"></div>
|
||||||
<div class="cbx-continuation-hint" [class.visible]="continuationHintVisible" aria-live="polite">
|
<div class="cbx-continuation-hint" [class.visible]="continuationHintVisible()" aria-live="polite">
|
||||||
{{ 'readerCbx.continuation.scrollForNext' | transloco }}
|
{{ 'readerCbx.continuation.scrollForNext' | transloco }}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (isAtEndOfInfiniteScroll && nextBookInSeries) {
|
@if (isAtEndOfInfiniteScroll() && nextBookInSeries) {
|
||||||
<div class="end-of-comic-action">
|
<div class="end-of-comic-action">
|
||||||
<button class="next-book-action-button" (click)="navigateToNextBook()">
|
<button class="next-book-action-button" (click)="navigateToNextBook()">
|
||||||
<span class="action-icon">📖</span>
|
<span class="action-icon">📖</span>
|
||||||
@@ -153,9 +153,9 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (clickToPaginate) {
|
@if (clickToPaginate()) {
|
||||||
<div class="click-overlay visible" [class.rtl-overlay]="readingDirection === CbxReadingDirection.RTL"
|
<div class="click-overlay visible" [class.rtl-overlay]="readingDirection() === CbxReadingDirection.RTL"
|
||||||
[class.magnifier-disabled]="isMagnifierActive">
|
[class.magnifier-disabled]="isMagnifierActive()">
|
||||||
<div class="click-zone click-zone-prev" role="button" tabindex="0" (click)="onClickZonePrev($event)"
|
<div class="click-zone click-zone-prev" role="button" tabindex="0" (click)="onClickZonePrev($event)"
|
||||||
(keydown.enter)="onClickZonePrev($event)">
|
(keydown.enter)="onClickZonePrev($event)">
|
||||||
<span class="zone-arrow">◀</span>
|
<span class="zone-arrow">◀</span>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+6
-9
@@ -1,6 +1,6 @@
|
|||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {of, Subject} from 'rxjs';
|
import {of} from 'rxjs';
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service';
|
import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service';
|
||||||
@@ -12,7 +12,6 @@ import {CbxSidebarService} from './cbx-sidebar.service';
|
|||||||
|
|
||||||
describe('CbxSidebarService', () => {
|
describe('CbxSidebarService', () => {
|
||||||
let service: CbxSidebarService;
|
let service: CbxSidebarService;
|
||||||
let destroy$: Subject<void>;
|
|
||||||
|
|
||||||
const pageInfo: CbxPageInfo[] = [
|
const pageInfo: CbxPageInfo[] = [
|
||||||
{pageNumber: 1, displayName: 'Page 1'},
|
{pageNumber: 1, displayName: 'Page 1'},
|
||||||
@@ -76,7 +75,6 @@ describe('CbxSidebarService', () => {
|
|||||||
} as Book);
|
} as Book);
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
destroy$ = new Subject<void>();
|
|
||||||
cbxReaderService.getPageInfo.mockReset();
|
cbxReaderService.getPageInfo.mockReset();
|
||||||
cbxReaderService.getPageInfo.mockReturnValue(of(pageInfo));
|
cbxReaderService.getPageInfo.mockReturnValue(of(pageInfo));
|
||||||
bookMarkService.getBookmarksForBook.mockReset();
|
bookMarkService.getBookmarksForBook.mockReset();
|
||||||
@@ -112,12 +110,11 @@ describe('CbxSidebarService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
destroy$.complete();
|
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('initializes book info and loads pages, bookmarks, and notes', () => {
|
it('initializes book info and loads pages, bookmarks, and notes', () => {
|
||||||
service.initialize(7, createBook(), destroy$, 'CBX');
|
service.initialize(7, createBook(), 'CBX');
|
||||||
|
|
||||||
expect(cbxReaderService.getPageInfo).toHaveBeenCalledWith(7, 'CBX');
|
expect(cbxReaderService.getPageInfo).toHaveBeenCalledWith(7, 'CBX');
|
||||||
expect(bookMarkService.getBookmarksForBook).toHaveBeenCalledWith(7);
|
expect(bookMarkService.getBookmarksForBook).toHaveBeenCalledWith(7);
|
||||||
@@ -135,7 +132,7 @@ describe('CbxSidebarService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('falls back to translated untitled book info when metadata is missing', () => {
|
it('falls back to translated untitled book info when metadata is missing', () => {
|
||||||
service.initialize(7, createBook({metadata: undefined, fileName: undefined}), destroy$);
|
service.initialize(7, createBook({metadata: undefined, fileName: undefined}));
|
||||||
|
|
||||||
expect(service.bookInfo()).toEqual({
|
expect(service.bookInfo()).toEqual({
|
||||||
id: 7,
|
id: 7,
|
||||||
@@ -161,7 +158,7 @@ describe('CbxSidebarService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('supports bookmark lookups, creation, deletion, and toggle branches', () => {
|
it('supports bookmark lookups, creation, deletion, and toggle branches', () => {
|
||||||
service.initialize(7, createBook(), destroy$);
|
service.initialize(7, createBook());
|
||||||
|
|
||||||
expect(service.isPageBookmarked(2)).toBe(true);
|
expect(service.isPageBookmarked(2)).toBe(true);
|
||||||
expect(service.isPageBookmarked(9)).toBe(false);
|
expect(service.isPageBookmarked(9)).toBe(false);
|
||||||
@@ -192,7 +189,7 @@ describe('CbxSidebarService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('filters notes by content or chapter title and clears the query', () => {
|
it('filters notes by content or chapter title and clears the query', () => {
|
||||||
service.initialize(7, createBook(), destroy$);
|
service.initialize(7, createBook());
|
||||||
|
|
||||||
service.setNotesSearchQuery('battle');
|
service.setNotesSearchQuery('battle');
|
||||||
expect(service.filteredNotes()).toEqual([notes[0]]);
|
expect(service.filteredNotes()).toEqual([notes[0]]);
|
||||||
@@ -209,7 +206,7 @@ describe('CbxSidebarService', () => {
|
|||||||
const editEvents: BookNoteV2[] = [];
|
const editEvents: BookNoteV2[] = [];
|
||||||
service.navigateToPage$.subscribe(value => pageEvents.push(value));
|
service.navigateToPage$.subscribe(value => pageEvents.push(value));
|
||||||
service.editNote$.subscribe(value => editEvents.push(value));
|
service.editNote$.subscribe(value => editEvents.push(value));
|
||||||
service.initialize(7, createBook(), destroy$);
|
service.initialize(7, createBook());
|
||||||
|
|
||||||
service.createNote(6, 'Remember this', '#fff000');
|
service.createNote(6, 'Remember this', '#fff000');
|
||||||
expect(bookNoteV2Service.createNote).toHaveBeenCalledWith({
|
expect(bookNoteV2Service.createNote).toHaveBeenCalledWith({
|
||||||
|
|||||||
+12
-13
@@ -1,6 +1,6 @@
|
|||||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
import {computed, DestroyRef, inject, Injectable, signal} from '@angular/core';
|
||||||
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {takeUntil} from 'rxjs/operators';
|
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service';
|
import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service';
|
||||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||||
@@ -25,7 +25,7 @@ export class CbxSidebarService {
|
|||||||
private bookNoteV2Service = inject(BookNoteV2Service);
|
private bookNoteV2Service = inject(BookNoteV2Service);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
private destroy$ = new Subject<void>();
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private bookId!: number;
|
private bookId!: number;
|
||||||
private altBookType?: string;
|
private altBookType?: string;
|
||||||
|
|
||||||
@@ -76,10 +76,9 @@ export class CbxSidebarService {
|
|||||||
navigateToPage$ = this._navigateToPage.asObservable();
|
navigateToPage$ = this._navigateToPage.asObservable();
|
||||||
editNote$ = this._editNote.asObservable();
|
editNote$ = this._editNote.asObservable();
|
||||||
|
|
||||||
initialize(bookId: number, book: Book, destroy$: Subject<void>, altBookType?: string): void {
|
initialize(bookId: number, book: Book, altBookType?: string): void {
|
||||||
this.bookId = bookId;
|
this.bookId = bookId;
|
||||||
this.altBookType = altBookType;
|
this.altBookType = altBookType;
|
||||||
this.destroy$ = destroy$;
|
|
||||||
|
|
||||||
this._bookInfo.set({
|
this._bookInfo.set({
|
||||||
id: book.id,
|
id: book.id,
|
||||||
@@ -95,19 +94,19 @@ export class CbxSidebarService {
|
|||||||
|
|
||||||
private loadPageInfo(): void {
|
private loadPageInfo(): void {
|
||||||
this.cbxReaderService.getPageInfo(this.bookId, this.altBookType)
|
this.cbxReaderService.getPageInfo(this.bookId, this.altBookType)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(pages => this._pages.set(pages));
|
.subscribe(pages => this._pages.set(pages));
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadBookmarks(): void {
|
private loadBookmarks(): void {
|
||||||
this.bookMarkService.getBookmarksForBook(this.bookId)
|
this.bookMarkService.getBookmarksForBook(this.bookId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(bookmarks => this._bookmarks.set(bookmarks));
|
.subscribe(bookmarks => this._bookmarks.set(bookmarks));
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadNotes(): void {
|
private loadNotes(): void {
|
||||||
this.bookNoteV2Service.getNotesForBook(this.bookId)
|
this.bookNoteV2Service.getNotesForBook(this.bookId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(notes => this._notes.set(notes));
|
.subscribe(notes => this._notes.set(notes));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,13 +152,13 @@ export class CbxSidebarService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.bookMarkService.createBookmark(request)
|
this.bookMarkService.createBookmark(request)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.loadBookmarks());
|
.subscribe(() => this.loadBookmarks());
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteBookmark(bookmarkId: number): void {
|
deleteBookmark(bookmarkId: number): void {
|
||||||
this.bookMarkService.deleteBookmark(bookmarkId)
|
this.bookMarkService.deleteBookmark(bookmarkId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.loadBookmarks());
|
.subscribe(() => this.loadBookmarks());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +194,7 @@ export class CbxSidebarService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.bookNoteV2Service.createNote(request)
|
this.bookNoteV2Service.createNote(request)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.loadNotes());
|
.subscribe(() => this.loadNotes());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,13 +205,13 @@ export class CbxSidebarService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.bookNoteV2Service.updateNote(noteId, request)
|
this.bookNoteV2Service.updateNote(noteId, request)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.loadNotes());
|
.subscribe(() => this.loadNotes());
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteNote(noteId: number): void {
|
deleteNote(noteId: number): void {
|
||||||
this.bookNoteV2Service.deleteNote(noteId)
|
this.bookNoteV2Service.deleteNote(noteId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
this._notes.update(notes => notes.filter(note => note.id !== noteId));
|
this._notes.update(notes => notes.filter(note => note.id !== noteId));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {ChangeDetectionStrategy, Component, CUSTOM_ELEMENTS_SCHEMA, DestroyRef, effect, HostListener, inject, OnInit, signal} from '@angular/core';
|
import {ChangeDetectionStrategy, Component, CUSTOM_ELEMENTS_SCHEMA, DestroyRef, effect, HostListener, inject, OnInit, signal} from '@angular/core';
|
||||||
import {from, Observable, of, Subject, throwError} from 'rxjs';
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {catchError, map, switchMap, takeUntil, tap} from 'rxjs/operators';
|
import {forkJoin, from, Observable, of, throwError} from 'rxjs';
|
||||||
|
import {catchError, map, switchMap, tap} from 'rxjs/operators';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {ReaderLoaderService} from './core/loader.service';
|
import {ReaderLoaderService} from './core/loader.service';
|
||||||
import {ReaderViewManagerService} from './core/view-manager.service';
|
import {ReaderViewManagerService} from './core/view-manager.service';
|
||||||
@@ -17,7 +18,7 @@ import {ReaderNoteService} from './features/notes/note.service';
|
|||||||
import {BookService} from '../../book/service/book.service';
|
import {BookService} from '../../book/service/book.service';
|
||||||
import {BookFileService} from '../../book/service/book-file.service';
|
import {BookFileService} from '../../book/service/book-file.service';
|
||||||
import {ActivatedRoute} from '@angular/router';
|
import {ActivatedRoute} from '@angular/router';
|
||||||
import {Book, BookType} from '../../book/model/book.model';
|
import {AdditionalFile, Book, BookType} from '../../book/model/book.model';
|
||||||
import {ReaderHeaderComponent} from './layout/header/header.component';
|
import {ReaderHeaderComponent} from './layout/header/header.component';
|
||||||
import {ReaderSidebarComponent} from './layout/sidebar/sidebar.component';
|
import {ReaderSidebarComponent} from './layout/sidebar/sidebar.component';
|
||||||
import {ReaderLeftSidebarComponent} from './layout/panel/panel.component';
|
import {ReaderLeftSidebarComponent} from './layout/panel/panel.component';
|
||||||
@@ -33,6 +34,7 @@ import {EbookShortcutsHelpComponent} from './dialogs/shortcuts-help.component';
|
|||||||
import {TranslocoPipe} from '@jsverse/transloco';
|
import {TranslocoPipe} from '@jsverse/transloco';
|
||||||
import {RelocateProgressData} from './state/progress.service';
|
import {RelocateProgressData} from './state/progress.service';
|
||||||
import {WakeLockService} from '../../../shared/service/wake-lock.service';
|
import {WakeLockService} from '../../../shared/service/wake-lock.service';
|
||||||
|
import {ViewEvent} from './core/view-manager.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-ebook-reader',
|
selector: 'app-ebook-reader',
|
||||||
@@ -71,8 +73,7 @@ import {WakeLockService} from '../../../shared/service/wake-lock.service';
|
|||||||
changeDetection: ChangeDetectionStrategy.OnPush
|
changeDetection: ChangeDetectionStrategy.OnPush
|
||||||
})
|
})
|
||||||
export class EbookReaderComponent implements OnInit {
|
export class EbookReaderComponent implements OnInit {
|
||||||
private destroy$ = new Subject<void>();
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private destroyRef = inject(DestroyRef);
|
|
||||||
private loaderService = inject(ReaderLoaderService);
|
private loaderService = inject(ReaderLoaderService);
|
||||||
private styleService = inject(ReaderStyleService);
|
private styleService = inject(ReaderStyleService);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
@@ -85,6 +86,7 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
private headerService = inject(ReaderHeaderService);
|
private headerService = inject(ReaderHeaderService);
|
||||||
private noteService = inject(ReaderNoteService);
|
private noteService = inject(ReaderNoteService);
|
||||||
private wakeLockService = inject(WakeLockService);
|
private wakeLockService = inject(WakeLockService);
|
||||||
|
private messageService = inject(MessageService);
|
||||||
|
|
||||||
public sidebarService = inject(ReaderSidebarService);
|
public sidebarService = inject(ReaderSidebarService);
|
||||||
public leftSidebarService = inject(ReaderLeftSidebarService);
|
public leftSidebarService = inject(ReaderLeftSidebarService);
|
||||||
@@ -121,9 +123,6 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.destroyRef.onDestroy(() => {
|
this.destroyRef.onDestroy(() => {
|
||||||
this.destroy$.next();
|
|
||||||
this.destroy$.complete();
|
|
||||||
|
|
||||||
this.wakeLockService.disable();
|
this.wakeLockService.disable();
|
||||||
this.viewManager.destroy();
|
this.viewManager.destroy();
|
||||||
this.annotationService.reset();
|
this.annotationService.reset();
|
||||||
@@ -169,43 +168,107 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.sidebarService.showMetadata$
|
this.sidebarService.showMetadata$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.showMetadata.set(true));
|
.subscribe(() => this.showMetadata.set(true));
|
||||||
|
|
||||||
this.headerService.showControls$
|
this.headerService.showControls$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.showQuickSettings.set(true));
|
.subscribe(() => this.showQuickSettings.set(true));
|
||||||
|
|
||||||
this.headerService.showMetadata$
|
this.headerService.showMetadata$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.showMetadata.set(true));
|
.subscribe(() => this.showMetadata.set(true));
|
||||||
|
|
||||||
this.headerService.toggleFullscreen$
|
this.headerService.toggleFullscreen$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.toggleFullscreen());
|
.subscribe(() => this.toggleFullscreen());
|
||||||
|
|
||||||
this.headerService.showShortcutsHelp$
|
this.headerService.showShortcutsHelp$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.showShortcutsHelp.set(true));
|
.subscribe(() => this.showShortcutsHelp.set(true));
|
||||||
|
|
||||||
// Enable wake lock after a short delay
|
// Enable wake lock after a short delay
|
||||||
setTimeout(() => this.wakeLockService.enable(), 1000);
|
setTimeout(() => this.wakeLockService.enable(), 1000);
|
||||||
|
|
||||||
this.isLoading.set(true);
|
this.isLoading.set(true);
|
||||||
this.initializeFoliate().pipe(
|
|
||||||
switchMap(() => this.epubCustomFontService.loadAndCacheFonts()),
|
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
|
||||||
tap(() => this.stateService.refreshCustomFonts()),
|
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
|
||||||
switchMap(() => this.setupView()),
|
|
||||||
|
// Parallelize Foliate script loading and initial book detail fetch
|
||||||
|
forkJoin([
|
||||||
|
this.initializeFoliate(),
|
||||||
|
from(this.bookService.fetchFreshBookDetail(this.bookId, false))
|
||||||
|
]).pipe(
|
||||||
|
switchMap(([, book]) => {
|
||||||
|
this.book.set(book);
|
||||||
|
const bookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType;
|
||||||
|
if (!bookType) {
|
||||||
|
return throwError(() => new Error('Book type not found'));
|
||||||
|
}
|
||||||
|
|
||||||
|
let bookFileId: number | undefined;
|
||||||
|
if (this.altBookType) {
|
||||||
|
const altFile = book.alternativeFormats?.find((f: AdditionalFile) => f.bookType === this.altBookType);
|
||||||
|
bookFileId = altFile?.id;
|
||||||
|
} else {
|
||||||
|
bookFileId = book.primaryFile?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parallelize font loading/view setup and state initialization
|
||||||
|
return forkJoin([
|
||||||
|
this.epubCustomFontService.loadAndCacheFonts().pipe(
|
||||||
|
tap(() => this.stateService.refreshCustomFonts())
|
||||||
|
),
|
||||||
|
this.setupView().pipe(
|
||||||
|
tap(() => this.subscribeToViewEvents())
|
||||||
|
),
|
||||||
|
this.stateService.initializeState(this.bookId, bookFileId!).pipe(
|
||||||
|
map(() => ({book, bookType, bookFileId}))
|
||||||
|
)
|
||||||
|
]);
|
||||||
|
}),
|
||||||
|
switchMap(([, , {book, bookType, bookFileId}]) => {
|
||||||
|
this.progressService.initialize(this.bookId, bookType, bookFileId);
|
||||||
|
this.selectionService.initialize(this.bookId);
|
||||||
|
this.headerService.initialize(this.bookId, book.metadata?.title || '');
|
||||||
|
|
||||||
|
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
|
||||||
|
const loadBook$ = bookType === 'EPUB' && useStreaming
|
||||||
|
? this.viewManager.loadEpubStreaming(this.bookId, this.altBookType)
|
||||||
|
: this.loadBookBlob();
|
||||||
|
|
||||||
|
return loadBook$.pipe(
|
||||||
tap(() => {
|
tap(() => {
|
||||||
this.subscribeToViewEvents();
|
this.applyStyles();
|
||||||
|
this.sidebarService.initialize(this.bookId, book);
|
||||||
|
this.leftSidebarService.initialize(this.bookId);
|
||||||
|
this.noteService.initialize(this.bookId);
|
||||||
|
}),
|
||||||
|
switchMap(() => this.viewManager.getMetadata()),
|
||||||
|
switchMap(() => {
|
||||||
|
if (!this.hasLoadedOnce) {
|
||||||
|
this.hasLoadedOnce = true;
|
||||||
|
if (book.epubProgress?.cfi) {
|
||||||
|
return this.viewManager.goTo(book.epubProgress.cfi);
|
||||||
|
} else if (book.epubProgress?.percentage && book.epubProgress.percentage > 0) {
|
||||||
|
return this.viewManager.goToFraction(book.epubProgress.percentage / 100);
|
||||||
|
} else {
|
||||||
|
return this.viewManager.goTo(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return of(undefined);
|
||||||
|
})
|
||||||
|
);
|
||||||
}),
|
}),
|
||||||
switchMap(() => this.loadBookFromAPI()),
|
|
||||||
tap(() => this.isLoading.set(false)),
|
tap(() => this.isLoading.set(false)),
|
||||||
catchError(() => {
|
catchError((err) => {
|
||||||
|
console.error('Failed to load ebook', err);
|
||||||
this.isLoading.set(false);
|
this.isLoading.set(false);
|
||||||
|
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load book'});
|
||||||
return of(null);
|
return of(null);
|
||||||
}),
|
}),
|
||||||
takeUntil(this.destroy$)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe();
|
).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,73 +288,6 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
return of(undefined);
|
return of(undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadBookFromAPI(): Observable<void> {
|
|
||||||
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
|
|
||||||
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
|
|
||||||
|
|
||||||
return from(this.bookService.fetchFreshBookDetail(this.bookId, false)).pipe(
|
|
||||||
switchMap((book) => {
|
|
||||||
this.book.set(book);
|
|
||||||
|
|
||||||
// Use alternative bookType from query param if provided, otherwise use primary
|
|
||||||
const bookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType;
|
|
||||||
if (!bookType) {
|
|
||||||
return throwError(() => new Error('Book type not found'));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine which file ID to use for progress tracking
|
|
||||||
let bookFileId: number | undefined;
|
|
||||||
if (this.altBookType) {
|
|
||||||
// Look for the alternative format file with matching type
|
|
||||||
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
|
|
||||||
bookFileId = altFile?.id;
|
|
||||||
} else {
|
|
||||||
// Use the primary file
|
|
||||||
bookFileId = book.primaryFile?.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.stateService.initializeState(this.bookId, bookFileId!).pipe(
|
|
||||||
map(() => ({book, bookType, bookFileId}))
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
switchMap(({book, bookType, bookFileId}) => {
|
|
||||||
this.progressService.initialize(this.bookId, bookType, bookFileId);
|
|
||||||
this.selectionService.initialize(this.bookId, this.destroy$);
|
|
||||||
this.headerService.initialize(this.bookId, book.metadata?.title || '');
|
|
||||||
|
|
||||||
// Use streaming for EPUB if query param is set, blob loading otherwise (default)
|
|
||||||
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
|
|
||||||
const loadBook$ = bookType === 'EPUB' && useStreaming
|
|
||||||
? this.viewManager.loadEpubStreaming(this.bookId, this.altBookType)
|
|
||||||
: this.loadBookBlob();
|
|
||||||
|
|
||||||
return loadBook$.pipe(
|
|
||||||
tap(() => {
|
|
||||||
this.applyStyles();
|
|
||||||
this.sidebarService.initialize(this.bookId, book, this.destroy$);
|
|
||||||
this.leftSidebarService.initialize(this.bookId, this.destroy$);
|
|
||||||
this.noteService.initialize(this.bookId, this.destroy$);
|
|
||||||
}),
|
|
||||||
switchMap(() => this.viewManager.getMetadata()),
|
|
||||||
switchMap(() => {
|
|
||||||
if (!this.hasLoadedOnce) {
|
|
||||||
this.hasLoadedOnce = true;
|
|
||||||
// Navigate to saved position if progress exists, otherwise go to first page
|
|
||||||
if (book.epubProgress?.cfi) {
|
|
||||||
return this.viewManager.goTo(book.epubProgress.cfi);
|
|
||||||
} else if (book.epubProgress?.percentage && book.epubProgress.percentage > 0) {
|
|
||||||
return this.viewManager.goToFraction(book.epubProgress.percentage / 100);
|
|
||||||
} else {
|
|
||||||
return this.viewManager.goTo(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return of(undefined);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private loadBookBlob(): Observable<void> {
|
private loadBookBlob(): Observable<void> {
|
||||||
return this.bookFileService.getFileContent(this.bookId, this.altBookType).pipe(
|
return this.bookFileService.getFileContent(this.bookId, this.altBookType).pipe(
|
||||||
switchMap(fileBlob => {
|
switchMap(fileBlob => {
|
||||||
@@ -304,8 +300,8 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
|
|
||||||
private subscribeToViewEvents(): void {
|
private subscribeToViewEvents(): void {
|
||||||
this.viewManager.events$
|
this.viewManager.events$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(event => {
|
.subscribe((event: ViewEvent) => {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case 'load':
|
case 'load':
|
||||||
this.applyStyles();
|
this.applyStyles();
|
||||||
@@ -430,7 +426,7 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
onProgressChange(fraction: number): void {
|
onProgressChange(fraction: number): void {
|
||||||
this.viewManager.goToFraction(fraction)
|
this.viewManager.goToFraction(fraction)
|
||||||
.pipe(
|
.pipe(
|
||||||
takeUntil(this.destroy$),
|
takeUntilDestroyed(this.destroyRef),
|
||||||
catchError(() => of(undefined))
|
catchError(() => of(undefined))
|
||||||
)
|
)
|
||||||
.subscribe();
|
.subscribe();
|
||||||
@@ -486,7 +482,7 @@ export class EbookReaderComponent implements OnInit {
|
|||||||
if (linkUrl) {
|
if (linkUrl) {
|
||||||
this.viewManager.goTo(linkUrl)
|
this.viewManager.goTo(linkUrl)
|
||||||
.pipe(
|
.pipe(
|
||||||
takeUntil(this.destroy$),
|
takeUntilDestroyed(this.destroyRef),
|
||||||
catchError(() => of(undefined))
|
catchError(() => of(undefined))
|
||||||
)
|
)
|
||||||
.subscribe();
|
.subscribe();
|
||||||
|
|||||||
@@ -53,10 +53,8 @@ describe('ReaderNoteService', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let service: ReaderNoteService;
|
let service: ReaderNoteService;
|
||||||
let destroy$: Subject<void>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
destroy$ = new Subject<void>();
|
|
||||||
bookNoteV2Service.createNote.mockReset();
|
bookNoteV2Service.createNote.mockReset();
|
||||||
bookNoteV2Service.updateNote.mockReset();
|
bookNoteV2Service.updateNote.mockReset();
|
||||||
messageService.add.mockReset();
|
messageService.add.mockReset();
|
||||||
@@ -80,12 +78,10 @@ describe('ReaderNoteService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(ReaderNoteService);
|
service = TestBed.inject(ReaderNoteService);
|
||||||
service.initialize(14, destroy$);
|
service.initialize(14);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
destroy$.next();
|
|
||||||
destroy$.complete();
|
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import {inject, Injectable, signal} from '@angular/core';
|
import {DestroyRef, inject, Injectable, signal} from '@angular/core';
|
||||||
import {Subject} from 'rxjs';
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {takeUntil} from 'rxjs/operators';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {BookNoteV2Service, CreateBookNoteV2Request, UpdateBookNoteV2Request} from '../../../../../shared/service/book-note-v2.service';
|
import {BookNoteV2Service, CreateBookNoteV2Request, UpdateBookNoteV2Request} from '../../../../../shared/service/book-note-v2.service';
|
||||||
@@ -25,8 +24,8 @@ export class ReaderNoteService {
|
|||||||
private leftSidebarService = inject(ReaderLeftSidebarService);
|
private leftSidebarService = inject(ReaderLeftSidebarService);
|
||||||
private viewManager = inject(ReaderViewManagerService);
|
private viewManager = inject(ReaderViewManagerService);
|
||||||
|
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private bookId!: number;
|
private bookId!: number;
|
||||||
private destroy$ = new Subject<void>();
|
|
||||||
|
|
||||||
private readonly _dialogState = signal<NoteDialogState>({
|
private readonly _dialogState = signal<NoteDialogState>({
|
||||||
visible: false,
|
visible: false,
|
||||||
@@ -34,12 +33,11 @@ export class ReaderNoteService {
|
|||||||
});
|
});
|
||||||
readonly dialogState = this._dialogState.asReadonly();
|
readonly dialogState = this._dialogState.asReadonly();
|
||||||
|
|
||||||
initialize(bookId: number, destroy$: Subject<void>): void {
|
initialize(bookId: number): void {
|
||||||
this.bookId = bookId;
|
this.bookId = bookId;
|
||||||
this.destroy$ = destroy$;
|
|
||||||
|
|
||||||
this.leftSidebarService.editNote$
|
this.leftSidebarService.editNote$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(note => {
|
.subscribe(note => {
|
||||||
this.openEditDialog({
|
this.openEditDialog({
|
||||||
cfi: note.cfi,
|
cfi: note.cfi,
|
||||||
@@ -96,7 +94,7 @@ export class ReaderNoteService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.bookNoteV2Service.createNote(createRequest)
|
this.bookNoteV2Service.createNote(createRequest)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
this.closeDialog();
|
this.closeDialog();
|
||||||
@@ -125,7 +123,7 @@ export class ReaderNoteService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.bookNoteV2Service.updateNote(noteId, updateRequest)
|
this.bookNoteV2Service.updateNote(noteId, updateRequest)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: () => {
|
next: () => {
|
||||||
this.closeDialog();
|
this.closeDialog();
|
||||||
|
|||||||
+2
-3
@@ -1,5 +1,5 @@
|
|||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {of, Subject} from 'rxjs';
|
import {of} from 'rxjs';
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
import {Annotation} from '../../../../../shared/service/annotation.service';
|
import {Annotation} from '../../../../../shared/service/annotation.service';
|
||||||
@@ -9,7 +9,6 @@ import {ReaderViewManagerService} from '../../core/view-manager.service';
|
|||||||
import {ReaderSelectionService} from './selection.service';
|
import {ReaderSelectionService} from './selection.service';
|
||||||
|
|
||||||
describe('ReaderSelectionService', () => {
|
describe('ReaderSelectionService', () => {
|
||||||
const destroy$ = new Subject<void>();
|
|
||||||
|
|
||||||
const viewManager = {
|
const viewManager = {
|
||||||
addAnnotation: vi.fn(() => of({index: 1, label: 'Annotation 1'})),
|
addAnnotation: vi.fn(() => of({index: 1, label: 'Annotation 1'})),
|
||||||
@@ -49,7 +48,7 @@ describe('ReaderSelectionService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(ReaderSelectionService);
|
service = TestBed.inject(ReaderSelectionService);
|
||||||
service.initialize(41, destroy$);
|
service.initialize(41);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
|||||||
+11
-11
@@ -1,6 +1,7 @@
|
|||||||
import {inject, Injectable, signal} from '@angular/core';
|
import {DestroyRef, inject, Injectable, signal} from '@angular/core';
|
||||||
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {switchMap, takeUntil, tap} from 'rxjs/operators';
|
import {switchMap, tap} from 'rxjs/operators';
|
||||||
import {of} from 'rxjs';
|
import {of} from 'rxjs';
|
||||||
import {Annotation} from '../../../../../shared/service/annotation.service';
|
import {Annotation} from '../../../../../shared/service/annotation.service';
|
||||||
import {ReaderViewManagerService} from '../../core/view-manager.service';
|
import {ReaderViewManagerService} from '../../core/view-manager.service';
|
||||||
@@ -31,10 +32,10 @@ export class ReaderSelectionService {
|
|||||||
private annotationService = inject(ReaderAnnotationHttpService);
|
private annotationService = inject(ReaderAnnotationHttpService);
|
||||||
private leftSidebarService = inject(ReaderLeftSidebarService);
|
private leftSidebarService = inject(ReaderLeftSidebarService);
|
||||||
|
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private bookId!: number;
|
private bookId!: number;
|
||||||
private annotations: Annotation[] = [];
|
private annotations: Annotation[] = [];
|
||||||
private currentSelection: SelectionDetail | null = null;
|
private currentSelection: SelectionDetail | null = null;
|
||||||
private destroy$ = new Subject<void>();
|
|
||||||
|
|
||||||
private _visible = false;
|
private _visible = false;
|
||||||
private _position = { x: 0, y: 0 };
|
private _position = { x: 0, y: 0 };
|
||||||
@@ -60,9 +61,8 @@ export class ReaderSelectionService {
|
|||||||
private annotationsChangedSubject = new Subject<Annotation[]>();
|
private annotationsChangedSubject = new Subject<Annotation[]>();
|
||||||
public annotationsChanged$ = this.annotationsChangedSubject.asObservable();
|
public annotationsChanged$ = this.annotationsChangedSubject.asObservable();
|
||||||
|
|
||||||
initialize(bookId: number, destroy$: Subject<void>): void {
|
initialize(bookId: number): void {
|
||||||
this.bookId = bookId;
|
this.bookId = bookId;
|
||||||
this.destroy$ = destroy$;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setAnnotations(annotations: Annotation[]): void {
|
setAnnotations(annotations: Annotation[]): void {
|
||||||
@@ -137,7 +137,7 @@ export class ReaderSelectionService {
|
|||||||
private updatePreview(cfi: string, color: string, style: AnnotationStyle): void {
|
private updatePreview(cfi: string, color: string, style: AnnotationStyle): void {
|
||||||
if (this.previewCfi) {
|
if (this.previewCfi) {
|
||||||
this.viewManager.deleteAnnotation(this.previewCfi)
|
this.viewManager.deleteAnnotation(this.previewCfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe();
|
.subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,13 +149,13 @@ export class ReaderSelectionService {
|
|||||||
value: cfi,
|
value: cfi,
|
||||||
color: color,
|
color: color,
|
||||||
style: style
|
style: style
|
||||||
}).pipe(takeUntil(this.destroy$)).subscribe();
|
}).pipe(takeUntilDestroyed(this.destroyRef)).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
private clearPreview(): void {
|
private clearPreview(): void {
|
||||||
if (this.previewCfi) {
|
if (this.previewCfi) {
|
||||||
this.viewManager.deleteAnnotation(this.previewCfi)
|
this.viewManager.deleteAnnotation(this.previewCfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe();
|
.subscribe();
|
||||||
this.previewCfi = null;
|
this.previewCfi = null;
|
||||||
this.previewColor = null;
|
this.previewColor = null;
|
||||||
@@ -185,7 +185,7 @@ export class ReaderSelectionService {
|
|||||||
tap(() => this.viewManager.clearSelection())
|
tap(() => this.viewManager.clearSelection())
|
||||||
);
|
);
|
||||||
}),
|
}),
|
||||||
takeUntil(this.destroy$)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
).subscribe();
|
).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,11 +194,11 @@ export class ReaderSelectionService {
|
|||||||
if (!annotation) return;
|
if (!annotation) return;
|
||||||
|
|
||||||
this.annotationService.deleteAnnotation(annotationId)
|
this.annotationService.deleteAnnotation(annotationId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(success => {
|
.subscribe(success => {
|
||||||
if (success) {
|
if (success) {
|
||||||
this.viewManager.deleteAnnotation(annotation.cfi)
|
this.viewManager.deleteAnnotation(annotation.cfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe();
|
.subscribe();
|
||||||
this.annotations = this.annotations.filter(a => a.id !== annotationId);
|
this.annotations = this.annotations.filter(a => a.id !== annotationId);
|
||||||
this.annotationsChangedSubject.next(this.annotations);
|
this.annotationsChangedSubject.next(this.annotations);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {of, Subject} from 'rxjs';
|
import {of} from 'rxjs';
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service';
|
import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service';
|
||||||
@@ -8,7 +8,6 @@ import {ReaderLeftSidebarService} from './panel.service';
|
|||||||
|
|
||||||
describe('ReaderLeftSidebarService', () => {
|
describe('ReaderLeftSidebarService', () => {
|
||||||
let service: ReaderLeftSidebarService;
|
let service: ReaderLeftSidebarService;
|
||||||
let destroy$: Subject<void>;
|
|
||||||
|
|
||||||
const notes = [
|
const notes = [
|
||||||
{id: 1, bookId: 9, cfi: 'epubcfi(/6/2)', noteContent: 'Alpha', selectedText: 'Quote', chapterTitle: 'Intro', createdAt: '2026-03-26T00:00:00Z'},
|
{id: 1, bookId: 9, cfi: 'epubcfi(/6/2)', noteContent: 'Alpha', selectedText: 'Quote', chapterTitle: 'Intro', createdAt: '2026-03-26T00:00:00Z'},
|
||||||
@@ -41,7 +40,6 @@ describe('ReaderLeftSidebarService', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
destroy$ = new Subject<void>();
|
|
||||||
bookNoteV2Service.getNotesForBook.mockReset();
|
bookNoteV2Service.getNotesForBook.mockReset();
|
||||||
bookNoteV2Service.getNotesForBook.mockReturnValue(of(notes));
|
bookNoteV2Service.getNotesForBook.mockReturnValue(of(notes));
|
||||||
bookNoteV2Service.deleteNote.mockReset();
|
bookNoteV2Service.deleteNote.mockReset();
|
||||||
@@ -61,13 +59,11 @@ describe('ReaderLeftSidebarService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(ReaderLeftSidebarService);
|
service = TestBed.inject(ReaderLeftSidebarService);
|
||||||
service.initialize(9, destroy$);
|
service.initialize(9);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
destroy$.next();
|
|
||||||
destroy$.complete();
|
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
import {computed, DestroyRef, inject, Injectable, signal} from '@angular/core';
|
||||||
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {takeUntil} from 'rxjs/operators';
|
|
||||||
import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service';
|
import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service';
|
||||||
import {ReaderViewManagerService} from '../../core/view-manager.service';
|
import {ReaderViewManagerService} from '../../core/view-manager.service';
|
||||||
import {SearchResult, SearchState} from '../sidebar/sidebar.service';
|
import {SearchResult, SearchState} from '../sidebar/sidebar.service';
|
||||||
@@ -17,7 +17,7 @@ export class ReaderLeftSidebarService {
|
|||||||
private viewManager = inject(ReaderViewManagerService);
|
private viewManager = inject(ReaderViewManagerService);
|
||||||
private bookNoteV2Service = inject(BookNoteV2Service);
|
private bookNoteV2Service = inject(BookNoteV2Service);
|
||||||
|
|
||||||
private destroy$ = new Subject<void>();
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private bookId!: number;
|
private bookId!: number;
|
||||||
|
|
||||||
private readonly _isOpen = signal(false);
|
private readonly _isOpen = signal(false);
|
||||||
@@ -58,16 +58,15 @@ export class ReaderLeftSidebarService {
|
|||||||
private _editNote = new Subject<BookNoteV2>();
|
private _editNote = new Subject<BookNoteV2>();
|
||||||
editNote$ = this._editNote.asObservable();
|
editNote$ = this._editNote.asObservable();
|
||||||
|
|
||||||
initialize(bookId: number, destroy$: Subject<void>): void {
|
initialize(bookId: number): void {
|
||||||
this.bookId = bookId;
|
this.bookId = bookId;
|
||||||
this.destroy$ = destroy$;
|
|
||||||
|
|
||||||
this.loadNotes();
|
this.loadNotes();
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadNotes(): void {
|
private loadNotes(): void {
|
||||||
this.bookNoteV2Service.getNotesForBook(this.bookId)
|
this.bookNoteV2Service.getNotesForBook(this.bookId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(notes => this._notes.set(notes));
|
.subscribe(notes => this._notes.set(notes));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,13 +105,13 @@ export class ReaderLeftSidebarService {
|
|||||||
|
|
||||||
navigateToNote(cfi: string): void {
|
navigateToNote(cfi: string): void {
|
||||||
this.viewManager.goTo(cfi)
|
this.viewManager.goTo(cfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.close());
|
.subscribe(() => this.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteNote(noteId: number): void {
|
deleteNote(noteId: number): void {
|
||||||
this.bookNoteV2Service.deleteNote(noteId)
|
this.bookNoteV2Service.deleteNote(noteId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
this._notes.update(notes => notes.filter(note => note.id !== noteId));
|
this._notes.update(notes => notes.filter(note => note.id !== noteId));
|
||||||
});
|
});
|
||||||
@@ -204,7 +203,7 @@ export class ReaderLeftSidebarService {
|
|||||||
|
|
||||||
navigateToSearchResult(cfi: string): void {
|
navigateToSearchResult(cfi: string): void {
|
||||||
this.viewManager.goTo(cfi)
|
this.viewManager.goTo(cfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.close());
|
.subscribe(() => this.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -14,7 +14,6 @@ import {Book} from '../../../../book/model/book.model';
|
|||||||
import {ReaderSidebarService} from './sidebar.service';
|
import {ReaderSidebarService} from './sidebar.service';
|
||||||
|
|
||||||
describe('ReaderSidebarService', () => {
|
describe('ReaderSidebarService', () => {
|
||||||
const destroy$ = new Subject<void>();
|
|
||||||
|
|
||||||
const selectionAnnotations$ = new Subject<{id: number; cfi: string}[]>();
|
const selectionAnnotations$ = new Subject<{id: number; cfi: string}[]>();
|
||||||
const selectionService = {
|
const selectionService = {
|
||||||
@@ -133,7 +132,7 @@ describe('ReaderSidebarService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(ReaderSidebarService);
|
service = TestBed.inject(ReaderSidebarService);
|
||||||
service.initialize(7, book, destroy$);
|
service.initialize(7, book);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {inject, Injectable, Injector, signal} from '@angular/core';
|
import {DestroyRef, inject, Injectable, Injector, signal} from '@angular/core';
|
||||||
|
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||||
import {Subject} from 'rxjs';
|
import {Subject} from 'rxjs';
|
||||||
import {takeUntil} from 'rxjs/operators';
|
|
||||||
import {TocItem} from 'epubjs';
|
import {TocItem} from 'epubjs';
|
||||||
import {BookMark, BookMarkService} from '../../../../../shared/service/book-mark.service';
|
import {BookMark, BookMarkService} from '../../../../../shared/service/book-mark.service';
|
||||||
import {Annotation} from '../../../../../shared/service/annotation.service';
|
import {Annotation} from '../../../../../shared/service/annotation.service';
|
||||||
@@ -48,7 +48,7 @@ export class ReaderSidebarService {
|
|||||||
private bookMarkHttpService = inject(BookMarkService);
|
private bookMarkHttpService = inject(BookMarkService);
|
||||||
private annotationService = inject(ReaderAnnotationHttpService);
|
private annotationService = inject(ReaderAnnotationHttpService);
|
||||||
|
|
||||||
private destroy$ = new Subject<void>();
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
private bookId!: number;
|
private bookId!: number;
|
||||||
private selectionService: ReaderSelectionService | null = null;
|
private selectionService: ReaderSelectionService | null = null;
|
||||||
|
|
||||||
@@ -84,9 +84,8 @@ export class ReaderSidebarService {
|
|||||||
return this.progressService.currentChapterHref;
|
return this.progressService.currentChapterHref;
|
||||||
}
|
}
|
||||||
|
|
||||||
initialize(bookId: number, book: Book, destroy$: Subject<void>): void {
|
initialize(bookId: number, book: Book): void {
|
||||||
this.bookId = bookId;
|
this.bookId = bookId;
|
||||||
this.destroy$ = destroy$;
|
|
||||||
|
|
||||||
this._bookInfo.set({
|
this._bookInfo.set({
|
||||||
id: book.id,
|
id: book.id,
|
||||||
@@ -110,7 +109,7 @@ export class ReaderSidebarService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.selectionService.annotationsChanged$
|
this.selectionService.annotationsChanged$
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(annotations => {
|
.subscribe(annotations => {
|
||||||
this._annotations.set(annotations);
|
this._annotations.set(annotations);
|
||||||
});
|
});
|
||||||
@@ -118,7 +117,7 @@ export class ReaderSidebarService {
|
|||||||
|
|
||||||
private loadAnnotations(): void {
|
private loadAnnotations(): void {
|
||||||
this.annotationService.getAnnotations(this.bookId)
|
this.annotationService.getAnnotations(this.bookId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(annotations => {
|
.subscribe(annotations => {
|
||||||
this._annotations.set(annotations);
|
this._annotations.set(annotations);
|
||||||
if (!this.selectionService) {
|
if (!this.selectionService) {
|
||||||
@@ -166,7 +165,7 @@ export class ReaderSidebarService {
|
|||||||
|
|
||||||
navigateToChapter(href: string): void {
|
navigateToChapter(href: string): void {
|
||||||
this.viewManager.goTo(href)
|
this.viewManager.goTo(href)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.close());
|
.subscribe(() => this.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,19 +222,19 @@ export class ReaderSidebarService {
|
|||||||
|
|
||||||
private loadBookmarks(): void {
|
private loadBookmarks(): void {
|
||||||
this.bookMarkHttpService.getBookmarksForBook(this.bookId)
|
this.bookMarkHttpService.getBookmarksForBook(this.bookId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(bookmarks => this._bookmarks.set(bookmarks));
|
.subscribe(bookmarks => this._bookmarks.set(bookmarks));
|
||||||
}
|
}
|
||||||
|
|
||||||
navigateToBookmark(cfi: string): void {
|
navigateToBookmark(cfi: string): void {
|
||||||
this.viewManager.goTo(cfi)
|
this.viewManager.goTo(cfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.close());
|
.subscribe(() => this.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
createBookmark(): void {
|
createBookmark(): void {
|
||||||
this.bookmarkService.createBookmarkAtCurrentPosition(this.bookId)
|
this.bookmarkService.createBookmarkAtCurrentPosition(this.bookId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(success => {
|
.subscribe(success => {
|
||||||
if (success) {
|
if (success) {
|
||||||
this.loadBookmarks();
|
this.loadBookmarks();
|
||||||
@@ -257,13 +256,13 @@ export class ReaderSidebarService {
|
|||||||
|
|
||||||
deleteBookmark(bookmarkId: number): void {
|
deleteBookmark(bookmarkId: number): void {
|
||||||
this.bookMarkHttpService.deleteBookmark(bookmarkId)
|
this.bookMarkHttpService.deleteBookmark(bookmarkId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.loadBookmarks());
|
.subscribe(() => this.loadBookmarks());
|
||||||
}
|
}
|
||||||
|
|
||||||
navigateToAnnotation(cfi: string): void {
|
navigateToAnnotation(cfi: string): void {
|
||||||
this.viewManager.goTo(cfi)
|
this.viewManager.goTo(cfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(() => this.close());
|
.subscribe(() => this.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,11 +272,11 @@ export class ReaderSidebarService {
|
|||||||
if (!annotation) return;
|
if (!annotation) return;
|
||||||
|
|
||||||
this.annotationService.deleteAnnotation(annotationId)
|
this.annotationService.deleteAnnotation(annotationId)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe(success => {
|
.subscribe(success => {
|
||||||
if (success) {
|
if (success) {
|
||||||
this.viewManager.deleteAnnotation(annotation.cfi)
|
this.viewManager.deleteAnnotation(annotation.cfi)
|
||||||
.pipe(takeUntil(this.destroy$))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe();
|
.subscribe();
|
||||||
const updatedAnnotations = annotations.filter(a => a.id !== annotationId);
|
const updatedAnnotations = annotations.filter(a => a.id !== annotationId);
|
||||||
this._annotations.set(updatedAnnotations);
|
this._annotations.set(updatedAnnotations);
|
||||||
|
|||||||
Reference in New Issue
Block a user