fix(reader): implement signal-based state management and cleanup in EbookReaderComponent (#435)

This commit is contained in:
brios
2026-04-22 17:27:11 -04:00
committed by Zach Yale
parent 376ac6ff60
commit a779de8f57
3 changed files with 131 additions and 108 deletions
@@ -100,6 +100,7 @@ export class ReaderEventService {
private longHoldTimeout: ReturnType<typeof setTimeout> | null = null; private longHoldTimeout: ReturnType<typeof setTimeout> | null = null;
private keydownHandler?: (event: KeyboardEvent) => void; private keydownHandler?: (event: KeyboardEvent) => void;
private clickedDocs = new WeakSet<Document>(); private clickedDocs = new WeakSet<Document>();
private iframeCleanupFns: (() => void)[] = [];
private touchStartX = 0; private touchStartX = 0;
private touchStartY = 0; private touchStartY = 0;
@@ -120,12 +121,26 @@ export class ReaderEventService {
} }
destroy(): void { destroy(): void {
window.removeEventListener('message', this.windowMessageHandler);
for (const fn of this.iframeCleanupFns) fn();
this.iframeCleanupFns = [];
if (this.keydownHandler) { if (this.keydownHandler) {
document.removeEventListener('keydown', this.keydownHandler); document.removeEventListener('keydown', this.keydownHandler);
this.keydownHandler = undefined; this.keydownHandler = undefined;
} }
if (this.longHoldTimeout) {
clearTimeout(this.longHoldTimeout);
this.longHoldTimeout = null;
}
if (this.selectionChangeTimeout) {
clearTimeout(this.selectionChangeTimeout);
this.selectionChangeTimeout = null;
}
this.view = null; this.view = null;
this.viewCallbacks = null; this.viewCallbacks = null;
this.isNavigating = false;
this.lastClickTime = 0;
this.lastClickZone = null;
this.clickedDocs = new WeakSet<Document>(); this.clickedDocs = new WeakSet<Document>();
} }
@@ -141,7 +156,9 @@ export class ReaderEventService {
this.eventSubject.next({type: 'load', detail: e.detail}); this.eventSubject.next({type: 'load', detail: e.detail});
if (e.detail?.doc) { if (e.detail?.doc) {
if (this.keydownHandler) { if (this.keydownHandler) {
e.detail.doc.addEventListener('keydown', this.keydownHandler); const handler = this.keydownHandler;
e.detail.doc.addEventListener('keydown', handler);
this.iframeCleanupFns.push(() => e.detail?.doc?.removeEventListener('keydown', handler));
} }
this.attachIframeEventHandlers(e.detail.doc); this.attachIframeEventHandlers(e.detail.doc);
} }
@@ -234,12 +251,14 @@ export class ReaderEventService {
document.addEventListener('keydown', this.keydownHandler); document.addEventListener('keydown', this.keydownHandler);
} }
private readonly windowMessageHandler = (event: MessageEvent): void => {
if (this.isIframeClickMessage(event.data)) {
this.handleIframeClickMessage(event.data);
}
};
private attachWindowMessageHandler(): void { private attachWindowMessageHandler(): void {
window.addEventListener('message', (event) => { window.addEventListener('message', this.windowMessageHandler);
if (this.isIframeClickMessage(event.data)) {
this.handleIframeClickMessage(event.data);
}
});
} }
private isIframeClickMessage(value: unknown): value is IframeClickMessage { private isIframeClickMessage(value: unknown): value is IframeClickMessage {
@@ -252,17 +271,22 @@ export class ReaderEventService {
} }
this.clickedDocs.add(doc); this.clickedDocs.add(doc);
doc.addEventListener('mousedown', () => { const track = (target: EventTarget, type: string, handler: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): void => {
target.addEventListener(type, handler, options);
this.iframeCleanupFns.push(() => target.removeEventListener(type, handler, options));
};
track(doc, 'mousedown', () => {
this.longHoldTimeout = setTimeout(() => { this.longHoldTimeout = setTimeout(() => {
this.longHoldTimeout = null; this.longHoldTimeout = null;
}, this.LONG_HOLD_THRESHOLD_MS); }, this.LONG_HOLD_THRESHOLD_MS);
}, true); }, {capture: true});
doc.addEventListener('mouseup', () => { track(doc, 'mouseup', () => {
this.handleSelectionEnd(doc); this.handleSelectionEnd(doc);
}); });
doc.addEventListener('click', (event: MouseEvent) => { track(doc, 'click', ((event: MouseEvent) => {
// Ignore synthesized mouse events that follow touch events // Ignore synthesized mouse events that follow touch events
if (Date.now() - this.lastTouchTime < 500) { if (Date.now() - this.lastTouchTime < 500) {
return; return;
@@ -284,21 +308,21 @@ export class ReaderEventService {
eventClientX: event.clientX, eventClientX: event.clientX,
target: (event.target as HTMLElement)?.tagName target: (event.target as HTMLElement)?.tagName
}, '*'); }, '*');
}, true); }) as EventListener, {capture: true});
doc.addEventListener('touchstart', (event: TouchEvent) => { track(doc, 'touchstart', ((event: TouchEvent) => {
this.handleTouchStart(event, doc); this.handleTouchStart(event, doc);
}, {passive: true}); }) as EventListener, {passive: true});
doc.addEventListener('touchmove', (event: TouchEvent) => { track(doc, 'touchmove', ((event: TouchEvent) => {
this.handleTouchMove(event, doc); this.handleTouchMove(event, doc);
}, {passive: false}); }) as EventListener, {passive: false});
doc.addEventListener('touchend', (event: TouchEvent) => { track(doc, 'touchend', ((event: TouchEvent) => {
this.handleTouchEnd(event, doc); this.handleTouchEnd(event, doc);
}, {passive: false}); }) as EventListener, {passive: false});
doc.addEventListener('selectionchange', () => { track(doc, 'selectionchange', () => {
this.handleSelectionChange(doc); this.handleSelectionChange(doc);
}); });
@@ -1,16 +1,16 @@
<div <div
class="reader" class="reader"
[class.immersive]="immersiveMode" [class.immersive]="immersiveMode()"
[style.background-color]="readerState().theme.bg ?? ''"> [style.background-color]="readerState().theme.bg ?? ''">
<div class="header-trigger-zone" <div class="header-trigger-zone"
[class.inactive]="headerVisible || immersiveMode" [class.inactive]="headerVisible() || immersiveMode()"
(mouseenter)="onHeaderTriggerZoneEnter()"></div> (mouseenter)="onHeaderTriggerZoneEnter()"></div>
<div class="footer-trigger-zone" <div class="footer-trigger-zone"
[class.inactive]="forceNavbarVisible || immersiveMode" [class.inactive]="forceNavbarVisible() || immersiveMode()"
(mouseenter)="onFooterTriggerZoneEnter()"></div> (mouseenter)="onFooterTriggerZoneEnter()"></div>
@if (isLoading) { @if (isLoading()) {
<div class="loader-overlay"> <div class="loader-overlay">
<div class="loader-content"> <div class="loader-content">
<div class="spinner"></div> <div class="spinner"></div>
@@ -33,37 +33,37 @@
</div> </div>
<app-reader-navbar <app-reader-navbar
[progressData]="currentProgressData" [progressData]="progressData()"
[forceVisible]="forceNavbarVisible" [forceVisible]="forceNavbarVisible()"
[sectionFractions]="sectionFractions" [sectionFractions]="sectionFractions()"
(progressChange)="onProgressChange($event)"> (progressChange)="onProgressChange($event)">
</app-reader-navbar> </app-reader-navbar>
<app-reader-sidebar></app-reader-sidebar> <app-reader-sidebar></app-reader-sidebar>
<app-reader-left-sidebar></app-reader-left-sidebar> <app-reader-left-sidebar></app-reader-left-sidebar>
@if (showQuickSettings) { @if (showQuickSettings()) {
<app-reader-quick-settings <app-reader-quick-settings
[stateService]="stateService" [stateService]="stateService"
[bookId]="bookId" [bookId]="bookId"
(closed)="showQuickSettings = false" (closed)="showQuickSettings.set(false)"
(openFullSettings)="showControls = true"> (openFullSettings)="showControls.set(true)">
</app-reader-quick-settings> </app-reader-quick-settings>
} }
@if (showControls) { @if (showControls()) {
<app-settings-dialog <app-settings-dialog
[stateService]="stateService" [stateService]="stateService"
[viewManager]="viewManager" [viewManager]="viewManager"
[bookId]="bookId" [bookId]="bookId"
(closed)="showControls = false"> (closed)="showControls.set(false)">
</app-settings-dialog> </app-settings-dialog>
} }
@if (showMetadata) { @if (showMetadata()) {
<app-reader-book-metadata-dialog <app-reader-book-metadata-dialog
[book]="book" [book]="book()"
(closed)="showMetadata = false" (closed)="showMetadata.set(false)"
></app-reader-book-metadata-dialog> ></app-reader-book-metadata-dialog>
} }
@@ -85,7 +85,7 @@
></app-reader-note-dialog> ></app-reader-note-dialog>
} }
@if (showShortcutsHelp) { @if (showShortcutsHelp()) {
<app-ebook-shortcuts-help (closed)="showShortcutsHelp = false"></app-ebook-shortcuts-help> <app-ebook-shortcuts-help (closed)="showShortcutsHelp.set(false)"></app-ebook-shortcuts-help>
} }
</div> </div>
@@ -1,4 +1,4 @@
import {Component, CUSTOM_ELEMENTS_SCHEMA, effect, HostListener, inject, OnDestroy, OnInit} from '@angular/core'; import {ChangeDetectionStrategy, Component, CUSTOM_ELEMENTS_SCHEMA, DestroyRef, effect, HostListener, inject, OnInit, signal} from '@angular/core';
import {CommonModule} from '@angular/common'; import {CommonModule} from '@angular/common';
import {from, Observable, of, Subject, throwError} from 'rxjs'; import {from, Observable, of, Subject, throwError} from 'rxjs';
import {catchError, map, switchMap, takeUntil, tap} from 'rxjs/operators'; import {catchError, map, switchMap, takeUntil, tap} from 'rxjs/operators';
@@ -69,10 +69,12 @@ import {WakeLockService} from '../../../shared/service/wake-lock.service';
ReaderNoteService ReaderNoteService
], ],
templateUrl: './ebook-reader.component.html', templateUrl: './ebook-reader.component.html',
styleUrls: ['./ebook-reader.component.scss'] styleUrls: ['./ebook-reader.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class EbookReaderComponent implements OnInit, OnDestroy { export class EbookReaderComponent implements OnInit {
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
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);
@@ -100,18 +102,19 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
private relocateTimeout?: ReturnType<typeof setTimeout>; private relocateTimeout?: ReturnType<typeof setTimeout>;
private sectionFractionsTimeout?: ReturnType<typeof setTimeout>; private sectionFractionsTimeout?: ReturnType<typeof setTimeout>;
isLoading = true; isLoading = signal(true);
showQuickSettings = false; showQuickSettings = signal(false);
showControls = false; showControls = signal(false);
showMetadata = false; showMetadata = signal(false);
forceNavbarVisible = false; forceNavbarVisible = signal(false);
headerVisible = false; headerVisible = signal(false);
book: Book | null = null; book = signal<Book | null>(null);
sectionFractions: number[] = []; sectionFractions = signal<number[]>([]);
isFullscreen = false; isFullscreen = signal(false);
showShortcutsHelp = false; showShortcutsHelp = signal(false);
immersiveMode = false; immersiveMode = signal(false);
private immersiveAutoHideTimer?: ReturnType<typeof setTimeout>; private immersiveAutoHideTimer?: ReturnType<typeof setTimeout>;
protected progressData = signal<RelocateProgressData | null>(null);
readonly readerState = this.stateService.state; readonly readerState = this.stateService.state;
readonly selectionState = this.selectionService.state; readonly selectionState = this.selectionService.state;
@@ -119,6 +122,32 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
readonly isCurrentCfiBookmarked = this.headerService.isCurrentCfiBookmarked; readonly isCurrentCfiBookmarked = this.headerService.isCurrentCfiBookmarked;
constructor() { constructor() {
this.destroyRef.onDestroy(() => {
this.destroy$.next();
this.destroy$.complete();
this.wakeLockService.disable();
this.viewManager.destroy();
this.annotationService.reset();
this.progressService.endSession();
this.progressService.reset();
this.selectionService.reset();
this.sidebarService.reset();
this.leftSidebarService.reset();
this.headerService.reset();
this.noteService.reset();
this.epubCustomFontService.cleanup();
if (this.immersiveAutoHideTimer) clearTimeout(this.immersiveAutoHideTimer);
if (this.relocateTimeout) clearTimeout(this.relocateTimeout);
if (this.sectionFractionsTimeout) clearTimeout(this.sectionFractionsTimeout);
if (this._fileUrl) {
URL.revokeObjectURL(this._fileUrl);
this._fileUrl = null;
}
});
effect(() => { effect(() => {
this.stateService.state(); this.stateService.state();
this.applyStyles(); this.applyStyles();
@@ -133,29 +162,25 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
); );
} }
get currentProgressData(): RelocateProgressData | null {
return this.progressService.currentProgressData;
}
ngOnInit() { ngOnInit() {
this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight); this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight);
this.visibilityManager.onStateChange((state) => { this.visibilityManager.onStateChange((state) => {
this.headerVisible = state.headerVisible; this.headerVisible.set(state.headerVisible);
this.headerService.setForceVisible(state.headerVisible); this.headerService.setForceVisible(state.headerVisible);
this.forceNavbarVisible = state.footerVisible; this.forceNavbarVisible.set(state.footerVisible);
}); });
this.sidebarService.showMetadata$ this.sidebarService.showMetadata$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe(() => this.showMetadata = true); .subscribe(() => this.showMetadata.set(true));
this.headerService.showControls$ this.headerService.showControls$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe(() => this.showQuickSettings = true); .subscribe(() => this.showQuickSettings.set(true));
this.headerService.showMetadata$ this.headerService.showMetadata$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe(() => this.showMetadata = true); .subscribe(() => this.showMetadata.set(true));
this.headerService.toggleFullscreen$ this.headerService.toggleFullscreen$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
@@ -163,12 +188,12 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.headerService.showShortcutsHelp$ this.headerService.showShortcutsHelp$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe(() => this.showShortcutsHelp = 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 = true; this.isLoading.set(true);
this.initializeFoliate().pipe( this.initializeFoliate().pipe(
switchMap(() => this.epubCustomFontService.loadAndCacheFonts()), switchMap(() => this.epubCustomFontService.loadAndCacheFonts()),
tap(() => this.stateService.refreshCustomFonts()), tap(() => this.stateService.refreshCustomFonts()),
@@ -177,39 +202,15 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.subscribeToViewEvents(); this.subscribeToViewEvents();
}), }),
switchMap(() => this.loadBookFromAPI()), switchMap(() => this.loadBookFromAPI()),
tap(() => this.isLoading = false), tap(() => this.isLoading.set(false)),
catchError(() => { catchError(() => {
this.isLoading = false; this.isLoading.set(false);
return of(null); return of(null);
}), }),
takeUntil(this.destroy$) takeUntil(this.destroy$)
).subscribe(); ).subscribe();
} }
ngOnDestroy(): void {
this.wakeLockService.disable();
this.destroy$.next();
this.destroy$.complete();
this.viewManager.destroy();
this.annotationService.reset();
this.progressService.endSession();
this.progressService.reset();
this.selectionService.reset();
this.sidebarService.reset();
this.leftSidebarService.reset();
this.headerService.reset();
this.noteService.reset();
this.epubCustomFontService.cleanup();
if (this.immersiveAutoHideTimer) {
clearTimeout(this.immersiveAutoHideTimer);
}
if (this._fileUrl) {
URL.revokeObjectURL(this._fileUrl);
this._fileUrl = null;
}
}
private initializeFoliate(): Observable<void> { private initializeFoliate(): Observable<void> {
return this.loaderService.loadFoliateScript().pipe( return this.loaderService.loadFoliateScript().pipe(
switchMap(() => this.loaderService.waitForCustomElement()) switchMap(() => this.loaderService.waitForCustomElement())
@@ -232,7 +233,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
return from(this.bookService.fetchFreshBookDetail(this.bookId, false)).pipe( return from(this.bookService.fetchFreshBookDetail(this.bookId, false)).pipe(
switchMap((book) => { switchMap((book) => {
this.book = book; this.book.set(book);
// Use alternative bookType from query param if provided, otherwise use primary // Use alternative bookType from query param if provided, otherwise use primary
const bookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType; const bookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType;
@@ -317,6 +318,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
if (this.relocateTimeout) clearTimeout(this.relocateTimeout); if (this.relocateTimeout) clearTimeout(this.relocateTimeout);
this.relocateTimeout = setTimeout(() => { this.relocateTimeout = setTimeout(() => {
this.progressService.handleRelocateEvent(event.detail); this.progressService.handleRelocateEvent(event.detail);
this.progressData.set(this.progressService.currentProgressData);
this.updateBookmarkIndicator(); this.updateBookmarkIndicator();
}, 100); }, 100);
@@ -326,7 +328,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
}, 500); }, 500);
break; break;
case 'middle-single-tap': case 'middle-single-tap':
if (this.immersiveMode) { if (this.immersiveMode()) {
this.immersiveTemporaryShow(); this.immersiveTemporaryShow();
} else { } else {
this.toggleHeaderNavbarPinned(); this.toggleHeaderNavbarPinned();
@@ -339,7 +341,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.toggleFullscreen(); this.toggleFullscreen();
break; break;
case 'toggle-shortcuts-help': case 'toggle-shortcuts-help':
this.showShortcutsHelp = !this.showShortcutsHelp; this.showShortcutsHelp.update(v => !v);
break; break;
case 'toggle-immersive': case 'toggle-immersive':
this.toggleImmersiveMode(); this.toggleImmersiveMode();
@@ -364,17 +366,17 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.leftSidebarService.toggle('notes'); this.leftSidebarService.toggle('notes');
break; break;
case 'escape-pressed': case 'escape-pressed':
if (this.showShortcutsHelp) { if (this.showShortcutsHelp()) {
this.showShortcutsHelp = false; this.showShortcutsHelp.set(false);
} else if (this.noteDialogState().visible) { } else if (this.noteDialogState().visible) {
this.noteService.closeDialog(); this.noteService.closeDialog();
} else if (this.showControls) { } else if (this.showControls()) {
this.showControls = false; this.showControls.set(false);
} else if (this.showQuickSettings) { } else if (this.showQuickSettings()) {
this.showQuickSettings = false; this.showQuickSettings.set(false);
} else if (this.showMetadata) { } else if (this.showMetadata()) {
this.showMetadata = false; this.showMetadata.set(false);
} else if (this.isFullscreen) { } else if (this.isFullscreen()) {
this.exitFullscreen(); this.exitFullscreen();
} }
break; break;
@@ -383,7 +385,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
} }
private updateSectionFractions(): void { private updateSectionFractions(): void {
this.sectionFractions = this.viewManager.getSectionFractions(); this.sectionFractions.set(this.viewManager.getSectionFractions());
} }
private updateBookmarkIndicator(): void { private updateBookmarkIndicator(): void {
@@ -407,8 +409,8 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
@HostListener('document:fullscreenchange') @HostListener('document:fullscreenchange')
onFullscreenChange(): void { onFullscreenChange(): void {
this.isFullscreen = !!document.fullscreenElement; this.isFullscreen.set(!!document.fullscreenElement);
this.headerService.setFullscreen(this.isFullscreen); this.headerService.setFullscreen(this.isFullscreen());
} }
toggleFullscreen(): void { toggleFullscreen(): void {
@@ -464,16 +466,13 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
} }
toggleImmersiveMode(): void { toggleImmersiveMode(): void {
this.immersiveMode = !this.immersiveMode; const newValue = !this.immersiveMode();
if (this.immersiveMode) { this.immersiveMode.set(newValue);
this.visibilityManager.setImmersive(true); this.visibilityManager.setImmersive(newValue);
} else {
this.visibilityManager.setImmersive(false);
}
} }
private immersiveTemporaryShow(): void { private immersiveTemporaryShow(): void {
if (!this.immersiveMode) return; if (!this.immersiveMode()) return;
this.visibilityManager.temporaryShow(); this.visibilityManager.temporaryShow();
if (this.immersiveAutoHideTimer) clearTimeout(this.immersiveAutoHideTimer); if (this.immersiveAutoHideTimer) clearTimeout(this.immersiveAutoHideTimer);
this.immersiveAutoHideTimer = setTimeout(() => { this.immersiveAutoHideTimer = setTimeout(() => {