refactor(ebook-reader): optimize destruction handling and improve reactive subscriptions (#478)

This commit is contained in:
brios
2026-04-22 17:27:38 -04:00
committed by Zach Yale
parent e26df36a33
commit 1f5f99d958
26 changed files with 1112 additions and 1068 deletions
@@ -8,7 +8,7 @@
<div class="entity-info">
<p class="entity-title">
@if (entityType === EntityType.ALL_BOOKS) {
@if (currentFilterLabel() && rawFilterParamFromUrl) {
@if (currentFilterLabel() && rawFilterParamFromUrl()) {
{{ currentFilterLabel() }}
} @else if (isFilterActive() || hasSearchTerm()) {
{{ computedFilterLabel() }}
@@ -70,7 +70,7 @@
<p-multiSelect
optionLabel="header"
[options]="columnPreferenceService.allColumns"
[(ngModel)]="visibleColumns"
[ngModel]="visibleColumns()"
(ngModelChange)="onVisibleColumnsChange($event)"
display="chip"
[placeholder]="t('placeholder.selectColumns')"
@@ -85,14 +85,14 @@
[label]="t('labels.save')"
outlined
size="small"
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns)"></p-button>
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns())"></p-button>
</div>
</p-popover>
</div>
}
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<i
[ngClass]="viewIcon()"
[class]="viewIcon()"
[pTooltip]="t('tooltip.toggleView')"
tooltipPosition="top">
</i>
@@ -180,14 +180,14 @@
[pTooltip]="t('tooltip.selectSorting')"
tooltipPosition="top">
</i>
@if (sortCriteriaCount > 1) {
<p-badge [value]="sortCriteriaCount.toString()" class="sort-badge"/>
@if (sortCriteriaCount() > 1) {
<p-badge [value]="sortCriteriaCount().toString()" class="sort-badge"/>
}
</a>
<p-popover #sortPopover [dismissable]="true" appendTo="body">
<app-multi-sort-popover
[sortCriteria]="this.bookSorter.selectedSortCriteria"
[availableSortOptions]="visibleSortOptions"
[availableSortOptions]="visibleSortOptions()"
[showSaveButton]="canSaveSort()"
(criteriaChange)="onSortCriteriaChange($event)"
(saveSortConfig)="onSaveSortConfig($event)">
@@ -215,7 +215,7 @@
type="text"
pInputText
[placeholder]="t('placeholder.search')"
[(ngModel)]="bookTitle"
[ngModel]="bookTitle()"
(ngModelChange)="onSearchTermChange($event)"
class="search-input-full"
/>
@@ -237,11 +237,11 @@
type="text"
pInputText
[placeholder]="t('placeholder.search')"
[(ngModel)]="bookTitle"
[ngModel]="bookTitle()"
(ngModelChange)="onSearchTermChange($event)"
class="search-input"
/>
@if (bookTitle) {
@if (bookTitle()) {
<p-button
icon="pi pi-times"
[text]="true"
@@ -314,7 +314,7 @@
[preselectedBookIds]="selectedBooks()"
(selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="this.bookSorter.selectedSort!"
[visibleColumns]="visibleColumns"
[visibleColumns]="visibleColumns()"
></app-book-table>
}
@if (currentViewMode() === 'grid') {
@@ -330,7 +330,7 @@
[index]="i"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled"
[seriesViewEnabled]="seriesViewEnabled()"
[onBookSelect]="onBookCardSelect"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
@@ -358,7 +358,7 @@
<div class="footer-center">
@if (entityType(); as entityType) {
<div class="action-buttons-group">
@if (hasMetadataMenuItems) {
@if (hasMetadataMenuItems()) {
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
<p-button
(click)="menu.toggle($event)"
@@ -418,7 +418,7 @@
tooltipPosition="top">
</p-button>
}
@if (hasMoreActionsItems) {
@if (hasMoreActionsItems()) {
<div class="more-actions-wrapper">
<p-button
(click)="menu.toggle($event)"
@@ -10,7 +10,7 @@ import {BookService} from '../../service/book.service';
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
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 {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {CoverScalePreferenceService} from './cover-scale-preference.service';
@@ -112,6 +112,8 @@ interface BookBrowserHarness {
updateFilters: ReturnType<typeof vi.fn>;
updateFilterMode: ReturnType<typeof vi.fn>;
updateMultiSort: ReturnType<typeof vi.fn>;
parseQueryParams: ReturnType<typeof vi.fn>;
syncQueryParams: ReturnType<typeof vi.fn>;
};
routeSnapshot: {
routeConfig: {path: string};
@@ -129,8 +131,8 @@ function createHarness(options?: {
}): BookBrowserHarness {
const books = signal<Book[]>(
options?.books ?? [
makeBook(1, 1, 'Alpha', '2024-01-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'),
]
);
@@ -143,7 +145,17 @@ function createHarness(options?: {
const paramMap$ = new BehaviorSubject(convertToParamMap({libraryId: '1'}));
const queryParamMap$ = new BehaviorSubject(convertToParamMap({}));
const url$ = new BehaviorSubject<unknown[]>([]);
const defaultSort: SortOption = {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'};
const queryParamsService = {
parseQueryParams: vi.fn((_q, _u, _et, _ei, _sortOptions, defaultFilterMode) => ({
viewMode: VIEW_MODES.GRID,
sortOption: defaultSort,
sortCriteria: [defaultSort],
filters: {},
filterMode: defaultFilterMode,
viewModeFromToggle: false,
})),
syncQueryParams: vi.fn(),
shouldForceExpandSeries: vi.fn(() => false),
updateViewMode: vi.fn(),
updateFilters: vi.fn(),
@@ -157,6 +169,7 @@ function createHarness(options?: {
params: {libraryId: '1'},
};
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
SortService,
@@ -206,6 +219,35 @@ function createHarness(options?: {
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: TaskHelperService, useValue: {}},
{
@@ -255,12 +297,14 @@ function createHarness(options?: {
if (f.libraryId) result = result.filter(b => b.libraryId === f.libraryId);
const s = _sort();
const dir = s.dir === 'asc' ? 1 : -1;
result = [...result].sort((a, b) => {
if (s.field === 'title') return dir * ((a.metadata?.title ?? '') as string).localeCompare((b.metadata?.title ?? '') as string);
if (s.field === 'addedOn') return dir * (a.addedOn ?? '').localeCompare(b.addedOn ?? '');
return 0;
const aVal = s.field === 'title' ? (a.metadata?.title ?? '') : (a.addedOn ?? '');
const bVal = s.field === 'title' ? (b.metadata?.title ?? '') : (b.addedOn ?? '');
return String(aVal).localeCompare(String(bVal));
});
if (s.dir === 'desc') {
result.reverse();
}
return result;
});
@@ -384,7 +428,7 @@ describe('BookBrowserComponent', () => {
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);
});
@@ -404,7 +448,7 @@ describe('BookBrowserComponent', () => {
TestBed.flushEffects();
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);
});
@@ -420,12 +464,12 @@ describe('BookBrowserComponent', () => {
TestBed.flushEffects();
expect(component.books()).toBeUndefined();
expect(component.hasRenderedBooks()).toBe(false);
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(false);
vi.runOnlyPendingTimers();
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', () => {
@@ -434,9 +478,14 @@ describe('BookBrowserComponent', () => {
isBooksLoading: true,
});
expect(component.showBooksLoadingPlaceholder()).toBe(false);
expect(component.showGridLoadingPlaceholder()).toBe(false);
expect(component.showTableLoadingPlaceholder()).toBe(false);
const comp = component as unknown as {
showBooksLoadingPlaceholder: () => boolean;
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', () => {
@@ -473,7 +522,6 @@ describe('BookBrowserComponent', () => {
removeEventListener: vi.fn(),
} as unknown as HTMLElement;
component.currentViewMode.set(VIEW_MODES.GRID);
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
// 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 {ActivatedRoute, NavigationStart, Router} from '@angular/router';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
@@ -79,7 +79,7 @@ export enum EntityType {
],
providers: [SeriesCollapseFilter],
})
export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
export class BookBrowserComponent implements AfterViewInit {
protected userService = inject(UserService);
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
@@ -112,6 +112,21 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private readonly t = inject(TranslocoService);
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[] = [{
field: 'addedOn',
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 selectedFilterMode = signal<BookFilterMode>('and');
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;
readonly selectedBooks = this.bookSelectionService.selectedBooks;
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 tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
parsedFilters: Record<string, string[]> = {};
bookTitle = '';
dynamicDialogRef: DynamicDialogRef | undefined | null;
EntityType = EntityType;
private readonly activeLang = toSignal(this.t.langChanges$, {
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})
: filterSummary;
});
readonly currentFilterLabel = computed(() => this.computedFilterLabel());
rawFilterParamFromUrl: string | null = null;
visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode = signal<string | undefined>(undefined);
lastAppliedSortCriteria: SortOption[] = [];
visibleSortOptions: SortOption[] = [];
screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
mobileColumnCount = signal(3);
private readonly MOBILE_BREAKPOINT = 768;
private readonly CARD_ASPECT_RATIO = 7 / 5;
@@ -576,7 +589,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
readonly showBooksLoadingPlaceholder = computed(() =>
!this.booksError() && !this.hasRenderedBooks()
!this.booksError() && (this.isBooksLoading() || !this.hasRenderedBooks())
);
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';
});
get seriesViewEnabled(): boolean {
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
}
readonly seriesViewEnabled = computed(() => Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView));
get hasMetadataMenuItems(): boolean {
return (this.metadataMenuItems?.length ?? 0) > 0;
}
readonly hasMetadataMenuItems = computed(() => (this.metadataMenuItems?.length ?? 0) > 0);
get hasMoreActionsItems(): boolean {
return (this.moreActionsMenuItems?.length ?? 0) > 0;
}
readonly hasMoreActionsItems = computed(() => (this.moreActionsMenuItems?.length ?? 0) > 0);
ngOnInit(): void {
this.loadMobileColumnsPreference();
this.setupRouteChangeHandlers();
this.setupQueryParamSubscription();
this.setupScrollPositionTracking();
}
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);
readonly sortCriteriaCount = computed(() => this.bookSorter.selectedSortCriteria.length);
ngAfterViewInit(): void {
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 => {
this.checkAndFetchIfNeeded();
};
@@ -687,7 +692,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private setupRouteChangeHandlers(): void {
this.activatedRoute.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
this.searchTerm.set('');
this.bookTitle = '';
this.bookTitle.set('');
this.bookSelectionService.deselectAll();
this.clearFilter();
this.scrollToTop();
@@ -750,14 +755,18 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.selectedFilter.set(parseResult.filters);
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;
} else {
this.clearFilter();
this.rawFilterParamFromUrl = null;
this.rawFilterParamFromUrl.set(null);
}
this.parsedFilters = parseResult.filters;
@@ -765,11 +774,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
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 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)) {
@@ -777,10 +786,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
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(
@@ -804,8 +810,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
: null;
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);
}
@@ -822,9 +830,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
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)
);
));
}
onCheckboxClicked(event: CheckboxClickEvent): void {
@@ -913,17 +921,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
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 {
const entityType = this.entityType();
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 {
this.searchTerm.set(term);
}
clearSearch(): void {
this.bookTitle = '';
this.bookTitle.set('');
this.onSearchTermChange('');
this.resetFilters();
}
@@ -31,6 +31,7 @@ import {BookCardOverlayPreferenceService} from '../book-browser/book-card-overla
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {injectQuery} from '@tanstack/angular-query-experimental';
import {AuthorService} from '../../../author-browser/service/author.service';
interface ReadStatusSegment {
status: ReadStatus;
@@ -110,6 +111,7 @@ export class SeriesPageComponent implements AfterViewChecked {
protected appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
protected urlHelper = inject(UrlHelperService);
private authorService = inject(AuthorService);
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
tab: string = "view";
@@ -368,7 +370,14 @@ export class SeriesPageComponent implements AfterViewChecked {
}
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 {