From b69247e1db66e285770830f30a27f561b5ec80fe Mon Sep 17 00:00:00 2001 From: nkAnF Date: Sun, 4 Oct 2026 14:17:52 +0800 Subject: [PATCH 1/3] feat: add named held pages with conflict-safe saving Add accessible local names and notes with IME-safe editing, Unicode limits, legacy preservation and session-owned drafts. Compare workspace revisions atomically across tabs and preserve both scenes until an exact-version recovery choice. Retire obsolete reading intent across accepted scene replacement and verify metadata through competing saves. Co-authored-by: Codex --- README.md | 5 +- docs/specs/shared-contracts.md | 17 + playwright.config.ts | 6 +- src/app/App.tsx | 71 +++- .../held-pages/HeldPageMetadataEditor.tsx | 64 ++++ src/components/held-pages/HeldPagesPanel.tsx | 103 ++++- src/hooks/usePdfLinkNavigation.ts | 5 +- src/services/HeldReadTransaction.ts | 8 +- src/services/PersistenceService.ts | 44 ++- src/stores/heldStore.ts | 23 +- src/stores/windowStore.ts | 3 + src/stores/workspaceStore.ts | 143 ++++++- src/tests/e2e/README.md | 3 + src/tests/e2e/held-metadata.test.ts | 100 +++++ .../workspace-concurrency-responsive.test.ts | 235 ++++++++++++ src/tests/e2e/workspace-concurrency.test.ts | 355 ++++++++++++++++++ src/tests/ui/App.test.tsx | 14 +- src/tests/ui/HeldPageMetadata.test.tsx | 127 +++++++ src/tests/ui/HeldReadWorkflow.test.tsx | 121 ++++++ src/tests/ui/ReaderPdfLinks.test.tsx | 15 + src/tests/ui/hiddenWorkspaceSave.test.tsx | 32 +- src/tests/ui/readerActivationSave.test.tsx | 2 +- src/tests/ui/useUnsavedExitGuard.test.tsx | 2 +- src/tests/ui/workspaceConflict.test.tsx | 181 +++++++++ src/tests/unit/heldPageMetadata.test.ts | 65 ++++ src/tests/unit/heldReadTransaction.test.ts | 11 + src/tests/unit/logicStores.test.ts | 15 +- src/tests/unit/workspaceConcurrency.test.ts | 146 +++++++ src/tests/unit/workspaceConflictState.test.ts | 275 ++++++++++++++ src/tests/unit/workspaceExitState.test.ts | 12 +- src/types/domain.ts | 2 + src/utils/heldPageMetadata.ts | 20 + 32 files changed, 2139 insertions(+), 86 deletions(-) create mode 100644 src/components/held-pages/HeldPageMetadataEditor.tsx create mode 100644 src/tests/e2e/held-metadata.test.ts create mode 100644 src/tests/e2e/workspace-concurrency-responsive.test.ts create mode 100644 src/tests/e2e/workspace-concurrency.test.ts create mode 100644 src/tests/ui/HeldPageMetadata.test.tsx create mode 100644 src/tests/ui/workspaceConflict.test.tsx create mode 100644 src/tests/unit/heldPageMetadata.test.ts create mode 100644 src/tests/unit/workspaceConcurrency.test.ts create mode 100644 src/tests/unit/workspaceConflictState.test.ts create mode 100644 src/utils/heldPageMetadata.ts diff --git a/README.md b/README.md index 0235b3f..1a98142 100644 --- a/README.md +++ b/README.md @@ -107,11 +107,14 @@ npm run test:e2e - PDF 内部页码链接在点击所在的阅读窗口跳转;较慢的链接解析不会覆盖之后的翻页、同页选择或速翻操作。无法解析的链接会在原窗口提示,按 Esc 可关闭提示 - PDF 内部链接在原阅读窗口打开目标页,保留其他窗口的位置和缩放;用 Enter 跳到其他页后,可继续用方向键翻页。链接解析期间若已把焦点移到工具栏或其他窗口,不会把焦点抢回 - 最多新增到 12 张夹页,可通过上下移动按钮调整顺序;移除正在对照的夹页时可选择是否保留窗口 +- 夹页的铅笔按钮可编辑名称与备注,例如「定义」「证明」「图示」。名称最多 80 字、备注最多 500 字,留空名称恢复页码;点击「保存」后随阅读现场存到本机。取消或 Esc 不保存草稿,切换书籍、速翻、卡片/列表视图或侧栏/抽屉布局也会取消编辑,普通阅读页码或活动窗口变化会保留草稿;原 PDF 不受影响 - 点击左上角 LeafSpace 回到书库。切换书籍、回到书库前,会先保存当前现场 - 页码、缩放、夹页与窗口布局在操作停止后自动保存;切到后台时会尽早尝试保存待存更改。只有真正保存完成才显示「已保存到本机」。存储失败或上次现场未恢复时仍需明确重试,后台保存不能保证在系统结束进程前完成 - 有尚未保存的阅读更改、进行中或失败的保存、未保存的 PDF 时,刷新或关闭页面会请求浏览器离开确认;保存成功后不再提示。浏览器控制提示文字与显示条件,手机进程被结束时可能不会提示,请保留原 PDF - 若 PDF 本机副本保存失败,可继续阅读并「重试保存」;系统会先补存原 PDF,再保存最新现场,不会悄悄丢下无法重新打开的书籍 -- 若上次现场读取失败,切换书籍和返回书库不会覆盖它。可重试恢复;选择「保存现场」时需明确确认是否用当前现场替换 +- 若上次现场读取失败,切换书籍和返回书库不会覆盖它。可重试恢复;选择「保存现场」时需明确确认是否用当前现场替换。仍无法读取比较版本时不会盲目覆盖 +- 多个标签页打开同一本书时,保存会在同一存储事务中检查现场版本。检测到其他页的更改后,会保留本页尚未保存的页码、夹页和窗口,暂停自动保存与切换;可继续阅读,或明确选择「载入已存现场」「用此页覆盖」。取消不会改变任一现场,任一确认后若检测到其他页再次保存,仍会保留本页并重新提示冲突 +- 冲突期间请勿关闭仍有未存更改的标签页。载入会放弃本页未存现场,覆盖会替换检测到的已存现场,两者都需确认;原 PDF 不受影响。已打开的旧版页境仍可能使用旧保存方式,更新后请先保存并关闭或刷新旧版标签页 - 关闭错误提示后,顶部「查看问题」可重新打开原有说明和重试入口;查看说明不会自动重试或覆盖现场 - 若单页绘制失败,阅读区会显示「重试此页」;明确重试只重新绘制这一页,保留书籍、缩放、夹页与窗口现场,也可以直接翻到其他页继续阅读 - 最近列表展示 3 本书,但不会删除更早书籍的 PDF 或阅读现场;重新导入同一本 PDF 可恢复 diff --git a/docs/specs/shared-contracts.md b/docs/specs/shared-contracts.md index 5106331..639349d 100644 --- a/docs/specs/shared-contracts.md +++ b/docs/specs/shared-contracts.md @@ -189,6 +189,7 @@ unholdPage(pageNumber: number): void reorderHeldPages(fromIndex: number, toIndex: number): void markHeldPageOpen(pageNumber: number, windowId: string): void markHeldPageClosed(pageNumber: number, windowId: string): void +updatePageMetadata(id: string, generation: number, changes: Pick): boolean ``` ### 5.4 Window actions @@ -259,3 +260,19 @@ clearWorkspace(documentId: string): Promise - Pinch preview transforms pixels locally; release commits one clamped reader scale with the original paper point anchored to the ending midpoint. It never changes another window or the browser viewport scale. Existing 10–400% stored scale compatibility is retained. - Timeline pointer preview is transient and never enters book/window stores or autosave. A normal release commits once to the originating active window. Moving more than56px vertically from the starting track position marks release as cancel; moving back resumes preview. Escape/Space, lost capture, pointercancel, blur, book/window/overlay change cancel. Native range keyboard and independent change input remain available. - Chromium CDP native touch input and cross-engine DOM TouchEvent contracts are separate evidence categories. iPhone-sized WebKit emulation is not physical iOS testing. + +## Cross-tab workspace persistence + +- `WorkspaceSnapshot.revision?: string` is an opaque write identity. Existing v1/v2 snapshots remain readable without migration or PDF conversion. The comparison token includes the complete lightweight record to detect legacy writers, even with identical timestamps or reused/missing revisions. +- `PersistenceService.saveWorkspace(snapshot, expectedVersion)` returns the committed snapshot. Absence is represented by `null`; it never implies permission to replace an existing record. Read/compare/write and lightweight metadata commit share one IndexedDB readwrite transaction. A sidecar failure rolls back the snapshot too. Failed schema upgrades retain the existing read-only legacy fallback. +- An owned identical-content save returns the existing snapshot without changing timestamps, revision or metadata. A stale identical-content save still conflicts. PDF payloads are never rewritten by workspace saves. +- Each opening owns a mutable persistence cursor, separate from request generations and exit baselines. Queued same-opening saves read the cursor at execution and advance it only after transaction success. An earlier conflict halts subsequent queued requests. No BroadcastChannel event is required for correctness. +- A conflict preserves the stored snapshot and every live page, zoom, held-page and window state. It blocks auto/hidden saves and library/import transitions, survives alert dismissal, and retains the unsaved-exit warning. Ordinary Save only exposes resolution controls. +- Confirmed reload compares a fresh read to the exact detected version before replacing live state; another committed change refreshes conflict details and requires new confirmation. Read/validation failure preserves the live scene, including rollback after partial legacy-layout application. Confirmed overwrite is bound to the exact detected version; another committed change requires a new explicit decision. Cancellation changes neither scene. A confirmed reload immediately retires older link/held-read navigation while its read is pending; accepted same-page scene replacement also retires reference owners. Failed partial application restores content while metadata generations stay monotonic. +- A still-unread failed-restore replacement requires a successful comparison read before CAS; it never falls back to blind overwriting. Existing running pre-fix tabs cannot be forced to respect CAS. Modern code detects their subsequent changes; users should close or refresh older-version tabs before parallel reading. + +## Held-page metadata editing + +- Metadata edits patch only explicitly changed `customName`/`note` fields. Names normalize to one trimmed line (80 Unicode code points); notes retain interior newlines (500 code points). Blank fields clear the override. Invalid edits fail atomically; legacy fields are never truncated during read, cancel, restore, or an unrelated edit. +- `heldStore.metadataGeneration` is transient and advances only on reset/restore, not thumbnail, ordering, or linked-window changes. Metadata writes require the opening generation plus live held-page ID; App additionally checks the book's document/session and loading/restore ownership. Metadata uses the pre-existing saved fields; metadataGeneration never enters snapshots. +- The inline editor is a transient draft. Save/cancel are separate from navigation; starting editor pointer input disposes a pending held-read transaction and cancels long-press recognition. Enter/Escape during IME composition stay inside the editor. Escape cancels an ordinary draft before global reference/drawer closing. Document/session/replaced held-list, removed held-page, and temporary surface/layout interruptions retire the draft. Ordinary reader page/active-window changes, consulting another held card, reordering, and window blur preserve it, including a delayed source-owned PDF link resolution. Removing the edited page retires its draft; removing another page does not. diff --git a/playwright.config.ts b/playwright.config.ts index 24a7219..58c0c50 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -27,15 +27,15 @@ export default defineConfig({ }, { name: 'firefox', testIgnore: '**/native-touch.test.ts', use: { ...devices['Desktop Firefox'], viewport: { width: 1440, height: 900 } } }, { name: 'webkit', testIgnore: '**/native-touch.test.ts', use: { ...devices['Desktop Safari'], viewport: { width: 1440, height: 900 } } }, - { name: 'mobile-webkit', testMatch: ['**/gesture-contract.test.ts', '**/site-icons.test.ts', '**/storage-recovery.test.ts', '**/held-read-intent.test.ts', '**/thumbnail-actions.test.ts', '**/fit-width.test.ts', '**/password-recovery.test.ts', '**/hidden-save.test.ts', '**/recovery-access.test.ts', '**/reader-activation.test.ts', '**/mixed-pages.test.ts', '**/pdf-decoders.test.ts', '**/pdf-fonts.test.ts', '**/render-recovery.test.ts', '**/pdf-links.test.ts'], use: { ...devices['iPhone 13'] } }, + { name: 'mobile-webkit', testMatch: ['**/gesture-contract.test.ts', '**/site-icons.test.ts', '**/storage-recovery.test.ts', '**/held-read-intent.test.ts', '**/held-metadata.test.ts', '**/thumbnail-actions.test.ts', '**/fit-width.test.ts', '**/password-recovery.test.ts', '**/hidden-save.test.ts', '**/recovery-access.test.ts', '**/reader-activation.test.ts', '**/mixed-pages.test.ts', '**/pdf-decoders.test.ts', '**/pdf-fonts.test.ts', '**/render-recovery.test.ts', '**/pdf-links.test.ts'], use: { ...devices['iPhone 13'] } }, { name: 'tablet', - testMatch: ['**/responsive.test.ts', '**/native-touch.test.ts', '**/gesture-contract.test.ts', '**/site-icons.test.ts', '**/storage-recovery.test.ts', '**/held-read-intent.test.ts', '**/thumbnail-actions.test.ts', '**/fit-width.test.ts', '**/password-recovery.test.ts', '**/hidden-save.test.ts', '**/recovery-access.test.ts', '**/reader-activation.test.ts', '**/mixed-pages.test.ts', '**/pdf-decoders.test.ts', '**/pdf-fonts.test.ts', '**/render-recovery.test.ts', '**/pdf-links.test.ts'], + testMatch: ['**/responsive.test.ts', '**/native-touch.test.ts', '**/gesture-contract.test.ts', '**/site-icons.test.ts', '**/storage-recovery.test.ts', '**/held-read-intent.test.ts', '**/held-metadata.test.ts', '**/thumbnail-actions.test.ts', '**/fit-width.test.ts', '**/password-recovery.test.ts', '**/hidden-save.test.ts', '**/recovery-access.test.ts', '**/reader-activation.test.ts', '**/mixed-pages.test.ts', '**/pdf-decoders.test.ts', '**/pdf-fonts.test.ts', '**/render-recovery.test.ts', '**/pdf-links.test.ts'], use: { ...devices['Desktop Chrome'], viewport: { width: 768, height: 1024 }, hasTouch: true, launchOptions: executablePath ? { executablePath } : {} }, }, { name: 'mobile', - testMatch: ['**/responsive.test.ts', '**/native-touch.test.ts', '**/gesture-contract.test.ts', '**/site-icons.test.ts', '**/storage-recovery.test.ts', '**/held-read-intent.test.ts', '**/thumbnail-actions.test.ts', '**/fit-width.test.ts', '**/password-recovery.test.ts', '**/hidden-save.test.ts', '**/recovery-access.test.ts', '**/reader-activation.test.ts', '**/mixed-pages.test.ts', '**/pdf-decoders.test.ts', '**/pdf-fonts.test.ts', '**/render-recovery.test.ts', '**/pdf-links.test.ts'], + testMatch: ['**/responsive.test.ts', '**/native-touch.test.ts', '**/gesture-contract.test.ts', '**/site-icons.test.ts', '**/storage-recovery.test.ts', '**/held-read-intent.test.ts', '**/held-metadata.test.ts', '**/thumbnail-actions.test.ts', '**/fit-width.test.ts', '**/password-recovery.test.ts', '**/hidden-save.test.ts', '**/recovery-access.test.ts', '**/reader-activation.test.ts', '**/mixed-pages.test.ts', '**/pdf-decoders.test.ts', '**/pdf-fonts.test.ts', '**/render-recovery.test.ts', '**/pdf-links.test.ts'], use: { ...devices['Pixel 7'], viewport: { width: 390, height: 844 }, defaultBrowserType: 'chromium', launchOptions: executablePath ? { executablePath } : {} }, }, ], diff --git a/src/app/App.tsx b/src/app/App.tsx index f3e8620..3ebbdae 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -8,7 +8,7 @@ import { useBookStore } from '../stores/bookStore'; import { useHeldStore } from '../stores/heldStore'; import { useWindowStore } from '../stores/windowStore'; import { useQuickFlipStore } from '../stores/quickFlipStore'; -import { useWorkspaceStore } from '../stores/workspaceStore'; +import { useWorkspaceStore, type WorkspaceConflict } from '../stores/workspaceStore'; import { useUnsavedExitGuard } from '../hooks/useUnsavedExitGuard'; import { useWorkspaceAutoSave } from '../hooks/useWorkspaceAutoSave'; import { PDFPasswordRequiredError } from '../services/PDFService'; @@ -26,6 +26,13 @@ function isCurrentWorkspaceSaved(documentId: string | null) { && JSON.stringify(snapshot.windows) === JSON.stringify(windows); } +function conflictDescription(conflict: WorkspaceConflict): string { + const page = conflict.currentPage === null ? '页码未知' : `第 ${conflict.currentPage} 页`; + const saved = conflict.savedAt && Number.isFinite(Date.parse(conflict.savedAt)) + ? `,保存于 ${new Date(conflict.savedAt).toLocaleString('zh-CN')}` : ''; + return `检测到的已存现场:${page}${saved}。`; +} + // Disabled controls may be muted, but re-enabled text must regain its full // contrast immediately instead of fading through a readable-but-low-contrast state. const solidButton = 'inline-flex min-h-10 items-center justify-center gap-2 border border-stone-900 bg-stone-900 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-stone-700 disabled:cursor-not-allowed disabled:opacity-50'; @@ -34,7 +41,7 @@ const outlineButton = 'inline-flex min-h-10 items-center justify-center gap-2 bo function App() { const book = useBookStore(); const { currentPage, totalPages, documentId, documentName, sessionId, scale, status: bookStatus, loadDocument } = book; - const { pages: heldPages, holdPage, unholdPage, reset: resetHeldPages } = useHeldStore(); + const { pages: heldPages, metadataGeneration, updatePageMetadata, holdPage, unholdPage, reset: resetHeldPages } = useHeldStore(); const { windows, activeWindowId, navigateActive, setLayout, notice: windowNotice, clearNotice: clearWindowNotice, updateWindow, closeWindow, openInNewWindow, setActiveWindow, reset: resetWindows } = useWindowStore(); const { isOpen: isQuickFlipVisible, close: closeQuickFlip, open: openQuickFlip } = useQuickFlipStore(); const activePage = windows.find(window => window.id === activeWindowId)?.pageNumber ?? currentPage; @@ -46,6 +53,8 @@ function App() { const [dismissedError, setDismissedError] = useState(null); const [showHeldPages, setShowHeldPages] = useState(false); const [replaceDocumentId, setReplaceDocumentId] = useState(null); + const [conflictResolution, setConflictResolution] = useState<{ action: 'reload' | 'overwrite'; conflict: WorkspaceConflict } | null>(null); + const conflictOpener = useRef(null); const saveButtonRef = useRef(null); const problemButtonRef = useRef(null); const problemRef = useRef(null); @@ -92,6 +101,8 @@ function App() { || (workspaceStatus === 'saving' && workspace.unrestoredDocumentId === documentId); const thumbnailActions = useThumbnailActions(`${showHeldPages}:${busy}`); const ready = !!documentId && bookStatus === 'ready' && !busy; + const conflictNeedsConfirmation = conflictResolution && conflictResolution.conflict.documentId === documentId + && conflictResolution.conflict.sessionId === sessionId && workspace.conflict?.version === conflictResolution.conflict.version; const replacementNeedsConfirmation = replaceDocumentId === documentId && !!documentId && workspace.unrestoredDocumentId === documentId; const flushWorkspace = useCallback(async (id: string) => { // A late scroll/render event may settle while the first write is pending. @@ -117,7 +128,9 @@ function App() { const previousBook = useBookStore.getState(); if (previousBook.documentId && previousBook.status === 'ready') { if (!await flushWorkspace(previousBook.documentId)) { - setWorkflowError(useWorkspaceStore.getState().unrestoredDocumentId === previousBook.documentId + setWorkflowError(useWorkspaceStore.getState().conflict + ? useWorkspaceStore.getState().error + : useWorkspaceStore.getState().unrestoredDocumentId === previousBook.documentId ? '上次阅读现场尚未恢复,已暂停切换书籍。请先重试恢复,或点击「保存现场」确认替换。' : '当前阅读现场未能保存,已暂停切换书籍。请重试保存后再导入,避免丢失刚才的更改。'); return; @@ -154,17 +167,23 @@ function App() { heldPages: useHeldStore.getState().pages, windows: currentWindows.windows, activeWindowId: currentWindows.activeWindowId, enabled: !importLock.current && currentBook.status === 'ready' && currentWorkspace.status === 'idle' - && currentWorkspace.unrestoredDocumentId !== currentBook.documentId, + && currentWorkspace.unrestoredDocumentId !== currentBook.documentId && !currentWorkspace.conflict, }; }, []); useWorkspaceAutoSave({ documentId, sessionId, currentPage, scale, heldPages, windows, activeWindowId, - enabled: ready && workspaceStatus === 'idle' && workspace.unrestoredDocumentId !== documentId, + enabled: ready && workspaceStatus === 'idle' && workspace.unrestoredDocumentId !== documentId && !workspace.conflict, currentSnapshot: workspace.currentSnapshot, readCurrent: readAutoSaveState, saveWorkspace }); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (thumbnailActions.controller.ownsInput() || busy || event.defaultPrevented || event.repeat || event.altKey || event.ctrlKey || event.metaKey) return; if (event.key === 'Escape' && !isQuickFlipVisible) { + if (conflictNeedsConfirmation) { + event.preventDefault(); + setConflictResolution(null); + conflictOpener.current?.focus(); + return; + } if (replacementNeedsConfirmation) { event.preventDefault(); setReplaceDocumentId(null); @@ -195,7 +214,7 @@ function App() { }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); - }, [thumbnailActions.controller, ready, busy, isQuickFlipVisible, activePage, showQuickFlip, dismissQuickFlip, showHeldPages, replacementNeedsConfirmation]); + }, [thumbnailActions.controller, ready, busy, isQuickFlipVisible, activePage, showQuickFlip, dismissQuickFlip, showHeldPages, replacementNeedsConfirmation, conflictNeedsConfirmation]); const returnToLibrary = async () => { if (!ready || importLock.current) return; @@ -256,9 +275,19 @@ function App() { }; const requestSave = () => { if (!documentId) return; - if (workspace.unrestoredDocumentId === documentId) setReplaceDocumentId(documentId); + if (workspace.conflict) { setWorkflowError(null); setDismissedError(null); } + else if (workspace.unrestoredDocumentId === documentId) setReplaceDocumentId(documentId); else void saveWorkspace(documentId); }; + const requestConflictResolution = (action: 'reload' | 'overwrite', opener: HTMLElement) => { + if (!workspace.conflict) return; + conflictOpener.current = opener; + setConflictResolution({ action, conflict: workspace.conflict }); + }; + const closeConflictConfirmation = () => { + setConflictResolution(null); + conflictOpener.current?.focus(); + }; const closeReplaceConfirmation = () => { setReplaceDocumentId(null); saveButtonRef.current?.focus(); @@ -297,10 +326,28 @@ function App() { } + {conflictNeedsConfirmation && conflictResolution && documentId &&
{ + if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeConflictConfirmation(); } + }} className="flex shrink-0 flex-wrap items-center gap-3 border-b border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-950"> +

{conflictDescription(conflictResolution.conflict)}{conflictResolution.action === 'reload' + ? '载入检测到的已存现场会替换此标签页尚未保存的页码、夹页(含名称和备注)和窗口布局。此页更改将丢失;原 PDF 不受影响。若已存现场再次变化,会保留此页并重新提示。' + : '将用此页当前的页码、夹页(含名称和备注)和窗口布局覆盖检测到的已存现场。已存现场将被替换;原 PDF 不受影响。若其他标签页再次保存,仍会暂停并提示。'}

+ + +
} + {problemVisible && } @@ -360,7 +407,11 @@ function App() { {documentId &&