fix(dashboard): improve performance with OnPush change detection (#440)

* fix(dashboard): improve performance with OnPush change detection

* fix(dashboard): refactor book card component for improved readability and performance

* fix(tests): mock matchMedia for improved test compatibility

* fix(tests): matchMedia mock for better CI compatibility and support

* fix(dashboard): add clearAll method to BookBrowserScrollService and update tests

* fix(dashboard): improve performance with content visibility and refactor styles

* fix(dashboard): improve scroll performance with estimated total height and refactor layout

* fix(tests): add mock for getCurrentUser in userService for improved test coverage

* fix(dashboard): implement infinite scroll for book loading and scroll restoration

* fix(tests): fix lint error

* fix(tests): mock ResizeObserver and IntersectionObserver

* fix(tests): mock ResizeObserver and IntersectionObserver (again)

* fix(dashboard): improve accessibility and performance by updating aria attributes and optimizing animations

* fix(dashboard): improve submenu accessibility and optimize virtual scroller performance

* fix(dashboard): clean up imports and improve component structure

* fix(dashboard): correct mobile check in author browser component

* fix(dashboard): add OnDestroy lifecycle hook to BookBrowserComponent
This commit is contained in:
brios
2026-04-22 17:27:11 -04:00
committed by Zach Yale
parent a779de8f57
commit 85e8d235b6
140 changed files with 1546 additions and 1233 deletions
@@ -1,11 +1,11 @@
import {AfterViewInit, ChangeDetectionStrategy, Component, HostListener, computed, effect, inject, OnDestroy, OnInit, signal, untracked, ViewChild} from '@angular/core';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, OnDestroy, computed, effect, inject, OnInit, 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';
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {BookService} from '../../service/book.service';
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
import {debounceTime, distinctUntilChanged, filter, map, takeUntil} from 'rxjs/operators';
import {debounceTime, distinctUntilChanged, filter, map, take} from 'rxjs/operators';
import {combineLatest, finalize, Subject} from 'rxjs';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
@@ -13,10 +13,9 @@ import {SortDirection, SortOption} from '../../model/sort.model';
import {Book} from '../../model/book.model';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {BookTableComponent} from './book-table/book-table.component';
import {animate, style, transition, trigger} from '@angular/animations';
import {computeGridColumns} from '../../../../shared/util/viewport.util';
import {Button} from 'primeng/button';
import {NgClass, NgStyle} from '@angular/common';
import {VirtualScrollerComponent, VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
import {BookCardComponent} from './book-card/book-card.component';
import {Menu} from 'primeng/menu';
@@ -36,7 +35,7 @@ import {Divider} from 'primeng/divider';
import {MultiSelect} from 'primeng/multiselect';
import {TableColumnPreferenceService} from './table-column-preference.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {BadgeModule} from 'primeng/badge';
import {Badge} from 'primeng/badge';
import {BookMenuService} from '../../service/book-menu.service';
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
@@ -74,23 +73,11 @@ export enum EntityType {
styleUrls: ['./book-browser.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
Button, VirtualScrollerModule, BookCardComponent, Menu, InputText, FormsModule,
Button, BookCardComponent, Menu, InputText, FormsModule,
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
Checkbox, Slider, Divider, MultiSelect, TieredMenu, BadgeModule, MultiSortPopoverComponent, TranslocoDirective
Checkbox, Slider, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective,
],
providers: [SeriesCollapseFilter],
animations: [
trigger('slideInOut', [
transition(':enter', [
style({transform: 'translateY(100%)'}),
animate('0.1s ease-in', style({transform: 'translateY(0)'}))
]),
transition(':leave', [
style({transform: 'translateY(0)'}),
animate('0.1s ease-out', style({transform: 'translateY(100%)'}))
])
])
]
})
export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
@@ -123,6 +110,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private localStorageService = inject(LocalStorageService);
private scrollService = inject(BookBrowserScrollService);
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
private readonly defaultSortCriteria: SortOption[] = [{
field: 'addedOn',
@@ -294,6 +282,41 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
return map;
});
readonly compareBookItems = (a: Book, b: Book): boolean => a?.id === b?.id;
private readonly GRID_GAP = 21;
private readonly containerWidth = signal(0);
private containerResizeObserver: ResizeObserver | undefined;
readonly gridColumns = computed(() => {
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth, 10) || 180, this.GRID_GAP);
});
/**
* Estimated total content height based on totalElements from the first API page.
* Used as min-height so the scrollbar reflects the full collection from the start.
* Only grows, never shrinks — prevents scroll teleportation.
*/
readonly estimatedTotalHeight = computed(() => {
const total = this.appBooksApi.totalElements();
if (total === 0) return 0;
const cols = this.gridColumns();
const rows = Math.ceil(total / cols);
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
return rows * rowHeight;
});
/**
* Total height of currently loaded books in grid view.
*/
readonly renderedHeight = computed(() => {
const books = this.books();
if (!books || books.length === 0) return 0;
const cols = this.gridColumns();
const rows = Math.ceil(books.length / cols);
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
return rows * rowHeight;
});
protected resetFilterSubject = new Subject<void>();
readonly skeletonSlots = Array.from({length: 24}, (_, index) => index);
@@ -321,7 +344,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private readonly MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
private settingFiltersFromUrl = false;
private destroy$ = new Subject<void>();
protected metadataMenuItems: MenuItem[] | undefined;
protected moreActionsMenuItems: MenuItem[] | undefined;
protected readonly onBookCardSelect = (book: Book, selected: boolean): void => {
@@ -389,12 +411,61 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
);
});
/**
* Triggers sequential page loads if the current scroll position is beyond the loaded content.
* This is critical for scroll restoration on page reload.
*/
private readonly fillScrollGapEffect = effect(() => {
const books = this.books();
if (books && books.length > 0) {
this.checkAndFetchIfNeeded();
}
});
@ViewChild(BookTableComponent)
bookTableComponent!: BookTableComponent;
@ViewChild(BookFilterComponent, {static: false})
bookFilterComponent!: BookFilterComponent;
@ViewChild('scroll')
virtualScroller: VirtualScrollerComponent | undefined;
private scrollContainer: HTMLElement | undefined;
private sentinelObserver: IntersectionObserver | undefined;
@ViewChild('scrollContainer')
set scrollContainerRef(ref: ElementRef<HTMLElement> | undefined) {
this.containerResizeObserver?.disconnect();
if (this.scrollContainer) {
this.scrollContainer.removeEventListener('scroll', this.onScroll);
}
this.scrollContainer = ref?.nativeElement;
if (this.scrollContainer) {
const el = this.scrollContainer;
this.containerWidth.set(el.clientWidth);
this.containerResizeObserver = new ResizeObserver(entries => {
this.containerWidth.set(entries[0]?.contentRect.width ?? el.clientWidth);
});
this.containerResizeObserver.observe(el);
el.addEventListener('scroll', this.onScroll, {passive: true});
// Initial check in case we are already scrolled down
globalThis.requestAnimationFrame(() => this.checkAndFetchIfNeeded());
}
}
@ViewChild('scrollSentinel')
set scrollSentinelRef(ref: ElementRef<HTMLElement> | undefined) {
this.sentinelObserver?.disconnect();
const el = ref?.nativeElement;
if (el) {
this.sentinelObserver = new IntersectionObserver(
entries => {
if (entries[0]?.isIntersecting) {
this.checkAndFetchNextPage();
}
},
{root: this.scrollContainer, rootMargin: '600px'}
);
this.sentinelObserver.observe(el);
}
}
@HostListener('window:resize')
onResize(): void {
@@ -533,8 +604,37 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
if (this.scrollContainer) {
this.scrollContainer.removeEventListener('scroll', this.onScroll);
}
this.containerResizeObserver?.disconnect();
this.sentinelObserver?.disconnect();
}
private onScroll = (): void => {
this.checkAndFetchIfNeeded();
};
/**
* Checks if the current scroll position plus viewport exceeds the rendered height (with a buffer)
* and fetches the next page if necessary.
*/
private checkAndFetchIfNeeded(): void {
if (!this.scrollContainer || this.currentViewMode === VIEW_MODES.TABLE) return;
const {scrollTop, clientHeight} = this.scrollContainer;
const buffer = 1000; // Large buffer to facilitate scroll restoration
const renderedHeight = untracked(() => this.renderedHeight());
if (scrollTop + clientHeight >= renderedHeight - buffer) {
untracked(() => this.checkAndFetchNextPage());
}
}
private checkAndFetchNextPage(): void {
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
this.appBooksApi.fetchNextPage();
}
}
private getScrollPositionKey(): string {
@@ -545,29 +645,38 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private setupScrollPositionTracking(): void {
this.router.events.pipe(
filter(event => event instanceof NavigationStart),
takeUntil(this.destroy$)
takeUntilDestroyed(this.destroyRef)
).subscribe(() => {
this.saveScrollPosition();
});
}
private saveScrollPosition(): void {
if (this.virtualScroller?.viewPortInfo) {
if (this.scrollContainer) {
const key = this.getScrollPositionKey();
const position = this.virtualScroller.viewPortInfo.scrollStartPosition ?? 0;
this.scrollService.savePosition(key, position);
this.scrollService.savePosition(key, this.scrollContainer.scrollTop);
}
}
private setupRouteChangeHandlers(): void {
this.activatedRoute.paramMap.pipe(takeUntil(this.destroy$)).subscribe(() => {
this.activatedRoute.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
this.searchTerm.set('');
this.bookTitle = '';
this.bookSelectionService.deselectAll();
this.clearFilter();
this.scrollToTop();
});
}
private scrollToTop(): void {
if (this.scrollContainer) {
this.scrollContainer.scrollTop = 0;
}
if (this.bookTableComponent) {
this.bookTableComponent.scrollToTop();
}
}
private readonly syncMetadataMenuEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
@@ -589,7 +698,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.activatedRoute.queryParamMap,
this.currentUser$,
]).pipe(
takeUntil(this.destroy$)
takeUntilDestroyed(this.destroyRef)
).subscribe(([entityInfo, queryParamMap, currentUser]) => {
const parseResult = this.queryParamsService.parseQueryParams(
queryParamMap,
@@ -934,8 +1043,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
openShelfAssigner(): void {
this.dynamicDialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(result => {
if (result.assigned) {
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(result => {
if (result?.assigned) {
this.bookSelectionService.deselectAll();
}
});
@@ -945,7 +1054,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
lockUnlockMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(() => {
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(() => {
this.bookSelectionService.deselectAll();
});
}
@@ -967,7 +1076,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
bulkEditMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(() => {
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(() => {
this.bookSelectionService.deselectAll();
});
}
@@ -976,7 +1085,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
multiBookEditMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks());
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(() => {
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(() => {
this.bookSelectionService.deselectAll();
});
}
@@ -1096,7 +1205,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.dynamicDialogRef = this.dialogHelperService.openBulkBookFileAttacherDialog(sourceBooks);
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(result => {
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(result => {
if (result?.success) {
this.bookSelectionService.deselectAll();
}
@@ -1129,10 +1238,4 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.mobileColumnCount = saved;
}
}
onScrollEnd(): void {
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
this.appBooksApi.fetchNextPage();
}
}
}