feat(cbx-viewer): add (back) infinite and long-strip modes, fixed. (#390)

* feat(cbx-viewer): add (back) infinite and long-strip modes, fixed.

* feat(reader): improve strip width controls and improve continuation affordance

* fix(cbx-reader): clear debounce timer on layout generation changes
This commit is contained in:
brios
2026-04-22 17:27:07 -04:00
committed by Zach Yale
parent 78099cc92c
commit 1db1b8404a
20 changed files with 964 additions and 123 deletions
@@ -202,6 +202,8 @@ public class BookLoreUser {
private CbxPageFitMode fitMode;
private CbxPageScrollMode scrollMode;
private CbxBackgroundColor backgroundColor;
/** Max width (percent of reader) for infinite / long-strip modes; null means 100. */
private Integer stripMaxWidthPercent;
}
@Data
@@ -101,6 +101,7 @@ public class DefaultUserSettingsProvider {
.fitMode(CbxPageFitMode.FIT_HEIGHT)
.scrollMode(CbxPageScrollMode.PAGINATED)
.backgroundColor(CbxBackgroundColor.GRAY)
.stripMaxWidthPercent(100)
.build();
}
@@ -1,10 +1,28 @@
<div class="comic-reader-container" tabindex="0" [class.rtl-reading]="readingDirection === CbxReadingDirection.RTL"
<div #readerRoot class="comic-reader-container" tabindex="0"
[class.rtl-reading]="readingDirection === CbxReadingDirection.RTL"
[class.fullscreen-mode]="isFullscreen" [class.slideshow-active]="isSlideshowActive">
<app-cbx-header [isCurrentPageBookmarked]="isCurrentPageBookmarked"
[currentPageHasNotes]="currentPageHasNotes"></app-cbx-header>
<app-cbx-sidebar></app-cbx-sidebar>
@if (showWebtoonSuggestion) {
<div class="webtoon-suggestion-banner" role="region" [attr.aria-label]="'readerCbx.webtoonHint.regionLabel' | transloco">
<p class="webtoon-suggestion-text">{{ 'readerCbx.webtoonHint.message' | transloco }}</p>
<div class="webtoon-suggestion-actions">
<button type="button" class="webtoon-btn primary" (click)="onWebtoonSuggestSwitchToLongStrip()">
{{ 'readerCbx.webtoonHint.switch' | transloco }}
</button>
<button type="button" class="webtoon-btn" (click)="onWebtoonSuggestDismiss()">
{{ 'readerCbx.webtoonHint.dismiss' | transloco }}
</button>
<button type="button" class="webtoon-btn subtle" (click)="onWebtoonSuggestNever()">
{{ 'readerCbx.webtoonHint.never' | transloco }}
</button>
</div>
</div>
}
@if (showQuickSettings) {
<app-cbx-quick-settings></app-cbx-quick-settings>
}
@@ -33,7 +51,7 @@
<div #magnifierLens class="magnifier-lens"></div>
<div 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.infinite-scroll]="scrollMode === CbxScrollMode.INFINITE"
[class.long-strip]="scrollMode === CbxScrollMode.LONG_STRIP"
@@ -79,12 +97,18 @@
} @else if (scrollMode === CbxScrollMode.LONG_STRIP) {
<div class="long-strip-wrapper" role="button" tabindex="0" (click)="onImageClick()"
(keydown.enter)="onImageClick()">
@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"
(load)="onLongStripImageLoad($event, item.page)" />
}
@if (longStripImages.length > 0 && longStripImages[longStripImages.length - 1].page >= pages.length - 1 &&
nextBookInSeries) {
<div class="strip-width-constrain" [style.width]="cbxQuickSettingsState().stripMaxWidthPercent + '%'">
@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"
draggable="false" (load)="onLongStripImageLoad($event, item.page)" />
}
@if (nextBookInSeries) {
<div class="cbx-continuation-spacer" aria-hidden="true"></div>
<div class="cbx-continuation-hint" [class.visible]="continuationHintVisible" aria-live="polite">
{{ 'readerCbx.continuation.scrollForNext' | transloco }}
</div>
}
@if (isAtEndOfLongStrip && nextBookInSeries) {
<div class="end-of-comic-action">
<button class="next-book-action-button" (click)="navigateToNextBook()">
<span class="action-icon">📖</span>
@@ -92,22 +116,30 @@
<span class="book-title">{{ getBookDisplayTitle(nextBookInSeries) }}</span>
</button>
</div>
}
}
</div>
</div>
} @else {
<div class="infinite-scroll-wrapper">
@for (pageIdx of infiniteScrollPages; track pageIdx; let i = $index) {
<img [src]="getPageImageUrl(pageIdx)" alt="Page {{ pageIdx + 1 }}" class="page-image" role="button" tabindex="0"
(click)="onImageClick()" (keydown.enter)="onImageClick()" (dblclick)="onImageDoubleClick()"
(load)="onPageImageLoad($event, pageIdx)" />
}
@if (isLoadingMore) {
<div class="loading-more">
<p-progressSpinner class="small-spinner"></p-progressSpinner>
</div>
}
@if (infiniteScrollPages.length > 0 && infiniteScrollPages[infiniteScrollPages.length - 1] >= pages.length - 1 &&
nextBookInSeries) {
<div class="strip-width-constrain" [style.width]="cbxQuickSettingsState().stripMaxWidthPercent + '%'">
@for (pageIdx of infiniteScrollPages; track pageIdx) {
<img [src]="getPageImageUrl(pageIdx)" alt="Page {{ pageIdx + 1 }}" class="page-image"
[attr.data-page]="pageIdx" role="button" tabindex="0" draggable="false"
(click)="onImageClick()" (keydown.enter)="onImageClick()" (dblclick)="onImageDoubleClick()"
(load)="onPageImageLoad($event, pageIdx)" />
}
@if (isLoadingMore) {
<div class="loading-more">
<p-progressSpinner class="small-spinner"></p-progressSpinner>
</div>
}
@if (nextBookInSeries) {
<div class="cbx-continuation-spacer" aria-hidden="true"></div>
<div class="cbx-continuation-hint" [class.visible]="continuationHintVisible" aria-live="polite">
{{ 'readerCbx.continuation.scrollForNext' | transloco }}
</div>
}
@if (isAtEndOfInfiniteScroll && nextBookInSeries) {
<div class="end-of-comic-action">
<button class="next-book-action-button" (click)="navigateToNextBook()">
<span class="action-icon">📖</span>
@@ -115,7 +147,8 @@
<span class="book-title">{{ getBookDisplayTitle(nextBookInSeries) }}</span>
</button>
</div>
}
}
</div>
</div>
}
@@ -1,3 +1,30 @@
@mixin cbx-reader-continuation-affordance {
.cbx-continuation-spacer {
flex: 0 0 auto;
min-height: 28vh;
width: 100%;
pointer-events: none;
}
.cbx-continuation-hint {
flex: 0 0 auto;
width: 100%;
text-align: center;
font-size: 0.88rem;
color: rgb(255 255 255 / 45%);
opacity: 0;
transform: translateY(6px);
transition: opacity 0.35s ease, transform 0.35s ease, color 0.35s ease;
pointer-events: none;
&.visible {
opacity: 1;
transform: translateY(0);
color: rgb(255 255 255 / 72%);
}
}
}
.comic-reader-container {
display: flex;
flex-direction: column;
@@ -16,6 +43,78 @@
outline: none;
}
&:fullscreen {
height: 100%;
width: 100%;
max-height: 100%;
}
.webtoon-suggestion-banner {
flex: 0 0 auto;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.75rem 1rem;
padding: 0.65rem 1rem;
margin: 0 0.5rem;
background: rgb(30 40 55 / 95%);
border: 1px solid rgb(255 255 255 / 12%);
border-radius: 8px;
z-index: 900;
box-shadow: 0 4px 16px rgb(0 0 0 / 35%);
}
.webtoon-suggestion-text {
margin: 0;
flex: 1 1 200px;
font-size: 0.9rem;
line-height: 1.35;
color: rgb(255 255 255 / 88%);
}
.webtoon-suggestion-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.webtoon-btn {
padding: 0.4rem 0.75rem;
border-radius: 6px;
border: 1px solid rgb(255 255 255 / 20%);
background: rgb(255 255 255 / 8%);
color: #fff;
font-size: 0.85rem;
cursor: pointer;
transition: background 0.15s ease, border-color 0.15s ease;
&:hover {
background: rgb(255 255 255 / 14%);
}
&.primary {
border-color: #4a90e2;
background: rgb(74 144 226 / 25%);
&:hover {
background: rgb(74 144 226 / 38%);
}
}
&.subtle {
border-color: transparent;
background: transparent;
color: rgb(255 255 255 / 55%);
font-size: 0.8rem;
&:hover {
color: rgb(255 255 255 / 85%);
}
}
}
// RTL reading mode - reverse page order in two-page view
&.rtl-reading {
.two-page-view {
@@ -328,7 +427,28 @@
align-items: center;
gap: 1rem;
width: 100%;
min-width: 0;
padding: 1rem 0;
overflow-anchor: none;
}
.strip-width-constrain {
// Width set inline from quick-settings signal (% of wrapper). Center column when < 100%.
flex-shrink: 0;
min-width: 0;
max-width: 100%;
margin-inline: auto;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
@include cbx-reader-continuation-affordance;
.cbx-continuation-hint {
padding: 0.5rem 1rem 1rem;
}
.page-image {
@@ -363,8 +483,10 @@
.infinite-scroll-wrapper {
align-items: center;
width: max-content;
min-width: 100%;
// Stable width so strip max-width % resolves against the reader scrollport, not max-content.
width: 100%;
min-width: 0;
}
.page-image {
@@ -406,7 +528,8 @@
}
}
// Long-strip (webtoon) mode — gapless vertical strip, always fit-width
// Long-strip: same fit semantics as infinite scroll (width:100% only for fit-width),
// so switching scroll modes does not change zoom.
&.long-strip {
overflow: hidden auto;
align-items: flex-start;
@@ -418,15 +541,31 @@
flex-direction: column;
align-items: center;
width: 100%;
min-width: 0;
// No gap, no padding — gapless vertical strip
}
.strip-width-constrain {
flex-shrink: 0;
min-width: 0;
max-width: 100%;
margin-inline: auto;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
}
@include cbx-reader-continuation-affordance;
.cbx-continuation-hint {
padding: 0.75rem 1rem 1.25rem;
}
.long-strip-image {
display: block;
width: 100%;
height: auto;
max-width: 100%;
object-fit: contain;
border: 0;
margin: 0;
padding: 0;
@@ -434,6 +573,66 @@
// Hardware acceleration (Kavita pattern)
transform: translate3d(0, 0, 0);
}
&.fit-width .long-strip-image {
width: 100%;
height: auto;
max-width: 100%;
}
&.fit-height {
.long-strip-wrapper {
min-height: 100%;
}
.long-strip-image {
width: auto;
height: calc(100vh - 2rem);
max-width: 100%;
}
}
&.fit-actual-size {
overflow-x: auto;
.long-strip-wrapper {
align-items: center;
width: 100%;
min-width: 0;
}
.long-strip-image {
width: auto;
height: auto;
max-width: none;
}
}
&.fit-page {
.long-strip-wrapper {
min-height: 100%;
}
.long-strip-image {
max-width: 100%;
max-height: calc(100vh - 2rem);
width: auto;
height: auto;
}
}
&.fit-auto {
.long-strip-wrapper {
min-height: 100%;
}
.long-strip-image {
max-width: 100%;
max-height: calc(100vh - 2rem);
width: auto;
height: auto;
}
}
}
.no-pages {
@@ -2,7 +2,7 @@ import { Component, effect, ElementRef, HostListener, inject, OnDestroy, OnInit,
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { forkJoin, from, Subject } from 'rxjs';
import { debounceTime, map, switchMap, takeUntil } from 'rxjs/operators';
import { debounceTime, map, switchMap, takeUntil, tap } from 'rxjs/operators';
import { PageTitleService } from "../../../shared/service/page-title.service";
import { CbxReaderService } from '../../book/service/cbx-reader.service';
import { BookService } from '../../book/service/book.service';
@@ -30,6 +30,15 @@ import { CbxNoteDialogComponent, CbxNoteDialogData, CbxNoteDialogResult } from '
import { CbxShortcutsHelpComponent } from './dialogs/cbx-shortcuts-help.component';
import { CanvasRendererComponent } from './renderers/canvas-renderer.component';
import { BookNoteV2 } from '../../../shared/service/book-note-v2.service';
import { ReaderPreferencesService } from '../../settings/reader-preferences/reader-preferences.service';
import {
clampStripMaxWidthPercent,
dismissWebtoonHintForSession,
dismissWebtoonHintForever,
readStripWidthPercent,
shouldOfferWebtoonHint,
writeStripWidthPercentPerBook
} from './core/cbx-reader-storage';
@Component({
@@ -58,6 +67,15 @@ import { BookNoteV2 } from '../../../shared/service/book-note-v2.service';
styleUrl: './cbx-reader.component.scss'
})
export class CbxReaderComponent implements OnInit, OnDestroy {
private static readonly PRELOAD_PAGE_WINDOW = 5;
private static readonly INFINITE_SCROLL_PAGE_DEBOUNCE_MS = 80;
private static readonly STRIP_WIDTH_PERSIST_DEBOUNCE_MS = 400;
private static readonly READER_LAYOUT_GRACE_MS = 1000;
private static readonly CONTINUATION_HINT_SHOW_PX = 220;
private static readonly CONTINUATION_HINT_HIDE_PX = 380;
private static readonly LONG_STRIP_BUFFER = 7;
private static readonly AUTO_CLOSE_MENU_TIMEOUT = 3000;
private destroy$ = new Subject<void>();
private progressSaveSubject$ = new Subject<void>();
@@ -83,11 +101,12 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
previousBookInSeries: Book | null = null;
infiniteScrollPages: number[] = [];
preloadCount: number = 3;
preloadCount: number = CbxReaderComponent.PRELOAD_PAGE_WINDOW;
/** True while a chunk of pages is being prepended/appended (does not block scroll UX). */
isLoadingMore: boolean = false;
private infiniteScrollPageDebounceTimer: ReturnType<typeof setTimeout> | null = null;
// Long-strip state (Kavita-inspired webtoon reader)
private static readonly LONG_STRIP_BUFFER = 5;
longStripImages: { src: string; page: number }[] = [];
private longStripLoadedPages = new Set<number>();
private longStripIntersectionObserver: IntersectionObserver | null = null;
@@ -135,6 +154,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
// Magnifier
isMagnifierActive = false;
@ViewChild('magnifierLens', { static: true }) private magnifierLensRef!: ElementRef<HTMLDivElement>;
@ViewChild('readerRoot', { read: ElementRef }) private readerRootRef?: ElementRef<HTMLElement>;
@ViewChild('imageScrollHost', { read: ElementRef }) private imageScrollHostRef?: ElementRef<HTMLElement>;
magnifierZoom: CbxMagnifierZoom = CbxMagnifierZoom.ZOOM_3X;
magnifierLensSize: CbxMagnifierLensSize = CbxMagnifierLensSize.MEDIUM;
private lastMouseEvent: MouseEvent | null = null;
@@ -145,6 +166,22 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
// Brightness filter (0-100, default 100)
brightness = 100;
/** 50–100: max width of strip column (infinite / long strip). */
stripMaxWidthPercent = 100;
/** Kavita-style hint when archive looks like vertical webtoon strips. */
showWebtoonSuggestion = false;
/** Near bottom of strip + next in series: show subtle continuation hint. */
continuationHintVisible = false;
private cbxSettingsUsesGlobal = true;
private readerLayoutGraceUntilMs = 0;
/** Invalidates delayed scroll/layout work after book or scroll-mode changes. */
private readerLayoutGeneration = 0;
/** Avoid continuation hint flicker when scroll height changes (hysteresis). */
private continuationHintLatched = false;
// Emulate book mode (spine shadow in two-page view)
emulateBook = false;
@@ -154,7 +191,6 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
// Auto-close menu after interaction
autoCloseMenu = false;
private autoCloseMenuTimer: ReturnType<typeof setTimeout> | null = null;
private static readonly AUTO_CLOSE_MENU_TIMEOUT = 3000;
// Page dimensions from backend
pageDimensions: CbxPageDimension[] = [];
@@ -188,8 +224,11 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
private sidebarService = inject(CbxSidebarService);
private footerService = inject(CbxFooterService);
private quickSettingsService = inject(CbxQuickSettingsService);
/** Template reads this signal so strip width tracks the slider (same source as quick settings panel). */
protected readonly cbxQuickSettingsState = this.quickSettingsService.state;
private pageDimensionService = inject(CbxPageDimensionService);
private wakeLockService = inject(WakeLockService);
private readerPreferencesService = inject(ReaderPreferencesService);
protected readonly CbxScrollMode = CbxScrollMode;
protected readonly CbxFitMode = CbxFitMode;
@@ -200,6 +239,20 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
private static readonly TYPE_CBX = 'CBX';
private static readonly SETTING_GLOBAL = 'Global';
private bumpReaderLayoutGeneration(): void {
this.readerLayoutGeneration++;
this.continuationHintLatched = false;
}
private getImageScrollContainer(): HTMLElement | null {
return this.imageScrollHostRef?.nativeElement ?? null;
}
/** Run after the browser has applied layout (two frames — common Angular/DOM pattern). */
private afterNextPaint(fn: () => void): void {
requestAnimationFrame(() => requestAnimationFrame(fn));
}
constructor() {
effect(() => {
this.sidebarService.bookmarks();
@@ -239,6 +292,14 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.bookId = +params.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
this.showWebtoonSuggestion = false;
this.continuationHintVisible = false;
if (this.infiniteScrollPageDebounceTimer) {
clearTimeout(this.infiniteScrollPageDebounceTimer);
this.infiniteScrollPageDebounceTimer = null;
}
this.bumpReaderLayoutGeneration();
this.previousBookInSeries = null;
this.nextBookInSeries = null;
this.currentBook = null;
@@ -293,6 +354,13 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
if (this.bookType === CbxReaderComponent.TYPE_CBX) {
const global = userSettings.perBookSetting.cbx === CbxReaderComponent.SETTING_GLOBAL;
this.cbxSettingsUsesGlobal = global;
this.stripMaxWidthPercent = readStripWidthPercent(
this.bookId,
global,
userSettings.cbxReaderSetting.stripMaxWidthPercent,
myself.id
);
this.pageViewMode = global
? this.CbxPageViewMode[userSettings.cbxReaderSetting.pageViewMode as keyof typeof CbxPageViewMode] || this.CbxPageViewMode.SINGLE_PAGE
: this.CbxPageViewMode[bookSettings.cbxSettings?.pageViewMode as keyof typeof CbxPageViewMode] || this.CbxPageViewMode[userSettings.cbxReaderSetting.pageViewMode as keyof typeof CbxPageViewMode] || this.CbxPageViewMode.SINGLE_PAGE;
@@ -325,10 +393,6 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.currentPage = (book.cbxProgress?.page || 1) - 1;
if (this.scrollMode as string === 'LONG_STRIP') {
this.scrollMode = CbxScrollMode.INFINITE;
}
if (this.scrollMode === CbxScrollMode.INFINITE) {
this.initializeInfiniteScroll();
} else if (this.scrollMode === CbxScrollMode.LONG_STRIP) {
@@ -337,6 +401,18 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
}
this.alignCurrentPageToParity();
this.readerLayoutGraceUntilMs = Date.now() + CbxReaderComponent.READER_LAYOUT_GRACE_MS;
if (this.bookType === CbxReaderComponent.TYPE_CBX) {
const webtoon = this.pageDimensionService.detectWebtoon(dimensions);
this.showWebtoonSuggestion =
webtoon.isWebtoon &&
this.scrollMode !== CbxScrollMode.LONG_STRIP &&
shouldOfferWebtoonHint(this.bookId);
} else {
this.showWebtoonSuggestion = false;
}
this.updateServiceStates();
this.updateBookmarkState();
this.updateNotesState();
@@ -527,6 +603,16 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.quickSettingsService.setAutoCloseMenu(value);
this.updateViewerSetting();
});
this.quickSettingsService.stripMaxWidthChange$
.pipe(
tap((value) => {
this.stripMaxWidthPercent = value;
}),
debounceTime(CbxReaderComponent.STRIP_WIDTH_PERSIST_DEBOUNCE_MS),
takeUntil(this.destroy$)
)
.subscribe((value) => this.persistStripMaxWidth(value));
}
private updateServiceStates(): void {
@@ -552,7 +638,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
brightness: this.brightness,
emulateBook: this.emulateBook,
clickToPaginate: this.clickToPaginate,
autoCloseMenu: this.autoCloseMenu
autoCloseMenu: this.autoCloseMenu,
stripMaxWidthPercent: this.stripMaxWidthPercent
});
this.headerService.updateState({
@@ -563,6 +650,72 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.sidebarService.setCurrentPage(this.currentPage + 1);
}
private persistStripMaxWidth(value: number): void {
const v = clampStripMaxWidthPercent(value);
const u = this.userService.currentUser();
if (this.cbxSettingsUsesGlobal) {
if (u) {
this.readerPreferencesService.updatePreference(
['cbxReaderSetting', 'stripMaxWidthPercent'],
v,
{ silent: true }
);
}
} else {
writeStripWidthPercentPerBook(this.bookId, v, u?.id);
}
}
private updateContinuationHint(container: HTMLElement): void {
if (!this.nextBookInSeries) {
this.continuationHintLatched = false;
this.continuationHintVisible = false;
return;
}
if (this.scrollMode !== CbxScrollMode.INFINITE && this.scrollMode !== CbxScrollMode.LONG_STRIP) {
this.continuationHintLatched = false;
this.continuationHintVisible = false;
return;
}
if (Date.now() < this.readerLayoutGraceUntilMs) {
this.continuationHintVisible = false;
return;
}
const edge = container.scrollTop + container.clientHeight;
const bottom = container.scrollHeight;
const showPx = CbxReaderComponent.CONTINUATION_HINT_SHOW_PX;
const hidePx = CbxReaderComponent.CONTINUATION_HINT_HIDE_PX;
if (this.continuationHintLatched) {
if (edge < bottom - hidePx) {
this.continuationHintLatched = false;
this.continuationHintVisible = false;
} else {
this.continuationHintVisible = true;
}
} else if (edge >= bottom - showPx) {
this.continuationHintLatched = true;
this.continuationHintVisible = true;
} else {
this.continuationHintVisible = false;
}
}
onWebtoonSuggestSwitchToLongStrip(): void {
this.showWebtoonSuggestion = false;
this.onScrollModeChange(CbxScrollMode.LONG_STRIP);
}
onWebtoonSuggestDismiss(): void {
this.showWebtoonSuggestion = false;
dismissWebtoonHintForSession(this.bookId);
}
onWebtoonSuggestNever(): void {
this.showWebtoonSuggestion = false;
dismissWebtoonHintForever();
}
private updateFooterPage(): void {
this.footerService.setCurrentPage(this.currentPage);
this.sidebarService.setCurrentPage(this.currentPage + 1);
@@ -905,20 +1058,31 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
}
onScrollModeChange(mode: CbxScrollMode): void {
this.bumpReaderLayoutGeneration();
const previousMode = this.scrollMode;
this.scrollMode = mode;
this.quickSettingsService.setScrollMode(mode);
if (mode === CbxScrollMode.LONG_STRIP) {
this.showWebtoonSuggestion = false;
}
this.updateViewerSetting();
// Teardown previous mode
if (previousMode === CbxScrollMode.LONG_STRIP) {
this.teardownLongStrip();
}
if (previousMode === CbxScrollMode.INFINITE) {
if (this.infiniteScrollPageDebounceTimer) {
clearTimeout(this.infiniteScrollPageDebounceTimer);
this.infiniteScrollPageDebounceTimer = null;
}
this.infiniteScrollPages = [];
this.isLoadingMore = false;
}
if (this.scrollMode === CbxScrollMode.INFINITE) {
this.initializeInfiniteScroll();
// Use instant scroll for mode switch to prevent teleportation feel
setTimeout(() => this.scrollToPage(this.currentPage, 'auto'), 50);
this.scrollToPage(this.currentPage, 'auto');
} else if (this.scrollMode === CbxScrollMode.LONG_STRIP) {
this.initializeLongStrip();
} else {
@@ -963,56 +1127,119 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
}
onScroll(event: Event): void {
if (this.scrollMode !== CbxScrollMode.INFINITE || this.isLoadingMore) return;
if (this.scrollMode !== CbxScrollMode.INFINITE) return;
const container = event.target as HTMLElement;
const scrollPosition = container.scrollTop + container.clientHeight;
const scrollHeight = container.scrollHeight;
if (scrollPosition >= scrollHeight * 0.8) {
this.loadMorePages();
if (!this.isLoadingMore) {
if (scrollPosition >= scrollHeight * 0.82) {
this.loadMorePages();
}
if (container.scrollTop <= container.clientHeight * 0.18 && this.infiniteScrollPages.length > 0) {
this.loadPreviousPages(container);
}
}
this.updateCurrentPageFromScroll(container);
if (this.infiniteScrollPageDebounceTimer) {
clearTimeout(this.infiniteScrollPageDebounceTimer);
}
const layoutGen = this.readerLayoutGeneration;
this.infiniteScrollPageDebounceTimer = setTimeout(() => {
this.infiniteScrollPageDebounceTimer = null;
if (layoutGen !== this.readerLayoutGeneration || this.scrollMode !== CbxScrollMode.INFINITE) {
return;
}
this.updateCurrentPageFromScroll(container);
}, CbxReaderComponent.INFINITE_SCROLL_PAGE_DEBOUNCE_MS);
this.updateContinuationHint(container);
}
private loadMorePages(): void {
if (this.isLoadingMore) return;
const lastLoadedIndex = this.infiniteScrollPages[this.infiniteScrollPages.length - 1];
if (lastLoadedIndex >= this.pages.length - 1) return;
if (lastLoadedIndex === undefined || lastLoadedIndex >= this.pages.length - 1) return;
this.isLoadingMore = true;
const endIndex = Math.min(lastLoadedIndex + this.preloadCount + 1, this.pages.length);
setTimeout(() => {
requestAnimationFrame(() => {
for (let i = lastLoadedIndex + 1; i < endIndex; i++) {
this.infiniteScrollPages.push(i);
}
this.isLoadingMore = false;
}, 100);
});
}
/**
* Prefetch upward when the user scrolls near the top.
* Preserves scroll position relative to the first previously visible page.
*/
private loadPreviousPages(container: HTMLElement): void {
if (this.isLoadingMore) return;
const first = this.infiniteScrollPages[0];
if (first === undefined || first <= 0) return;
const anchorEl = container.querySelector(
`.infinite-scroll-wrapper img.page-image[data-page="${first}"]`
) as HTMLElement | null;
if (!anchorEl) return;
const beforeTop = anchorEl.getBoundingClientRect().top;
this.isLoadingMore = true;
const newFirst = Math.max(0, first - this.preloadCount);
const added: number[] = [];
for (let p = newFirst; p < first; p++) {
added.push(p);
}
this.infiniteScrollPages = [...added, ...this.infiniteScrollPages];
this.afterNextPaint(() => {
const afterTop = anchorEl.getBoundingClientRect().top;
container.scrollTop += afterTop - beforeTop;
this.isLoadingMore = false;
});
}
private updateCurrentPageFromScroll(container: HTMLElement): void {
const images = container.querySelectorAll('.page-image');
const images = Array.from(
container.querySelectorAll('.infinite-scroll-wrapper img.page-image[data-page]')
) as HTMLElement[];
if (!images.length) return;
const containerRect = container.getBoundingClientRect();
const midY = containerRect.top + containerRect.height / 2;
for (let i = 0; i < images.length; i++) {
const img = images[i] as HTMLElement;
let best: HTMLElement | null = null;
let bestDist = Number.MAX_VALUE;
for (const img of images) {
const rect = img.getBoundingClientRect();
if (rect.top <= containerRect.top + containerRect.height / 2 &&
rect.bottom >= containerRect.top + containerRect.height / 2) {
const newPage = this.infiniteScrollPages[i];
if (newPage !== this.currentPage) {
this.currentPage = newPage;
this.progressSaveSubject$.next();
this.updateSessionProgress();
this.updateFooterPage();
}
break;
if (rect.bottom < containerRect.top || rect.top > containerRect.bottom) {
continue;
}
const imgCenterY = rect.top + rect.height / 2;
const dist = Math.abs(imgCenterY - midY);
if (dist < bestDist) {
bestDist = dist;
best = img;
}
}
if (!best) return;
const attr = best.getAttribute('data-page');
const newPage = attr != null ? parseInt(attr, 10) : NaN;
if (Number.isNaN(newPage) || newPage === this.currentPage) return;
this.currentPage = newPage;
this.progressSaveSubject$.next();
this.updateSessionProgress();
this.updateFooterPage();
}
getPageImageUrl(pageIndex: number): string {
@@ -1038,11 +1265,15 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
{ threshold: 0.01 }
);
// Attach scroll listeners after a tick so the DOM is ready
const layoutGen = this.readerLayoutGeneration;
setTimeout(() => {
if (layoutGen !== this.readerLayoutGeneration) return;
this.longStripAttachScrollListeners();
this.longStripScrollToPage(this.currentPage);
}, 50);
this.afterNextPaint(() => {
if (layoutGen !== this.readerLayoutGeneration) return;
this.longStripWaitForImagesAndScroll(0, layoutGen);
});
}, 0);
}
private teardownLongStrip(): void {
@@ -1087,56 +1318,97 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
if (this.longStripIntersectionObserver) {
this.longStripIntersectionObserver.observe(img);
}
// Check if this is the current page's image — if so, scroll to it on first load
if (pageIndex === this.currentPage && !this.longStripInitFinished) {
this.longStripWaitForImagesAndScroll();
}
}
private longStripWaitForImagesAndScroll(): void {
// Wait for all currently-in-DOM images to load, then scroll
const container = document.querySelector('.image-container.long-strip');
if (!container) return;
/**
* Positions the strip once the current page's image exists (matches infinite scroll: no smooth jump on mode switch).
* Only waits for the active page, not the whole prefetch window.
* Retries until the img node exists single finish() guarantees one scroll.
*/
private longStripWaitForImagesAndScroll(attempt: number, layoutGen: number): void {
if (layoutGen !== this.readerLayoutGeneration) return;
if (this.scrollMode !== CbxScrollMode.LONG_STRIP) return;
if (this.longStripInitFinished) return;
const imgs = Array.from(container.querySelectorAll('img[data-page]')) as HTMLImageElement[];
const pending = imgs.filter(img => !img.complete);
if (pending.length === 0) {
this.longStripAllImagesLoaded = true;
this.longStripDoScroll(this.currentPage);
this.longStripInitFinished = true;
const container = this.getImageScrollContainer();
if (!container) {
if (attempt < 30) {
requestAnimationFrame(() => this.longStripWaitForImagesAndScroll(attempt + 1, layoutGen));
}
return;
}
Promise.all(pending.map(img => new Promise<void>(resolve => {
img.onload = () => resolve();
img.onerror = () => resolve();
}))).then(() => {
const img = container.querySelector(`img[data-page="${this.currentPage}"]`) as HTMLImageElement | null;
if (!img) {
if (attempt < 30) {
requestAnimationFrame(() => this.longStripWaitForImagesAndScroll(attempt + 1, layoutGen));
}
return;
}
const finish = (): void => {
if (layoutGen !== this.readerLayoutGeneration) return;
if (this.longStripInitFinished) return;
this.longStripAllImagesLoaded = true;
this.longStripDoScroll(this.currentPage);
this.longStripDoScroll(this.currentPage, 'instant', layoutGen);
this.longStripInitFinished = true;
});
};
if (img.complete) {
this.afterNextPaint(finish);
return;
}
const scheduleFinish = (): void => this.afterNextPaint(finish);
img.addEventListener('load', scheduleFinish, { once: true });
img.addEventListener('error', scheduleFinish, { once: true });
}
private longStripDoScroll(pageNum: number): void {
const el = document.querySelector(`img[data-page="${pageNum}"]`);
if (!el) return;
/**
* One-step scroll within a container avoids scrollIntoView + reflow (double teleport) on mode switches.
*/
private snapScrollContainerToElement(
container: HTMLElement,
el: Element,
block: 'start' | 'center'
): void {
const cRect = container.getBoundingClientRect();
const eRect = el.getBoundingClientRect();
const delta =
block === 'center'
? (eRect.top + eRect.height / 2) - (cRect.top + cRect.height / 2)
: eRect.top - cRect.top;
container.scrollTop += delta;
}
private longStripDoScroll(pageNum: number, behavior: ScrollBehavior = 'smooth', layoutGen?: number): void {
const gen = layoutGen ?? this.readerLayoutGeneration;
const container = this.getImageScrollContainer();
const el = container?.querySelector(`img[data-page="${pageNum}"]`) ?? null;
if (!container || !el) return;
this.longStripIsScrolling = true;
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
if (behavior === 'instant' || behavior === 'auto') {
this.snapScrollContainerToElement(container, el, 'center');
} else {
el.scrollIntoView({ behavior, block: 'start', inline: 'nearest' });
}
// Clear the scrolling flag once the target is visible
const settleMs = behavior === 'instant' || behavior === 'auto' ? 80 : 600;
setTimeout(() => {
if (gen !== this.readerLayoutGeneration) return;
this.longStripIsScrolling = false;
}, 600);
}, settleMs);
}
private longStripScrollToPage(pageNum: number): void {
private longStripScrollToPage(pageNum: number, behavior: ScrollBehavior = 'smooth'): void {
this.longStripPrefetchAround(pageNum);
// Wait a tick for new images to render in DOM, then scroll
setTimeout(() => this.longStripDoScroll(pageNum), 50);
const layoutGen = this.readerLayoutGeneration;
setTimeout(() => {
if (layoutGen !== this.readerLayoutGeneration) return;
this.longStripDoScroll(pageNum, behavior, layoutGen);
}, 50);
}
private longStripHandleIntersection(entries: IntersectionObserverEntry[]): void {
@@ -1155,7 +1427,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
}
private longStripAttachScrollListeners(): void {
const container = document.querySelector('.image-container.long-strip') as HTMLElement;
const container = this.getImageScrollContainer();
if (!container) return;
this.longStripScrollHandler = () => {
@@ -1182,7 +1454,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
}
private longStripDetachScrollListeners(): void {
const container = document.querySelector('.image-container.long-strip') as HTMLElement;
const container = this.getImageScrollContainer();
if (!container) return;
if (this.longStripScrollHandler) {
@@ -1215,19 +1487,20 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
// If performing a programmatic scroll, check if target is visible
if (this.longStripIsScrolling) {
const target = document.querySelector(`img[data-page="${this.currentPage}"]`);
const target = container.querySelector(`img[data-page="${this.currentPage}"]`);
if (target && this.longStripIsElementVisible(target, container)) {
this.longStripIsScrolling = false;
}
}
this.updateContinuationHint(container);
}
private longStripOnScrollEnd(container: HTMLElement): void {
if (this.longStripIsScrolling) return;
// Find the image closest to the top of the viewport
const images = Array.from(container.querySelectorAll('img[data-page]')) as HTMLImageElement[];
const closest = this.longStripFindClosestImage(images);
const images = Array.from(container.querySelectorAll('.long-strip-wrapper img[data-page]')) as HTMLImageElement[];
const closest = this.longStripFindClosestImage(images, container);
if (closest) {
const page = parseInt(closest.getAttribute('data-page') ?? '0', 10);
@@ -1238,15 +1511,23 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.updateFooterPage();
}
}
this.updateContinuationHint(container);
}
private longStripFindClosestImage(images: HTMLImageElement[]): HTMLImageElement | null {
private longStripFindClosestImage(images: HTMLImageElement[], container: HTMLElement): HTMLImageElement | null {
let closest: HTMLImageElement | null = null;
let closestDist = Number.MAX_VALUE;
const containerRect = container.getBoundingClientRect();
const midY = containerRect.top + containerRect.height / 2;
for (const img of images) {
const rect = img.getBoundingClientRect();
const dist = Math.abs(rect.top);
if (rect.bottom < containerRect.top || rect.top > containerRect.bottom) {
continue;
}
const imgCenterY = rect.top + rect.height / 2;
const dist = Math.abs(imgCenterY - midY);
if (dist < closestDist) {
closestDist = dist;
closest = img;
@@ -1338,18 +1619,19 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
private scrollToPage(pageIndex: number, behavior: ScrollBehavior = 'smooth'): void {
this.ensurePageLoaded(pageIndex);
const layoutGen = this.readerLayoutGeneration;
setTimeout(() => {
const container = document.querySelector('.image-container.infinite-scroll') as HTMLElement;
if (layoutGen !== this.readerLayoutGeneration) return;
const container = this.getImageScrollContainer();
if (!container) return;
const images = container.querySelectorAll('.page-image');
const indexInScroll = this.infiniteScrollPages.indexOf(pageIndex);
const targetImage = container.querySelector(
`.infinite-scroll-wrapper img.page-image[data-page="${pageIndex}"]`
) as HTMLElement | null;
if (indexInScroll >= 0 && indexInScroll < images.length) {
const targetImage = images[indexInScroll] as HTMLElement;
targetImage.scrollIntoView({ behavior: behavior, block: 'start' });
if (targetImage) {
targetImage.scrollIntoView({ behavior, block: 'start' });
} else if (behavior === 'auto') {
// Fallback for instant scroll: just go to top
container.scrollTop = 0;
}
}, 50);
@@ -1508,7 +1790,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
@HostListener('document:fullscreenchange')
onFullscreenChange(): void {
this.isFullscreen = !!document.fullscreenElement;
const target = this.readerRootRef?.nativeElement ?? document.documentElement;
this.isFullscreen = document.fullscreenElement === target;
this.headerService.updateState({ isFullscreen: this.isFullscreen, isSlideshowActive: this.isSlideshowActive });
}
@@ -1608,6 +1891,20 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
return this.currentPage >= this.pages.length - 1;
}
/** Last loaded long-strip page is the archive's final page (show next-book CTA when in series). */
get isAtEndOfLongStrip(): boolean {
if (this.longStripImages.length === 0) return false;
const last = this.longStripImages[this.longStripImages.length - 1];
return last.page >= this.pages.length - 1;
}
/** Last loaded infinite-scroll index is the archive's final page (show next-book CTA when in series). */
get isAtEndOfInfiniteScroll(): boolean {
if (this.infiniteScrollPages.length === 0) return false;
const lastIdx = this.infiniteScrollPages[this.infiniteScrollPages.length - 1];
return lastIdx >= this.pages.length - 1;
}
navigateToPreviousBook(): void {
if (this.previousBookInSeries) {
this.endReadingSession();
@@ -1682,7 +1979,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
}
private enterFullscreen(): void {
const elem = document.documentElement;
const elem = this.readerRootRef?.nativeElement ?? document.documentElement;
if (elem.requestFullscreen) {
void elem.requestFullscreen().catch(() => undefined);
}
@@ -1844,7 +2141,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
onClickZonePrev(event: Event): void {
event.stopPropagation();
if (this.scrollMode === CbxScrollMode.INFINITE) {
const container = document.querySelector('.image-container.infinite-scroll');
const container = this.getImageScrollContainer();
if (container) {
container.scrollBy({ top: -container.clientHeight * 0.9, behavior: 'smooth' });
}
@@ -1856,7 +2153,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
onClickZoneNext(event: Event): void {
event.stopPropagation();
if (this.scrollMode === CbxScrollMode.INFINITE) {
const container = document.querySelector('.image-container.infinite-scroll');
const container = this.getImageScrollContainer();
if (container) {
container.scrollBy({ top: container.clientHeight * 0.9, behavior: 'smooth' });
}
@@ -1933,6 +2230,10 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
ngOnDestroy(): void {
this.stopSlideshow();
if (this.infiniteScrollPageDebounceTimer) {
clearTimeout(this.infiniteScrollPageDebounceTimer);
this.infiniteScrollPageDebounceTimer = null;
}
this.teardownLongStrip();
this.endReadingSession();
this.wakeLockService.disable();
@@ -0,0 +1,70 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {
clampStripMaxWidthPercent,
readStripWidthPercent,
shouldOfferWebtoonHint,
writeStripWidthPercentPerBook
} from './cbx-reader-storage';
describe('cbx-reader-storage', () => {
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
vi.stubGlobal('localStorage', localStorage);
vi.stubGlobal('sessionStorage', sessionStorage);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('clampStripMaxWidthPercent', () => {
it('clamps to 50–100 and rounds', () => {
expect(clampStripMaxWidthPercent(40)).toBe(50);
expect(clampStripMaxWidthPercent(110)).toBe(100);
expect(clampStripMaxWidthPercent(72.4)).toBe(72);
expect(clampStripMaxWidthPercent(NaN)).toBe(100);
expect(clampStripMaxWidthPercent(undefined)).toBe(100);
});
});
describe('readStripWidthPercent / writeStripWidthPercentPerBook', () => {
it('uses server-backed value when global CBX settings are enabled', () => {
expect(readStripWidthPercent(1, true, 65, 99)).toBe(65);
expect(readStripWidthPercent(1, true, undefined, 99)).toBe(100);
});
it('reads per-book legacy key when no user id', () => {
localStorage.setItem('grimmory.cbx.stripWidth.book.7', '80');
expect(readStripWidthPercent(7, false, undefined, null)).toBe(80);
});
it('reads namespaced key when user id is set', () => {
localStorage.setItem('grimmory.cbx.stripWidth.u42.book.3', '55');
expect(readStripWidthPercent(3, false, undefined, 42)).toBe(55);
});
it('falls back from namespaced key to legacy per-book key', () => {
localStorage.setItem('grimmory.cbx.stripWidth.book.3', '60');
expect(readStripWidthPercent(3, false, undefined, 42)).toBe(60);
});
it('writes namespaced storage when user id is provided', () => {
writeStripWidthPercentPerBook(2, 88, 5);
expect(localStorage.getItem('grimmory.cbx.stripWidth.u5.book.2')).toBe('88');
});
});
describe('shouldOfferWebtoonHint', () => {
it('returns false when session dismissed for book', () => {
sessionStorage.setItem('grimmory.cbx.webtoonHint.sessionBook.9', '1');
expect(shouldOfferWebtoonHint(9)).toBe(false);
});
it('returns false when never-again is set', () => {
localStorage.setItem('grimmory.cbx.webtoonHint.never', '1');
expect(shouldOfferWebtoonHint(1)).toBe(false);
});
});
});
@@ -0,0 +1,84 @@
const LEGACY_STRIP_WIDTH_BOOK_PREFIX = 'grimmory.cbx.stripWidth.book.';
const WEBTOON_NEVER = 'grimmory.cbx.webtoonHint.never';
const WEBTOON_SESSION_BOOK_PREFIX = 'grimmory.cbx.webtoonHint.sessionBook.';
function stripWidthStorageKey(bookId: number, userId: number | null | undefined): string {
if (userId != null && userId > 0) {
return `grimmory.cbx.stripWidth.u${userId}.book.${bookId}`;
}
return LEGACY_STRIP_WIDTH_BOOK_PREFIX + bookId;
}
/** Clamp comic strip width preference to 50–100 (percent). */
export function clampStripMaxWidthPercent(n: number | null | undefined): number {
if (n == null || Number.isNaN(n)) return 100;
return Math.min(100, Math.max(50, Math.round(n)));
}
export function readStripWidthPercent(
bookId: number,
usesGlobalCbxSettings: boolean,
userStripMaxWidthPercent: number | undefined | null,
userId?: number | null
): number {
if (usesGlobalCbxSettings) {
if (userStripMaxWidthPercent != null && !Number.isNaN(userStripMaxWidthPercent)) {
return clampStripMaxWidthPercent(userStripMaxWidthPercent);
}
return 100;
}
try {
let raw: string | null = null;
if (userId != null && userId > 0) {
raw = localStorage.getItem(stripWidthStorageKey(bookId, userId));
if (raw == null) {
raw = localStorage.getItem(LEGACY_STRIP_WIDTH_BOOK_PREFIX + bookId);
}
} else {
raw = localStorage.getItem(LEGACY_STRIP_WIDTH_BOOK_PREFIX + bookId);
}
if (raw == null) return 100;
return clampStripMaxWidthPercent(parseInt(raw, 10));
} catch {
return 100;
}
}
export function writeStripWidthPercentPerBook(
bookId: number,
value: number,
userId?: number | null
): void {
try {
localStorage.setItem(stripWidthStorageKey(bookId, userId), String(clampStripMaxWidthPercent(value)));
} catch {
/* quota / private mode */
}
}
export function shouldOfferWebtoonHint(bookId: number): boolean {
try {
if (localStorage.getItem(WEBTOON_NEVER) === '1') return false;
if (sessionStorage.getItem(WEBTOON_SESSION_BOOK_PREFIX + bookId) === '1') return false;
return true;
} catch {
return true;
}
}
/** Hide webtoon suggestion until the browser tab/session ends (middle “not now” action). */
export function dismissWebtoonHintForSession(bookId: number): void {
try {
sessionStorage.setItem(WEBTOON_SESSION_BOOK_PREFIX + bookId, '1');
} catch {
/* sessionStorage unavailable */
}
}
export function dismissWebtoonHintForever(): void {
try {
localStorage.setItem(WEBTOON_NEVER, '1');
} catch {
/* ignore */
}
}
@@ -34,6 +34,18 @@
</div>
</div>
@if (showStripWidthControl) {
<div class="control">
<span id="cbx-quick-strip-width-label">{{ 'readerCbx.quickSettings.stripMaxWidth' | transloco }}</span>
<div class="control-right strip-width-row">
<input type="range" min="50" max="100" step="5" [value]="state().stripMaxWidthPercent"
(input)="onStripMaxWidthInput($event)" class="brightness-slider"
aria-labelledby="cbx-quick-strip-width-label" />
<span class="brightness-value">{{ state().stripMaxWidthPercent }}%</span>
</div>
</div>
}
<!-- Page View (only in paginated mode) -->
@if (isPaginated && !isPhonePortrait) {
<div class="control">
@@ -94,6 +94,12 @@ $transition-normal: 200ms ease;
gap: 10px;
}
.strip-width-row {
flex: 1;
min-width: 0;
justify-content: flex-end;
}
.mode-label {
font-size: 12px;
color: $text-secondary;
@@ -51,8 +51,8 @@ export class CbxQuickSettingsComponent {
get scrollModeOptions(): { value: CbxScrollMode, label: string }[] {
return [
{ value: CbxScrollMode.PAGINATED, label: this.t.translate('readerCbx.quickSettings.paginated') },
{ value: CbxScrollMode.INFINITE, label: this.t.translate('readerCbx.quickSettings.infinite') }
// { value: CbxScrollMode.LONG_STRIP, label: this.t.translate('readerCbx.quickSettings.longStrip') }
{ value: CbxScrollMode.INFINITE, label: this.t.translate('readerCbx.quickSettings.infinite') },
{ value: CbxScrollMode.LONG_STRIP, label: this.t.translate('readerCbx.quickSettings.longStrip') }
];
}
@@ -99,6 +99,17 @@ export class CbxQuickSettingsComponent {
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
}
get showStripWidthControl(): boolean {
if (this.isPhonePortrait) return false;
const m = this.state().scrollMode;
return m === CbxScrollMode.INFINITE || m === CbxScrollMode.LONG_STRIP;
}
onStripMaxWidthInput(event: Event): void {
const value = +(event.target as HTMLInputElement).value;
this.quickSettingsService.setStripMaxWidthPercent(value);
}
get currentScrollModeLabel(): string {
return this.scrollModeOptions.find(o => o.value === this.state().scrollMode)?.label || this.t.translate('readerCbx.quickSettings.paginated');
}
@@ -28,6 +28,7 @@ describe('CbxQuickSettingsService', () => {
service.setMagnifierZoom(CbxMagnifierZoom.ZOOM_4X);
service.setMagnifierLensSize(CbxMagnifierLensSize.EXTRA_LARGE);
service.setBrightness(50);
service.setStripMaxWidthPercent(85);
service.setEmulateBook(true);
service.setClickToPaginate(true);
service.setAutoCloseMenu(true);
@@ -44,6 +45,7 @@ describe('CbxQuickSettingsService', () => {
magnifierZoom: CbxMagnifierZoom.ZOOM_4X,
magnifierLensSize: CbxMagnifierLensSize.EXTRA_LARGE,
brightness: 50,
stripMaxWidthPercent: 85,
emulateBook: true,
clickToPaginate: true,
autoCloseMenu: true
@@ -65,6 +67,7 @@ describe('CbxQuickSettingsService', () => {
magnifierZoom: CbxMagnifierZoom.ZOOM_3X,
magnifierLensSize: CbxMagnifierLensSize.MEDIUM,
brightness: 100,
stripMaxWidthPercent: 100,
emulateBook: false,
clickToPaginate: false,
autoCloseMenu: false
@@ -113,4 +116,15 @@ describe('CbxQuickSettingsService', () => {
expect(zoomEvents).toEqual([CbxMagnifierZoom.ZOOM_2X]);
expect(lensSizeEvents).toEqual([CbxMagnifierLensSize.LARGE]);
});
it('emits strip width changes when setStripMaxWidthPercent is called', () => {
const service = new CbxQuickSettingsService();
const stripEvents: number[] = [];
service.stripMaxWidthChange$.subscribe((v) => stripEvents.push(v));
service.setStripMaxWidthPercent(72);
expect(stripEvents).toEqual([72]);
expect(service.state().stripMaxWidthPercent).toBe(72);
});
});
@@ -1,6 +1,7 @@
import {Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {CbxBackgroundColor, CbxFitMode, CbxMagnifierLensSize, CbxMagnifierZoom, CbxPageSpread, CbxPageViewMode, CbxScrollMode, CbxReadingDirection, CbxSlideshowInterval} from '../../../../settings/user-management/user.service';
import {clampStripMaxWidthPercent} from '../../core/cbx-reader-storage';
export interface CbxQuickSettingsState {
fitMode: CbxFitMode;
@@ -13,6 +14,7 @@ export interface CbxQuickSettingsState {
magnifierZoom: CbxMagnifierZoom;
magnifierLensSize: CbxMagnifierLensSize;
brightness: number;
stripMaxWidthPercent: number;
emulateBook: boolean;
clickToPaginate: boolean;
autoCloseMenu: boolean;
@@ -31,6 +33,7 @@ export class CbxQuickSettingsService {
magnifierZoom: CbxMagnifierZoom.ZOOM_3X,
magnifierLensSize: CbxMagnifierLensSize.MEDIUM,
brightness: 100,
stripMaxWidthPercent: 100,
emulateBook: false,
clickToPaginate: false,
autoCloseMenu: false
@@ -81,6 +84,9 @@ export class CbxQuickSettingsService {
private _autoCloseMenuChange = new Subject<boolean>();
autoCloseMenuChange$ = this._autoCloseMenuChange.asObservable();
private _stripMaxWidthChange = new Subject<number>();
stripMaxWidthChange$ = this._stripMaxWidthChange.asObservable();
show(): void {
this._visible.set(true);
}
@@ -133,6 +139,12 @@ export class CbxQuickSettingsService {
this.updateState({brightness: value});
}
setStripMaxWidthPercent(value: number): void {
const v = clampStripMaxWidthPercent(value);
this.updateState({stripMaxWidthPercent: v});
this._stripMaxWidthChange.next(v);
}
setEmulateBook(value: boolean): void {
this.updateState({emulateBook: value});
}
@@ -94,6 +94,30 @@
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row strip-width-row">
<label class="setting-label" for="cbx-strip-max-width">{{ t('stripMaxWidth') }}</label>
<div class="strip-width-control">
<input
id="cbx-strip-max-width"
type="range"
min="50"
max="100"
step="5"
[value]="selectedCbxStripMaxWidthPercent"
(input)="onStripMaxWidthInput($event)"
[attr.aria-valuetext]="selectedCbxStripMaxWidthPercent + '%'"
/>
<span class="strip-width-value">{{ selectedCbxStripMaxWidthPercent }}%</span>
</div>
</div>
<p class="setting-description">
{{ t('stripMaxWidthDesc') }}
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
@@ -49,6 +49,26 @@
}
}
.strip-width-control {
display: flex;
align-items: center;
gap: 0.75rem;
flex: 1;
min-width: 0;
input[type='range'] {
flex: 1;
min-width: 120px;
max-width: 280px;
}
}
.strip-width-value {
font-size: 0.9rem;
color: var(--p-text-muted-color);
min-width: 2.75rem;
}
.setting-description {
color: var(--p-text-muted-color);
font-size: settings.$settings-section-description-size;
@@ -57,6 +57,7 @@ describe('CbxReaderPreferencesComponent', () => {
expect(component.selectedCbxFitMode).toBe(CbxFitMode.AUTO);
expect(component.selectedCbxScrollMode).toBe(CbxScrollMode.PAGINATED);
expect(component.selectedCbxBackgroundColor).toBe(CbxBackgroundColor.GRAY);
expect(component.selectedCbxStripMaxWidthPercent).toBe(100);
});
it('persists each CBX reader preference through the shared preferences service', () => {
@@ -74,4 +75,16 @@ describe('CbxReaderPreferencesComponent', () => {
expect(updatePreference).toHaveBeenNthCalledWith(4, ['cbxReaderSetting', 'scrollMode'], CbxScrollMode.INFINITE);
expect(updatePreference).toHaveBeenNthCalledWith(5, ['cbxReaderSetting', 'backgroundColor'], CbxBackgroundColor.BLACK);
});
it('persists strip max width with silent preference updates', () => {
const component = fixture.componentInstance;
component.selectedCbxStripMaxWidthPercent = 75;
expect(updatePreference).toHaveBeenCalledWith(
['cbxReaderSetting', 'stripMaxWidthPercent'],
75,
{ silent: true }
);
});
});
@@ -1,6 +1,7 @@
import {Component, inject, Input} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {TranslocoDirective} from '@jsverse/transloco';
import {clampStripMaxWidthPercent} from '../../../readers/cbx-reader/core/cbx-reader-storage';
import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, UserSettings} from '../../user-management/user.service';
import {ReaderPreferencesService} from '../reader-preferences.service';
import {TooltipModule} from 'primeng/tooltip';
@@ -27,6 +28,7 @@ export class CbxReaderPreferencesComponent {
private static readonly PROP_FIT_MODE = 'fitMode';
private static readonly PROP_SCROLL_MODE = 'scrollMode';
private static readonly PROP_BACKGROUND_COLOR = 'backgroundColor';
private static readonly PROP_STRIP_MAX_WIDTH_PERCENT = 'stripMaxWidthPercent';
readonly cbxSpreads = [
{name: 'Even', key: CbxPageSpread.EVEN, icon: 'pi pi-align-left', translationKey: 'even'},
@@ -102,4 +104,23 @@ export class CbxReaderPreferencesComponent {
this.userSettings.cbxReaderSetting.backgroundColor = value;
this.readerPreferencesService.updatePreference([CbxReaderPreferencesComponent.SETTING_ROOT, CbxReaderPreferencesComponent.PROP_BACKGROUND_COLOR], value);
}
get selectedCbxStripMaxWidthPercent(): number {
return clampStripMaxWidthPercent(this.userSettings.cbxReaderSetting.stripMaxWidthPercent);
}
set selectedCbxStripMaxWidthPercent(value: number) {
const v = clampStripMaxWidthPercent(value);
this.userSettings.cbxReaderSetting.stripMaxWidthPercent = v;
this.readerPreferencesService.updatePreference(
[CbxReaderPreferencesComponent.SETTING_ROOT, CbxReaderPreferencesComponent.PROP_STRIP_MAX_WIDTH_PERCENT],
v,
{ silent: true }
);
}
onStripMaxWidthInput(event: Event): void {
const input = event.target as HTMLInputElement;
this.selectedCbxStripMaxWidthPercent = Number(input.value);
}
}
@@ -21,7 +21,7 @@ export class ReaderPreferencesService {
});
}
updatePreference(path: string[], value: unknown): void {
updatePreference(path: string[], value: unknown, options?: { silent?: boolean }): void {
if (!this.currentUser) return;
let target = this.currentUser.userSettings as unknown as MutableSettingsBranch;
@@ -38,11 +38,13 @@ export class ReaderPreferencesService {
const updatedValue = this.currentUser.userSettings[rootKey as keyof UserSettings];
this.userService.updateUserSetting(this.currentUser.id, rootKey, updatedValue);
this.messageService.add({
severity: 'success',
summary: this.t.translate('settingsReader.toast.preferencesUpdated'),
detail: this.t.translate('settingsReader.toast.preferencesUpdatedDetail'),
life: 2000
});
if (!options?.silent) {
this.messageService.add({
severity: 'success',
summary: this.t.translate('settingsReader.toast.preferencesUpdated'),
detail: this.t.translate('settingsReader.toast.preferencesUpdatedDetail'),
life: 2000
});
}
}
}
@@ -210,6 +210,8 @@ export interface CbxReaderSetting {
emulateBook?: boolean;
clickToPaginate?: boolean;
autoCloseMenu?: boolean;
/** 50–100: max width % of reader for infinite / long-strip (global setting). */
stripMaxWidthPercent?: number;
}
export interface TableColumnPreference {
+12 -1
View File
@@ -114,7 +114,18 @@
"brightness": "Brightness",
"emulateBook": "Emulate Book",
"clickToPaginate": "Click to Paginate",
"autoCloseMenu": "Auto Close Menu"
"autoCloseMenu": "Auto Close Menu",
"stripMaxWidth": "Strip width"
},
"webtoonHint": {
"regionLabel": "Webtoon reading suggestion",
"message": "These pages look like a vertical webtoon. Long strip mode removes gaps and scrolls the whole chapter smoothly.",
"switch": "Use long strip",
"dismiss": "Hide for now",
"never": "Don't ask again"
},
"continuation": {
"scrollForNext": "Keep scrolling for the next book in this series"
},
"sidebar": {
"contentTab": "Content",
@@ -80,6 +80,8 @@
"fitModeDesc": "Select how images should be scaled to fit the reader window.",
"scrollMode": "Scroll Mode",
"scrollModeDesc": "Choose between paginated or infinite scroll reading experience.",
"stripMaxWidth": "Strip max width",
"stripMaxWidthDesc": "Maximum width for infinite scroll and long strip (percent of the reader). Narrower columns can make tall webtoon pages easier to read.",
"backgroundColor": "Background Color",
"backgroundColorDesc": "Set the background color for the comic reader.",
"even": "Even",
@@ -93,6 +95,7 @@
"automatic": "Automatic",
"paginated": "Paginated",
"infinite": "Infinite",
"longStrip": "Long Strip",
"gray": "Gray",
"black": "Black",
"white": "White"