From b277abff87dce8655479f6983e05a77902ab49d5 Mon Sep 17 00:00:00 2001 From: Taki Date: Mon, 16 Nov 2026 09:53:07 +0700 Subject: [PATCH 1/4] feat(state): implement NavigationHistory data structure for reading stack --- src/state-manager.ts | 79 +++++++++++++++++++++++++++++++++++++++++++ test/history.test.mjs | 51 ++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 test/history.test.mjs diff --git a/src/state-manager.ts b/src/state-manager.ts index a4121d8..31adce0 100644 --- a/src/state-manager.ts +++ b/src/state-manager.ts @@ -14,6 +14,85 @@ export interface ReadingLocation { timestamp: number; } +export interface HistoryLocation { + uri: string; + chapterTitle?: string; + scrollY: number; + scrollRatio: number; + anchorId?: string; + isPaginated?: boolean; +} + +export class NavigationHistory { + private backStack: HistoryLocation[] = []; + private forwardStack: HistoryLocation[] = []; + private readonly maxDepth: number; + + constructor(maxDepth = 50) { + this.maxDepth = maxDepth; + } + + push(location: HistoryLocation): void { + this.backStack.push(location); + if (this.backStack.length > this.maxDepth) { + this.backStack.shift(); + } + // When a new jump occurs, clear forward stack + this.forwardStack = []; + } + + canGoBack(): boolean { + return this.backStack.length > 0; + } + + canGoForward(): boolean { + return this.forwardStack.length > 0; + } + + peekBack(): HistoryLocation | undefined { + return this.backStack.length > 0 ? this.backStack[this.backStack.length - 1] : undefined; + } + + peekForward(): HistoryLocation | undefined { + return this.forwardStack.length > 0 ? this.forwardStack[this.forwardStack.length - 1] : undefined; + } + + goBack(currentLocation: HistoryLocation): HistoryLocation | undefined { + const target = this.backStack.pop(); + if (target) { + this.forwardStack.push(currentLocation); + if (this.forwardStack.length > this.maxDepth) { + this.forwardStack.shift(); + } + } + return target; + } + + goForward(currentLocation: HistoryLocation): HistoryLocation | undefined { + const target = this.forwardStack.pop(); + if (target) { + this.backStack.push(currentLocation); + if (this.backStack.length > this.maxDepth) { + this.backStack.shift(); + } + } + return target; + } + + clear(): void { + this.backStack = []; + this.forwardStack = []; + } + + getBackCount(): number { + return this.backStack.length; + } + + getForwardCount(): number { + return this.forwardStack.length; + } +} + export interface MementoLike { get(key: string, defaultValue?: T): T; update(key: string, value: unknown): Thenable | Promise; diff --git a/test/history.test.mjs b/test/history.test.mjs new file mode 100644 index 0000000..393d642 --- /dev/null +++ b/test/history.test.mjs @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +test('NavigationHistory pushes, peeks, and respects max depth', async () => { + const { NavigationHistory } = await import('../dist/state-manager.js'); + const history = new NavigationHistory(3); + + assert.equal(history.canGoBack(), false); + assert.equal(history.canGoForward(), false); + + history.push({ uri: 'chapter1.xhtml', chapterTitle: 'Chapter 1', scrollY: 100, scrollRatio: 0.1 }); + history.push({ uri: 'chapter2.xhtml', chapterTitle: 'Chapter 2', scrollY: 200, scrollRatio: 0.2 }); + history.push({ uri: 'chapter3.xhtml', chapterTitle: 'Chapter 3', scrollY: 300, scrollRatio: 0.3 }); + + assert.equal(history.canGoBack(), true); + assert.equal(history.getBackCount(), 3); + assert.equal(history.peekBack()?.uri, 'chapter3.xhtml'); + + // Push 4th item beyond capacity 3 -> oldest (chapter1) pruned + history.push({ uri: 'chapter4.xhtml', chapterTitle: 'Chapter 4', scrollY: 400, scrollRatio: 0.4 }); + assert.equal(history.getBackCount(), 3); + + // Navigate back to chapter 3 + const currentLoc = { uri: 'chapter5.xhtml', chapterTitle: 'Chapter 5', scrollY: 500, scrollRatio: 0.5 }; + const back1 = history.goBack(currentLoc); + assert.equal(back1?.uri, 'chapter4.xhtml'); + assert.equal(history.canGoForward(), true); + assert.equal(history.peekForward()?.uri, 'chapter5.xhtml'); + + // Navigate forward again + const fwd = history.goForward({ uri: 'chapter4.xhtml', chapterTitle: 'Chapter 4', scrollY: 400, scrollRatio: 0.4 }); + assert.equal(fwd?.uri, 'chapter5.xhtml'); +}); + +test('NavigationHistory clears forward stack on new push and clears all on clear()', async () => { + const { NavigationHistory } = await import('../dist/state-manager.js'); + const history = new NavigationHistory(); + + history.push({ uri: 'chapter1.xhtml', chapterTitle: 'Chapter 1', scrollY: 100, scrollRatio: 0.1 }); + history.goBack({ uri: 'chapter2.xhtml', chapterTitle: 'Chapter 2', scrollY: 200, scrollRatio: 0.2 }); + assert.equal(history.canGoForward(), true); + + // New push should reset forward stack + history.push({ uri: 'chapter3.xhtml', chapterTitle: 'Chapter 3', scrollY: 300, scrollRatio: 0.3 }); + assert.equal(history.canGoForward(), false); + + history.clear(); + assert.equal(history.canGoBack(), false); + assert.equal(history.canGoForward(), false); + assert.equal(history.getBackCount(), 0); +}); From d44544e6f851966acfe25a07921cc24ef414f69a Mon Sep 17 00:00:00 2001 From: Taki Date: Mon, 16 Nov 2026 09:58:58 +0700 Subject: [PATCH 2/4] feat(reader): implement reading navigation history stack and return-to-reading pill --- src/extension.ts | 125 +++++++++++++++++++++- src/reader-shell.ts | 209 ++++++++++++++++++++++++++++++++++++- src/state-manager.ts | 1 + test/reader-shell.test.mjs | 21 ++++ 4 files changed, 346 insertions(+), 10 deletions(-) diff --git a/src/extension.ts b/src/extension.ts index b37490d..15e47b2 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -4,7 +4,7 @@ import * as path from 'node:path'; import { sanitizeXhtml, extractElementById } from './xhtml'; import { readerShell, ReaderNavInfo } from './reader-shell'; import { locateEpubContainer, parseContainerXml, parseOpfXml, loadEpubToc, EpubPackage } from './epub'; -import { StateManager, ReaderPreferences } from './state-manager'; +import { StateManager, ReaderPreferences, NavigationHistory, ReadingLocation } from './state-manager'; import { EpubCacheManager, ArchiveSecurityError, ArchiveCorruptError } from './archive'; const supportedExtensions = new Set(['.xhtml', '.html', '.htm', '.epub']); @@ -200,9 +200,10 @@ async function attachReaderToWebview( panel.webview.options = { enableScripts: true, localResourceRoots }; + const navigationHistory = new NavigationHistory(); let timer: NodeJS.Timeout | undefined; - const render = async (resetToTop = false, startAtBottom = false): Promise => { + const render = async (resetToTop = false, startAtBottom = false, targetLocation?: ReadingLocation): Promise => { try { const xhtml = await readSource(currentSource); const chapterDir = parentUri(currentSource); @@ -225,6 +226,13 @@ async function attachReaderToWebview( }; }); + const peek = navigationHistory.peekBack(); + const historyBackInfo = peek ? { + canGoBack: true, + chapterTitle: peek.chapterTitle, + scrollRatio: peek.scrollRatio + } : undefined; + const navInfo: ReaderNavInfo = { hasPrev: spineIndex > 0, hasNext: spineIndex >= 0 && spineIndex < (epubPackage?.spine.length ?? 0) - 1, @@ -232,12 +240,13 @@ async function attachReaderToWebview( creator: epubPackage?.creator, chapterIndex: spineIndex >= 0 ? spineIndex + 1 : undefined, totalChapters: epubPackage?.spine.length, - toc: tocWithActive + toc: tocWithActive, + historyBackInfo }; panel.title = getPanelTitle(currentSource, epubPackage); const preferences = stateManager?.getPreferences(); - const location = (resetToTop || startAtBottom) ? undefined : stateManager?.getReadingLocation(currentSource.toString()); + const location = targetLocation || ((resetToTop || startAtBottom) ? undefined : stateManager?.getReadingLocation(currentSource.toString())); panel.webview.html = readerShell(content, currentSource, pendingFragment, panel.webview, navInfo, preferences, location, resetToTop, startAtBottom); pendingFragment = undefined; } catch (error) { @@ -352,10 +361,71 @@ async function attachReaderToWebview( if (isOpenLinkMessage(message)) { const target = resolveChapterLink(message.href, currentSource, watchRoot, epubPackage?.opfDir); if (target) { + const chapterTitle = getChapterTitle(currentSource, epubPackage); + const pos = message.currentPosition || stateManager?.getReadingLocation(currentSource.toString()) || { scrollY: 0, scrollRatio: 0 }; + navigationHistory.push({ + uri: currentSource.toString(), + chapterTitle, + scrollY: pos.scrollY, + scrollRatio: pos.scrollRatio, + isPaginated: Boolean(pos.isPaginated) + }); + currentSource = target.source; pendingFragment = target.fragment; void render(!target.fragment); } + return; + } + + if (isHistoryBackMessage(message)) { + if (navigationHistory.canGoBack()) { + const chapterTitle = getChapterTitle(currentSource, epubPackage); + const pos = message.currentPosition || stateManager?.getReadingLocation(currentSource.toString()) || { scrollY: 0, scrollRatio: 0 }; + const prev = navigationHistory.goBack({ + uri: currentSource.toString(), + chapterTitle, + scrollY: pos.scrollY, + scrollRatio: pos.scrollRatio, + isPaginated: Boolean(pos.isPaginated) + }); + if (prev) { + currentSource = vscode.Uri.parse(prev.uri); + pendingFragment = prev.anchorId; + void render(false, false, { + scrollY: prev.scrollY, + scrollRatio: prev.scrollRatio, + anchorId: prev.anchorId, + timestamp: Date.now() + }); + } + } + return; + } + + if (isHistoryForwardMessage(message)) { + if (navigationHistory.canGoForward()) { + const chapterTitle = getChapterTitle(currentSource, epubPackage); + const pos = message.currentPosition || stateManager?.getReadingLocation(currentSource.toString()) || { scrollY: 0, scrollRatio: 0 }; + const next = navigationHistory.goForward({ + uri: currentSource.toString(), + chapterTitle, + scrollY: pos.scrollY, + scrollRatio: pos.scrollRatio, + isPaginated: Boolean(pos.isPaginated) + }); + if (next) { + currentSource = vscode.Uri.parse(next.uri); + pendingFragment = next.anchorId; + void render(false, false, { + scrollY: next.scrollY, + scrollRatio: next.scrollRatio, + anchorId: next.anchorId, + timestamp: Date.now() + }); + } + } + return; } }); @@ -369,6 +439,7 @@ async function attachReaderToWebview( if (timer) { clearTimeout(timer); } + navigationHistory.clear(); watcher.dispose(); documentChange.dispose(); messageSubscription.dispose(); @@ -390,6 +461,28 @@ function getPanelTitle(source: vscode.Uri, epub?: EpubPackage): string { return `${epub.title} — ${fileName}`; } +function getChapterTitle(source: vscode.Uri, epub?: EpubPackage): string { + const fileName = source.path.slice(source.path.lastIndexOf('/') + 1); + if (epub) { + const currentPath = source.path.toLowerCase(); + const tocMatch = epub.toc.find((item) => item.uri.path.toLowerCase() === currentPath); + if (tocMatch && tocMatch.label) { + return tocMatch.label; + } + const spineIdx = epub.spine.findIndex((item) => item.uri.path.toLowerCase() === currentPath); + if (spineIdx >= 0) { + return `Chapter ${spineIdx + 1}`; + } + } + return fileName; +} + +export interface ReadingPositionPayload { + scrollY: number; + scrollRatio: number; + isPaginated?: boolean; +} + function isPrevChapterMessage(message: unknown): message is { type: 'prevChapter'; startAtBottom?: boolean } { return typeof message === 'object' && message !== null && (message as { type?: unknown }).type === 'prevChapter'; } @@ -398,13 +491,35 @@ function isNextChapterMessage(message: unknown): message is { type: 'nextChapter return typeof message === 'object' && message !== null && (message as { type?: unknown }).type === 'nextChapter'; } -function isOpenLinkMessage(message: unknown): message is { type: 'openLink'; href: string } { +function isOpenLinkMessage(message: unknown): message is { + type: 'openLink'; + href: string; + currentPosition?: ReadingPositionPayload; +} { return typeof message === 'object' && message !== null && (message as { type?: unknown }).type === 'openLink' && typeof (message as { href?: unknown }).href === 'string'; } +function isHistoryBackMessage(message: unknown): message is { + type: 'historyBack'; + currentPosition?: ReadingPositionPayload; +} { + return typeof message === 'object' + && message !== null + && (message as { type?: unknown }).type === 'historyBack'; +} + +function isHistoryForwardMessage(message: unknown): message is { + type: 'historyForward'; + currentPosition?: ReadingPositionPayload; +} { + return typeof message === 'object' + && message !== null + && (message as { type?: unknown }).type === 'historyForward'; +} + function isRequestFootnoteMessage(message: unknown): message is { type: 'requestFootnote'; href: string; diff --git a/src/reader-shell.ts b/src/reader-shell.ts index 9cd6c69..89a77e7 100644 --- a/src/reader-shell.ts +++ b/src/reader-shell.ts @@ -8,6 +8,12 @@ export interface ReaderTocItem { active?: boolean; } +export interface HistoryBackInfo { + canGoBack: boolean; + chapterTitle?: string; + scrollRatio?: number; +} + export interface ReaderNavInfo { hasPrev?: boolean; hasNext?: boolean; @@ -16,6 +22,7 @@ export interface ReaderNavInfo { chapterIndex?: number; totalChapters?: number; toc?: ReaderTocItem[]; + historyBackInfo?: HistoryBackInfo; } const fontCssMap: Record = { @@ -64,6 +71,7 @@ const PHOSPHOR = { slidersHorizontal: ``, dotsThree: ``, bookmarkSimple: ``, + arrowUUpLeft: ``, x: `` }; @@ -904,6 +912,110 @@ export function readerShell( display: none !important; } + /* Floating Return to Reading Position Pill */ + .history-return-pill { + position: fixed; + bottom: 2rem; + left: 2rem; + z-index: 90; + display: flex; + align-items: center; + gap: 0.35rem; + padding: 0.35rem 0.5rem 0.35rem 0.75rem; + background: var(--popover-bg); + color: var(--popover-fg); + border: 1px solid var(--popover-border); + border-radius: 9999px; + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.25), 0 8px 10px -6px rgba(0, 0, 0, 0.2); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.2s ease, visibility 0.2s; + animation: pillSlideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1); + user-select: none; + } + .history-return-pill.minimized { + opacity: 0.45; + transform: translateY(6px) scale(0.96); + } + .history-return-pill.minimized:hover { + opacity: 1; + transform: translateY(0) scale(1); + } + .history-return-pill.hidden { + display: none !important; + } + @keyframes pillSlideIn { + from { + opacity: 0; + transform: translateY(16px) scale(0.95); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } + } + .history-return-btn { + display: inline-flex; + align-items: center; + gap: 0.5rem; + background: transparent !important; + border: none !important; + color: inherit !important; + font-size: 0.8125rem; + font-weight: 500; + cursor: pointer; + padding: 0.25rem 0.35rem; + line-height: 1.2; + } + .history-return-btn:hover { + color: var(--reader-link) !important; + } + .history-return-icon { + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--reader-link); + } + .history-return-text { + display: inline-flex; + align-items: center; + gap: 0.4rem; + max-width: 280px; + } + .history-return-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .history-return-pct { + font-size: 0.75rem; + padding: 0.1rem 0.35rem; + border-radius: 9999px; + background: rgba(156, 163, 175, 0.15); + color: var(--popover-fg); + font-variant-numeric: tabular-nums; + } + .history-return-close { + display: inline-flex; + align-items: center; + justify-content: center; + background: transparent !important; + border: none !important; + color: #94a3b8 !important; + cursor: pointer; + padding: 0.2rem; + border-radius: 50%; + font-size: 1rem; + line-height: 1; + width: 1.35rem; + height: 1.35rem; + transition: background 0.15s ease, color 0.15s ease; + } + .history-return-close:hover { + background: rgba(156, 163, 175, 0.2) !important; + color: var(--popover-fg) !important; + } + /* Light Theme */ .light { --reader-bg: #f8fafc; @@ -1039,7 +1151,7 @@ export function readerShell( } - +
@@ -1158,6 +1270,19 @@ export function readerShell(
+ ${navInfo?.historyBackInfo?.canGoBack ? ` + + ` : ''} +