diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml
index 8fe9e5a..e813d47 100644
--- a/.github/workflows/quality.yml
+++ b/.github/workflows/quality.yml
@@ -28,7 +28,9 @@ jobs:
- run: npm run test:ui
browser-tests:
runs-on: ubuntu-latest
- timeout-minutes: 20
+ # The single-worker WebKit matrix includes mobile and stability repeats.
+ # Keep every check and per-test deadline while allowing normal runner variance.
+ timeout-minutes: 30
strategy:
fail-fast: false
matrix:
diff --git a/README.md b/README.md
index 353c84a..0235b3f 100644
--- a/README.md
+++ b/README.md
@@ -104,6 +104,8 @@ npm run test:e2e
- 浮窗拖动、缩放和分栏调整在失焦、切换标签页或松开鼠标时结束;拖动中按 Esc 只取消本次拖动,不关闭窗口
- 最多新建 4 个参考窗口。可选择并排或平铺 2–5 页;手机通过「打开的页面」切换主视角与参考页
- 速翻、目录、底部时间轴和页码输入跟随当前活动窗口。页码输入按 Enter 确认,Esc 取消
+- PDF 内部页码链接在点击所在的阅读窗口跳转;较慢的链接解析不会覆盖之后的翻页、同页选择或速翻操作。无法解析的链接会在原窗口提示,按 Esc 可关闭提示
+- PDF 内部链接在原阅读窗口打开目标页,保留其他窗口的位置和缩放;用 Enter 跳到其他页后,可继续用方向键翻页。链接解析期间若已把焦点移到工具栏或其他窗口,不会把焦点抢回
- 最多新增到 12 张夹页,可通过上下移动按钮调整顺序;移除正在对照的夹页时可选择是否保留窗口
- 点击左上角 LeafSpace 回到书库。切换书籍、回到书库前,会先保存当前现场
- 页码、缩放、夹页与窗口布局在操作停止后自动保存;切到后台时会尽早尝试保存待存更改。只有真正保存完成才显示「已保存到本机」。存储失败或上次现场未恢复时仍需明确重试,后台保存不能保证在系统结束进程前完成
diff --git a/playwright.config.ts b/playwright.config.ts
index 83d0e92..24a7219 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'], 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', '**/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'],
+ 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'],
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'],
+ 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'],
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 0dc4bc6..f3e8620 100644
--- a/src/app/App.tsx
+++ b/src/app/App.tsx
@@ -13,6 +13,7 @@ import { useUnsavedExitGuard } from '../hooks/useUnsavedExitGuard';
import { useWorkspaceAutoSave } from '../hooks/useWorkspaceAutoSave';
import { PDFPasswordRequiredError } from '../services/PDFService';
import { prepareHeldRead } from '../services/HeldReadTransaction';
+import { notifyReaderNavigation } from '../services/readerNavigationIntent';
import { useThumbnailActions } from '../hooks/useThumbnailActions';
import { ThumbnailActionDialog } from '../components/thumbnails/ThumbnailActionDialog';
@@ -25,8 +26,10 @@ function isCurrentWorkspaceSaved(documentId: string | null) {
&& JSON.stringify(snapshot.windows) === JSON.stringify(windows);
}
-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 hover:bg-stone-700 disabled:cursor-not-allowed disabled:opacity-50';
-const outlineButton = 'inline-flex min-h-10 items-center justify-center gap-2 border border-[var(--border)] px-3 py-2 text-sm font-medium text-stone-700 transition hover:border-stone-700 hover:bg-stone-100 disabled:cursor-not-allowed disabled:opacity-50';
+// 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';
+const outlineButton = 'inline-flex min-h-10 items-center justify-center gap-2 border border-[var(--border)] px-3 py-2 text-sm font-medium text-stone-700 transition-colors hover:border-stone-700 hover:bg-stone-100 disabled:cursor-not-allowed disabled:opacity-50';
function App() {
const book = useBookStore();
@@ -318,7 +321,15 @@ function App() {
{(windowNotice || heldNotice) &&
{windowNotice || heldNotice}
}
- {documentId ? { updateWindow(win.id, win); if (win.isActive) setActiveWindow(win.id); }} onWindowClose={closeReferenceWindow} /> : (
+ {documentId ? {
+ // Canvas callbacks carry the full window for layout operations.
+ // Do not turn a raise/drag/resize into a new page choice or replay
+ // a stale paper viewport while applying that geometry.
+ updateWindow(win.id, { x: win.x, y: win.y, width: win.width, height: win.height,
+ type: win.type, dockMode: win.dockMode, splitRatio: win.splitRatio,
+ zIndex: win.zIndex, isActive: win.isActive });
+ if (win.isActive) setActiveWindow(win.id);
+ }} onWindowClose={closeReferenceWindow} /> : (
@@ -363,7 +374,7 @@ function App() {
}} onPageClick={(page) => { openInNewWindow(page.pageNumber); closeHeldPanel(); }} onRemovePage={(id, closeReferences) => { const page = heldPages.find((candidate) => candidate.id === id); if (page) { if (closeReferences) useWindowStore.getState().closeWindowsForPage(page.pageNumber); unholdPage(page.pageNumber); } }} />
}
- {documentId && }
+ {documentId && }
{isQuickFlipVisible && ready &&
{ updateWindow(quickFlipOrigin.current.windowId, { pageNumber: page }); setActiveWindow(quickFlipOrigin.current.windowId); }} />}
{thumbnailActions.request && }
diff --git a/src/components/reader/ReaderViewport.tsx b/src/components/reader/ReaderViewport.tsx
index a1e817f..71eaa43 100644
--- a/src/components/reader/ReaderViewport.tsx
+++ b/src/components/reader/ReaderViewport.tsx
@@ -8,6 +8,7 @@ import { useWindowStore } from '../../stores/windowStore';
import { useQuickFlipStore } from '../../stores/quickFlipStore';
import { pdfCMapAssetsUrl, pdfDecoderAssetsUrl, pdfStandardFontAssetsUrl } from '../../services/pdfDecoderAssets';
import { useReaderGestures } from '../../hooks/useReaderGestures';
+import { usePdfLinkNavigation } from '../../hooks/usePdfLinkNavigation';
import { MousePointer2, Hand, ZoomIn, ZoomOut, ChevronLeft, ChevronRight, RotateCcw } from 'lucide-react';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';
@@ -71,6 +72,7 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
const containerRef = useRef(null);
const contentFrameRef = useRef(null);
+ const pageElementRef = useRef(null);
const [isPanning, setIsPanning] = useState(false);
const panGestureActive = useRef(false);
const [shouldCenterHorizontally, setShouldCenterHorizontally] = useState(true);
@@ -93,6 +95,9 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
renderGeneration.current += 1;
};
}, []);
+ const pdfLinks = usePdfLinkNavigation({ sessionId, documentUrl, windowId: windowId ?? 'main',
+ pageNumber: activePage, attempt: retryAttempt, containerRef, pageRef: pageElementRef });
+ const cancelPdfLinks = pdfLinks.cancel;
const [renderFeedback, setRenderFeedback] = useState(null);
const showRenderFailure = renderFeedback?.kind === 'failed' && renderFeedback.token === renderToken;
const showRenderRetry = renderFeedback?.kind === 'retrying' && renderFeedback.context === renderContext && renderFeedback.attempt === retryAttempt;
@@ -381,13 +386,14 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
if (zoomCorrectionFrame.current !== null) window.cancelAnimationFrame(zoomCorrectionFrame.current);
zoomCorrectionFrame.current = null;
renderReady.current = false;
+ cancelPdfLinks();
const attempt = ++requestedAttempt.current;
// Supersede old callbacks now, not only after React commits the new Page.
currentRenderToken.current = null;
containerRef.current?.focus({ preventScroll: true });
setRenderFeedback({ kind: 'retrying', context: renderContext, attempt });
setRetryAttempt(attempt);
- }, [cancelPanning, cancelZoom, captureScrollIntent, renderContext, renderFeedback]);
+ }, [cancelPanning, cancelPdfLinks, cancelZoom, captureScrollIntent, renderContext, renderFeedback]);
useEffect(() => {
const container = containerRef.current;
@@ -618,7 +624,7 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
if (quickFlipVisible || activeWindowId !== (windowId ?? 'main')) cancelZoom();
}, [activeWindowId, cancelZoom, quickFlipVisible, windowId]);
- useReaderGestures({
+ const readerGestures = useReaderGestures({
containerRef, frameRef: contentFrameRef, scale, canSwipe: mode === 'grab', isActive: activeWindowId === (windowId ?? 'main'),
contextKey: `${sessionId}:${windowId}:${documentUrl}:${activePage}:${retryAttempt}:${quickFlipVisible}:${scale}:${mode}`,
onActivate: () => { cancelZoom(); handleViewportFocus(); },
@@ -672,7 +678,12 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
}, [activePage, holdPage, totalPages, updateActivePage]);
return (
-
+
{
+ if (event.key !== 'Escape' || event.defaultPrevented || !pdfLinks.notice || showRenderFailure || showRenderRetry) return;
+ event.preventDefault(); event.stopPropagation();
+ pdfLinks.cancel(); containerRef.current?.focus({ preventScroll: true });
+ }}>
@@ -706,6 +717,7 @@ export const ReaderViewport: React.FC
= ({ pageNumber, isMain = false, wi
role="region"
aria-label={isMain ? '主阅读区' : `参考阅读区,第 ${activePage} 页`}
className={`flex min-h-0 min-w-0 flex-1 overflow-auto bg-[#edece9] ${mode === 'grab' ? 'select-none' : 'select-text'}`}
+ onClickCapture={event => { if (!readerGestures.suppressClick(event)) pdfLinks.onClickCapture(event); }}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={stopPanning}
@@ -723,13 +735,16 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
style={paperRatio ? { width: Math.floor(pageWidth * scale) + 2, height: Math.floor(pageWidth * scale * paperRatio) + 2 } : undefined}>
{file ? (
页面暂时无法显示,请重新导入这本 PDF。}
loading={
正在渲染...
}
>
= ({ pageNumber, isMain = false, wi
className="border border-[#e0ddd5] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.05),0_30px_100px_rgba(0,0,0,0.1)]"
renderTextLayer={true}
onLoadSuccess={handlePageLoad}
+ onGetAnnotationsSuccess={pdfLinks.onAnnotations}
onRenderSuccess={handleRenderSuccess}
onRenderError={handleRenderError}
loading={正在渲染页面…
}
@@ -749,6 +765,16 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi
+ {pdfLinks.notice && !showRenderFailure && !showRenderRetry && (
+
+
+
无法打开此链接。可尝试目录或页码导航。
+
+
+
+ )}
{(showRenderFailure || showRenderRetry) && (
diff --git a/src/components/timeline/TimelineBar.tsx b/src/components/timeline/TimelineBar.tsx
index 7b0cd05..70d4754 100644
--- a/src/components/timeline/TimelineBar.tsx
+++ b/src/components/timeline/TimelineBar.tsx
@@ -6,11 +6,12 @@ interface Props {
currentPage: number;
totalPages: number;
onPageClick: (page: number) => void;
+ onPreviewStart?: () => void;
markers?: number[];
chapters?: TOCItem[];
}
-export const TimelineBar: React.FC
= ({ currentPage, totalPages, onPageClick, markers = [], chapters = [] }) => {
+export const TimelineBar: React.FC = ({ currentPage, totalPages, onPageClick, onPreviewStart, markers = [], chapters = [] }) => {
const [pageInput, setPageInput] = useState(null);
const [preview, setPreview] = useState<{ page: number; origin: number; total: number; outside?: boolean } | null>(null);
const previewPage = preview?.origin === currentPage && preview.total === totalPages ? preview.page : null;
@@ -88,6 +89,7 @@ export const TimelineBar: React.FC = ({ currentPage, totalPages, onPageCl
// semantics. WebKit's internal thumb capture conflicts with explicit
// input capture; native change timing also differs across engines.
event.preventDefault();
+ onPreviewStart?.();
const page = pointerPage(event);
drag.current = { pointerId: event.pointerId, page, canceled: false, startY: event.clientY, outside: false };
setPreview({ page, origin: currentPage, total: totalPages });
diff --git a/src/hooks/usePdfLinkNavigation.ts b/src/hooks/usePdfLinkNavigation.ts
new file mode 100644
index 0000000..fa259c5
--- /dev/null
+++ b/src/hooks/usePdfLinkNavigation.ts
@@ -0,0 +1,163 @@
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type RefObject } from 'react';
+import type { PDFDocumentProxy } from 'pdfjs-dist';
+import { bookStore } from '../stores/bookStore';
+import { windowStore } from '../stores/windowStore';
+import { quickFlipStore } from '../stores/quickFlipStore';
+import { subscribeReaderNavigation } from '../services/readerNavigationIntent';
+
+type Owner = { sessionId: number; documentUrl: string | null; windowId: string };
+type PageOwner = { owner: Owner; pageNumber: number; attempt: number };
+type Annotation = { id: string; destination?: unknown };
+type Ticket = { id: number; page: PageOwner; pdf: PDFDocumentProxy };
+interface Options extends Owner {
+ pageNumber: number;
+ attempt: number;
+ containerRef: RefObject;
+ pageRef: RefObject;
+}
+
+/** Own only local PDF destinations; URI/actions/forms retain PDF.js handling. */
+export function usePdfLinkNavigation({ sessionId, documentUrl, windowId, pageNumber, attempt, containerRef, pageRef }: Options) {
+ const owner = useMemo(() => ({ sessionId, documentUrl, windowId }), [sessionId, documentUrl, windowId]);
+ const page = useMemo(() => ({ owner, pageNumber, attempt }), [owner, pageNumber, attempt]);
+ const liveOwner = useRef(owner), livePage = useRef(page);
+ const pdfDocument = useRef<{ owner: Owner; pdf: PDFDocumentProxy } | null>(null);
+ const annotations = useRef<{ page: PageOwner; items: Map } | null>(null);
+ const sequence = useRef(0), pending = useRef(null);
+ const [notice, setNotice] = useState<{ page: PageOwner; id: number } | null>(null);
+ const retire = useCallback(() => { sequence.current++; pending.current = null; }, []);
+ const cancel = useCallback(() => { retire(); setNotice(null); }, [retire]);
+ const isOwnerCurrent = useCallback(() => {
+ const book = bookStore.getState();
+ return liveOwner.current === owner && book.status === 'ready' && book.sessionId === owner.sessionId
+ && book.documentUrl === owner.documentUrl && windowStore.getState().windows.some(window => window.id === owner.windowId);
+ }, [owner]);
+
+ useLayoutEffect(() => {
+ liveOwner.current = owner;
+ const cancelRetiredBook = () => { if (!isOwnerCurrent()) cancel(); };
+ const subscriptions = [subscribeReaderNavigation(id => { if (id === owner.windowId) cancel(); }),
+ bookStore.subscribe(cancelRetiredBook), windowStore.subscribe((next, previous) => {
+ const origin = next.windows.find(window => window.id === owner.windowId);
+ const before = previous.windows.find(window => window.id === owner.windowId);
+ // Observe every transition synchronously: away-and-back cannot revive a
+ // deferred link. Focus/viewport writes alone are not navigation intent.
+ if (!origin || origin.pageNumber !== before?.pageNumber) cancel();
+ }), quickFlipStore.subscribe((next, previous) => {
+ if (next.isOpen && !previous.isOpen && windowStore.getState().activeWindowId === owner.windowId) cancel();
+ })];
+ return () => {
+ subscriptions.forEach(unsubscribe => unsubscribe());
+ if (liveOwner.current === owner) liveOwner.current = null;
+ retire(); pdfDocument.current = null; annotations.current = null;
+ };
+ }, [cancel, isOwnerCurrent, owner, retire]);
+
+ useLayoutEffect(() => {
+ livePage.current = page; annotations.current = null; cancel();
+ return () => { if (livePage.current === page) livePage.current = null; };
+ }, [cancel, page]);
+
+ const onDocumentLoad = useCallback((pdf: PDFDocumentProxy) => {
+ if (!isOwnerCurrent()) return;
+ if (pdfDocument.current && pdfDocument.current.pdf !== pdf) { cancel(); annotations.current = null; }
+ pdfDocument.current = { owner, pdf };
+ }, [cancel, isOwnerCurrent, owner]);
+ const onAnnotations = useCallback((items: unknown[]) => {
+ if (!isOwnerCurrent() || livePage.current !== page
+ || windowStore.getState().windows.find(window => window.id === owner.windowId)?.pageNumber !== page.pageNumber) return;
+ const entries = new Map();
+ for (const item of items) {
+ if (!item || typeof item !== 'object') continue;
+ const data = item as Record;
+ if (typeof data.id !== 'string') continue;
+ // Match LinkAnnotationElement's precedence. A URI, named action,
+ // attachment or optional-content action wins over an ordinary dest.
+ const internal = data.annotationType === 2 && !data.url && !data.action && !data.attachment && !data.setOCGState && !!data.dest;
+ entries.set(data.id, { id: data.id, ...(internal ? { destination: data.dest } : {}) });
+ }
+ // AnnotationLayer calls this before rendering links. State-only caching
+ // would leave a gap in which its native untokened handler could run.
+ annotations.current = { page, items: entries };
+ }, [isOwnerCurrent, owner, page]);
+
+ const isCurrent = useCallback((ticket: Ticket) => isOwnerCurrent() && pending.current === ticket
+ && sequence.current === ticket.id && livePage.current === ticket.page
+ && pdfDocument.current?.pdf === ticket.pdf
+ && windowStore.getState().windows.find(window => window.id === owner.windowId)?.pageNumber === ticket.page.pageNumber,
+ [isOwnerCurrent, owner]);
+
+ const follow = useCallback(async (ticket: Ticket, destination: unknown) => {
+ let target: number;
+ try {
+ let explicit = destination;
+ if (typeof explicit === 'string') {
+ explicit = await ticket.pdf.getDestination(explicit);
+ if (!isCurrent(ticket)) return;
+ }
+ if (!Array.isArray(explicit) || !explicit.length) throw new Error('Invalid PDF destination');
+ const reference: unknown = explicit[0];
+ let index: number;
+ if (typeof reference === 'number') index = reference;
+ else if (reference && typeof reference === 'object' && 'num' in reference && 'gen' in reference
+ && typeof reference.num === 'number' && Number.isInteger(reference.num) && reference.num > 0
+ && typeof reference.gen === 'number' && Number.isInteger(reference.gen) && reference.gen >= 0) {
+ index = await ticket.pdf.getPageIndex({ num: reference.num, gen: reference.gen });
+ if (!isCurrent(ticket)) return;
+ } else throw new Error('Invalid PDF page reference');
+ target = index + 1;
+ if (!Number.isInteger(index) || index < 0 || target > ticket.pdf.numPages || target > bookStore.getState().totalPages) throw new Error('PDF destination is out of bounds');
+ } catch {
+ // Handle only this resolution/validation promise, never unrelated PDF.js,
+ // DOM or application errors. Obsolete work cannot publish a new notice.
+ if (isCurrent(ticket)) { pending.current = null; setNotice({ page: ticket.page, id: ticket.id }); }
+ return;
+ }
+ if (!isCurrent(ticket)) return;
+ pending.current = null;
+ const container = containerRef.current, element = pageRef.current, workspace = windowStore.getState();
+ const visible = container?.isConnected && container.clientWidth > 0 && container.clientHeight > 0 && !container.closest('[inert]');
+ const displayedPage = element?.isConnected && container?.contains(element) && element.dataset.pageNumber === String(ticket.page.pageNumber);
+ if (target === ticket.page.pageNumber) {
+ if (visible && displayedPage) element.scrollIntoView();
+ return;
+ }
+ if (visible && displayedPage && workspace.activeWindowId === owner.windowId
+ && element.querySelector('.annotationLayer')?.contains(globalThis.document.activeElement)) container.focus({ preventScroll: true });
+ workspace.updateWindow(owner.windowId, { pageNumber: target });
+ }, [containerRef, isCurrent, owner, pageRef]);
+
+ const onClickCapture = useCallback((event: MouseEvent) => {
+ if (!(event.target instanceof Element)) return;
+ const anchor = event.target.closest('a'), element = pageRef.current;
+ if (!anchor || !element?.querySelector('.annotationLayer')?.contains(anchor)) return;
+ const annotation = anchor.closest('[data-annotation-id]');
+ if (!annotation) return;
+ const metadata = annotations.current, current = metadata?.page === page && livePage.current === page && isOwnerCurrent()
+ && element.dataset.pageNumber === String(page.pageNumber);
+ const item = current ? metadata.items.get(annotation.dataset.annotationId ?? '') : undefined;
+ if (!item) {
+ // A retired internal anchor must not fall through to PDF.js navigation.
+ // Current unrelated annotations and external URI anchors are untouched.
+ if (annotation.hasAttribute('data-internal-link')) { event.preventDefault(); event.stopPropagation(); }
+ return;
+ }
+ if (item.destination === undefined) return;
+ event.preventDefault(); event.stopPropagation();
+ cancel();
+ const source = pdfDocument.current;
+ if (!source || source.owner !== owner || !isOwnerCurrent()
+ || containerRef.current?.closest('[inert]')
+ || (quickFlipStore.getState().isOpen && windowStore.getState().activeWindowId === owner.windowId)
+ || windowStore.getState().windows.find(window => window.id === owner.windowId)?.pageNumber !== page.pageNumber) return;
+ const ticket = { id: sequence.current, page, pdf: source.pdf };
+ pending.current = ticket;
+ void follow(ticket, item.destination);
+ }, [cancel, containerRef, follow, isOwnerCurrent, owner, page, pageRef]);
+
+ return {
+ documentKey: JSON.stringify([owner.sessionId, owner.documentUrl, owner.windowId]),
+ onDocumentLoad, onAnnotations, onClickCapture, cancel,
+ notice: notice?.page === page && notice.id === sequence.current && isOwnerCurrent(),
+ };
+}
diff --git a/src/hooks/useReaderGestures.ts b/src/hooks/useReaderGestures.ts
index b144f59..979dd32 100644
--- a/src/hooks/useReaderGestures.ts
+++ b/src/hooks/useReaderGestures.ts
@@ -1,4 +1,4 @@
-import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from 'react';
type Point = { x: number; y: number };
type Gesture =
@@ -29,6 +29,19 @@ export function useReaderGestures(options: Options) {
const latest = useRef(options);
useLayoutEffect(() => { latest.current = options; });
const cancelRef = useRef<() => void>(() => {});
+ const suppressClickUntil = useRef(0);
+ // React root capture runs before the reader's native capture listener.
+ // Share this guard with PDF link capture so a post-gesture ghost click
+ // cannot navigate first. Firefox can report detail=1 for keyboard clicks;
+ // Pointer Events reserves pointerId=-1 for non-pointing activation. React's
+ // MouseEvent wrapper omits pointerId, so consult the native event as well.
+ const suppressClick = useCallback((event: Pick & { nativeEvent?: MouseEvent }) => {
+ const source = event.nativeEvent ?? event;
+ if (event.detail === 0 || ('pointerId' in source && source.pointerId === -1)
+ || performance.now() >= suppressClickUntil.current) return false;
+ event.preventDefault(); event.stopPropagation();
+ return true;
+ }, []);
useEffect(() => { cancelRef.current(); }, [options.contextKey]);
useEffect(() => { if (!options.isActive) cancelRef.current(); }, [options.isActive]);
@@ -37,7 +50,6 @@ export function useReaderGestures(options: Options) {
const frame = options.frameRef.current;
if (!container || !frame) return;
let gesture: Gesture | null = null;
- let suppressClickUntil = 0;
const clearPreview = () => { frame.style.transform = ''; frame.style.transformOrigin = ''; frame.style.willChange = ''; };
const cancel = () => { clearPreview(); gesture = null; };
const interrupt = () => {
@@ -97,7 +109,7 @@ export function useReaderGestures(options: Options) {
frame.style.transformOrigin = '0 0';
frame.style.willChange = 'transform';
frame.style.transform = `translate(${gesture.midpoint.x - gesture.frame.x - gesture.anchor.x * ratio}px, ${gesture.midpoint.y - gesture.frame.y - gesture.anchor.y * ratio}px) scale(${ratio})`;
- suppressClickUntil = performance.now() + 600;
+ suppressClickUntil.current = performance.now() + 600;
} else {
const touch = Array.from(event.touches).find(touch => touch.identifier === (gesture?.kind === 'swipe' ? gesture.id : -1));
if (!touch || event.touches.length !== 1) { cancel(); return; }
@@ -120,7 +132,7 @@ export function useReaderGestures(options: Options) {
gesture = event.touches.length ? { kind: 'blocked' } : null;
if (Math.abs(completed.nextScale - completed.scale) > 0.0001) latest.current.onZoom(completed.nextScale,
completed.paperPoint, completed.midpoint);
- suppressClickUntil = performance.now() + 600;
+ suppressClickUntil.current = performance.now() + 600;
} else if (!event.touches.length) {
gesture = null;
if (completed?.kind !== 'swipe') return;
@@ -130,13 +142,13 @@ export function useReaderGestures(options: Options) {
const dy = last.y - completed.start.y;
if (Math.abs(dx) >= 56 && Math.abs(dx) > Math.abs(dy) * 1.5 && performance.now() - completed.time <= 700) {
if (event.cancelable) event.preventDefault();
- suppressClickUntil = performance.now() + 600;
+ suppressClickUntil.current = performance.now() + 600;
latest.current.onTurn(dx < 0 ? 1 : -1);
}
}
};
const cancelTouch = (event: TouchEvent) => { cancel(); if (event.touches.length) gesture = { kind: 'blocked' }; };
- const click = (event: MouseEvent) => { if (performance.now() < suppressClickUntil) { event.preventDefault(); event.stopPropagation(); } };
+ const click = (event: MouseEvent) => { suppressClick(event); };
const visibility = () => { if (document.hidden) interrupt(); };
const key = (event: KeyboardEvent) => {
if ((gesture?.kind === 'pinch' || gesture?.kind === 'swipe') && (event.key === 'Escape' || event.key === ' ')) {
@@ -167,5 +179,6 @@ export function useReaderGestures(options: Options) {
window.removeEventListener('resize', interrupt);
document.removeEventListener('visibilitychange', visibility);
};
- }, [options.containerRef, options.frameRef]);
+ }, [options.containerRef, options.frameRef, suppressClick]);
+ return { suppressClick };
}
diff --git a/src/services/HeldReadTransaction.ts b/src/services/HeldReadTransaction.ts
index 907ee17..69c8f5f 100644
--- a/src/services/HeldReadTransaction.ts
+++ b/src/services/HeldReadTransaction.ts
@@ -1,5 +1,6 @@
import { bookStore } from '../stores/bookStore';
import { windowStore } from '../stores/windowStore';
+import { notifyReaderNavigation } from './readerNavigationIntent';
export interface PreparedHeldRead {
commit(): boolean;
@@ -15,6 +16,9 @@ export function prepareHeldRead(pageNumber: number): PreparedHeldRead {
if (!origin || !book.documentId || book.status !== 'ready') {
return { commit: () => false, rollback: () => false, dispose: () => undefined };
}
+ // The click expresses intent now, before the double-click grace period.
+ // An older deferred PDF link must not invalidate this newer prepared read.
+ notifyReaderNavigation(windowId);
const position = { pageNumber: origin.pageNumber, title: origin.title,
viewport: { ...origin.viewport, scale: windowId === 'main' ? book.scale : origin.viewport?.scale ?? 1 } };
const signature = (): readonly unknown[] => {
diff --git a/src/services/readerNavigationIntent.ts b/src/services/readerNavigationIntent.ts
new file mode 100644
index 0000000..cb12c9e
--- /dev/null
+++ b/src/services/readerNavigationIntent.ts
@@ -0,0 +1,13 @@
+type NavigationListener = (windowId: string) => void;
+const listeners = new Set();
+
+/** Explicit page choices are intent even when clamping keeps the same page.
+ * This transient signal never enters a saved workspace or dirties autosave. */
+export function notifyReaderNavigation(windowId: string): void {
+ for (const listener of listeners) listener(windowId);
+}
+
+export function subscribeReaderNavigation(listener: NavigationListener): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
diff --git a/src/stores/bookStore.ts b/src/stores/bookStore.ts
index 242a96c..eb69a6b 100644
--- a/src/stores/bookStore.ts
+++ b/src/stores/bookStore.ts
@@ -1,6 +1,7 @@
import { create } from 'zustand';
import { pdfService } from '../services/PDFService';
import { thumbnailService } from '../services/ThumbnailService';
+import { notifyReaderNavigation } from '../services/readerNavigationIntent';
import type { TOCItem } from '../types/domain';
type DocumentSource = File | string;
@@ -131,7 +132,10 @@ export const useBookStore = create((set, get) => ({
},
restoreDocument: (payload) => get().setDocumentReady(payload),
- setCurrentPage: (page) => set({ currentPage: clampPage(page, get().totalPages) }),
+ setCurrentPage: (page) => {
+ notifyReaderNavigation('main');
+ set({ currentPage: clampPage(page, get().totalPages) });
+ },
setScale: (scale) => set({ scale: clampScale(scale) }),
setTotalPages: (value) => {
const totalPages = normalizeTotalPages(value);
diff --git a/src/stores/windowStore.ts b/src/stores/windowStore.ts
index addef6c..f1aa306 100644
--- a/src/stores/windowStore.ts
+++ b/src/stores/windowStore.ts
@@ -3,6 +3,7 @@ import { v4 as uuidv4 } from 'uuid';
import { bookStore } from './bookStore';
import { heldStore } from './heldStore';
+import { notifyReaderNavigation } from '../services/readerNavigationIntent';
import type { ReaderWindow } from '../types/domain';
export const MAX_READER_WINDOWS = 5;
@@ -212,6 +213,7 @@ export const useWindowStore = create((set, get) => ({
const mainWindow = windows.find(w => w.id === 'main');
const targetWindow = windows.find(w => w.id === windowId);
if (!mainWindow || !targetWindow || windowId === 'main') return;
+ notifyReaderNavigation(windowId);
const nextWindows = windows.map(w => {
if (w.id === 'main') return { ...w, pageNumber: targetWindow.pageNumber, title: targetWindow.title, viewport: targetWindow.viewport };
@@ -229,6 +231,7 @@ export const useWindowStore = create((set, get) => ({
const { windows } = get();
if (!windows.some((window) => window.id === windowId)) return;
if (partial.pageNumber !== undefined) {
+ if (windowId !== 'main') notifyReaderNavigation(windowId);
const pageNumber = normalizePage(partial.pageNumber);
partial = { ...partial, pageNumber, title: partial.title ?? createWindowTitle(pageNumber) };
if (windowId === 'main') bookStore.getState().setCurrentPage(pageNumber);
diff --git a/src/tests/e2e/README.md b/src/tests/e2e/README.md
index d3d492c..d0037c5 100644
--- a/src/tests/e2e/README.md
+++ b/src/tests/e2e/README.md
@@ -26,6 +26,7 @@ Playwright builds the deployable bundle, then starts Vite preview on `127.0.0.1:
- **Mixed-page geometry:** a ten-page image-only fixture covers rotation, offset/rotated crop boxes, portrait/landscape/square and 6:1 tall/wide pages. Repeated toolbar zoom to 400% and a fresh zoom after scrolling deep into a tall page retain the same actual-canvas point within 2 CSS pixels, including fractional DPR. The maximum-size canvas is screen-captured before readback and its visible pixel is compared with the decoded canvas; cropped/rotated thumbnails, reference zoom/scroll, saved reopen and PDF-byte hashes are checked separately
- **Local PDF decoders:** a genuine small lossless JPEG2000 scan and identical RGB control require decoded red/green pixels in main/reference readers and Quick Flip/held thumbnails. Worker and main-thread thumbnail routes run separately, as do native WASM and forced local-JavaScript decoder fallback. Exact binary/license hashes, WASM magic, JavaScript MIME, app-base URL prefixes, saved reopen and original PDF hashes are checked
- **Page raster recovery:** controlled native canvas drawing failures require a visible, keyboard-reachable page-local Retry above real PDF text/link layers. Grab and text-selection modes, repeated explicit attempts, 10%/400% scale, a 320px short viewport, navigation away from failure and desktop background-reference ownership are covered. Recovery replaces only the failed Page canvas, retains its Document node and worker count, and checks saved reading state and original PDF-byte hashes
+- **Internal PDF links:** numeric, named and indirect-reference destinations navigate the originating main/reference reader, including a destination already mounted in another pane. Native Enter retains arrow-reading continuity; same-page links retain their existing scoped scrolling and focus. A controlled native Worker message gate delays named resolution while focus moves to main or a newer toolbar control. Saved reopening, original PDF-byte hashes, retained Document DOM and worker counts, and external-link attributes are checked without following the external URL
- **Large raster PDF:** generated 106 MB image-only document, first-render timing evidence, final-page navigation, held thumbnail and IndexedDB reopen
- **Import recovery:** real opening-password rejection gives actionable local-copy guidance; owner-permission-only encryption still opens. Repeated failure resets the file input/import lock. Protected and corrupt replacements preserve PDF-byte hashes, held pages, independent scale/viewport and reference windows; recent-card recovery needs no original-file reimport
- **Activation identity:** repeated motionless reader clicks, stationary touch where supported, and toolbar focus do not rewrite the saved snapshot or its timestamp. Controlled page-clock checks retain a genuine page change’s original 500 ms save deadline. Real reference activation/Enter still save, while cancelled preview focus does not. These are operation counts and input contracts, not latency or battery benchmarks
@@ -73,3 +74,9 @@ Held decoder checks wait for the actual 60px bitmap before sampling colors, so a
Raster-recovery tests throw once or twice from native `CanvasRenderingContext2D.drawImage` only for the selected reader/page canvas. PDF.js and React-PDF still execute their real rejection and retry paths; temporary canvases and thumbnail workers are untouched. A generated raster PDF with an internal full-page link makes native PDF layer stacking observable. Recovered screenshots precede the first pixel readback of the replacement canvas. This verifies explicit failed-raster recovery, not automatic detection of silently blank PDFs, memory-pressure diagnosis, physical-device canvas limits or the separate pending-worker teardown issue. Mobile projects establish responsive emulation; native-touch and assistive-technology hardware validation remain separate.
Deterministic UI cases additionally cover stale page/scale/size/session callbacks, repeated clicks, unmount and StrictMode, a focused Retry removed by resize, background completion that must not steal focus, and interruption of an older pinch preview. Retry does not reload Document, clear durable state, change PDF.js versions or suppress render errors.
+
+Internal PDF links are resolved through the owning Document's public PDFDocumentProxy. Annotation metadata is captured before PDF.js renders its anchors; a reader capture handler intercepts only ordinary local destinations while external URIs, named actions, attachments, forms and optional-content actions retain PDF.js handling. Reader Documents keep a session/source/window identity; page, zoom, width, focus and raster-retry changes do not reparse the document. This does not fix the separate pending-worker teardown rejection.
+
+Each activation owns a cancellable ticket through both named-destination and indirect-page-reference resolution. A newer link, explicit navigation (including choosing the same page), owning QuickFlip entry, retry, page/session/owner retirement or unmount permanently retires older work. Focus is returned before a departing annotation disappears only while the active visible source still owns it. Missing/invalid destinations produce dismissible local feedback; Escape from that pane dismisses the notice before global window closing. Post-pinch/swipe click suppression is checked before React capture can navigate; keyboard activation remains available.
+
+UI tests cover synchronous retirement, away-and-back, no-op main/reference navigation, both asynchronous stages, current/stale rejection, repeated activation, StrictMode and focus ownership. Browser tests use real generated PDF annotations, worker-protocol response gates, saved-source hashing, reopen verification, same-page Home/page input, QuickFlip open/cancel/commit and a deliberate missing destination. Synthetic touch events establish gesture/click ordering across engines; they are not physical-device touch validation. Destination-coordinate/zoom interpretation remains outside this page-navigation feature.
diff --git a/src/tests/e2e/pdf-links.test.ts b/src/tests/e2e/pdf-links.test.ts
new file mode 100644
index 0000000..6f50f0b
--- /dev/null
+++ b/src/tests/e2e/pdf-links.test.ts
@@ -0,0 +1,257 @@
+import { fileURLToPath } from 'node:url';
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import type { Locator, Page } from '@playwright/test';
+import { test, expect, importBook, reader, quickFlip, snapshots, reopenRecent } from './helpers';
+
+const fixture = fileURLToPath(new URL('../fixtures/leafspace-links.pdf', import.meta.url));
+const colors = [[51, 128, 77], [26, 89, 179], [179, 64, 26]];
+const annotation = (region: Locator, id: string) => region.locator(`.annotationLayer [data-annotation-id="${id}"] a`);
+type LinkGate = { holding: boolean; queued: number; workers: number; pending: number; responses: number; release: () => void };
+const gate = (page: Page) => page.evaluate(() => {
+ const { holding, queued, workers, pending, responses } = (window as unknown as { leafspaceLinkGate: LinkGate }).leafspaceLinkGate;
+ return { holding, queued, workers, pending, responses };
+});
+async function installGate(page: Page) {
+ await page.addInitScript(() => {
+ const pending: (() => void)[] = [];
+ const state = { holding: false, queued: 0, workers: 0, pending: 0, responses: 0, release() { state.holding = false; pending.splice(0).forEach(send => send()); } };
+ Object.assign(window, { leafspaceLinkGate: state });
+ const NativeWorker = window.Worker, postMessage = NativeWorker.prototype.postMessage;
+ window.Worker = class extends NativeWorker {
+ requests = new Set();
+ constructor(url: string | URL, options?: WorkerOptions) {
+ super(url, options); state.workers++;
+ this.addEventListener('message', event => {
+ const message = event.data;
+ if (message?.callback && this.requests.delete(`${message.targetName}:${message.callbackId}`)) { state.pending--; state.responses++; }
+ });
+ }
+ postMessage(message: unknown, options?: StructuredSerializeOptions | Transferable[]) {
+ const request = message as { action?: string; sourceName?: string; callbackId?: number; data?: { id?: string } };
+ if (['GetDestination', 'GetPageIndex'].includes(request?.action ?? '') && typeof request.callbackId === 'number') {
+ this.requests.add(`${request.sourceName}:${request.callbackId}`); state.pending++;
+ }
+ const send = () => Reflect.apply(postMessage, this, options === undefined ? [message] : [message, options]);
+ if (state.holding && request?.action === 'GetDestination' && request.data?.id === 'chapter') { state.queued++; pending.push(send); }
+ else send();
+ }
+ };
+ });
+}
+async function holdNamedLink(page: Page) {
+ await page.evaluate(() => { (window as unknown as { leafspaceLinkGate: LinkGate }).leafspaceLinkGate.holding = true; });
+ await annotation(reader(page), '11R').focus(); await page.keyboard.press('Enter');
+ await expect.poll(async () => (await gate(page)).queued).toBe(1);
+}
+async function releaseAndSettle(page: Page) {
+ await page.evaluate(() => (window as unknown as { leafspaceLinkGate: LinkGate }).leafspaceLinkGate.release());
+ await expect.poll(async () => { const state = await gate(page); return state.responses > 0 && state.pending === 0; }).toBe(true);
+ // Worker replies and their Promise continuations precede this paint boundary.
+ await page.evaluate(async () => { await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame); });
+}
+async function save(page: Page) {
+ await page.getByRole('button', { name: '保存现场', exact: true }).click();
+ await expect(page.getByText('已保存到本机', { exact: true })).toBeVisible();
+ return (await snapshots(page))[0];
+}
+async function sourceHash(page: Page) {
+ return page.evaluate(async () => {
+ const bytes = await new Promise((resolve, reject) => {
+ const opening = indexedDB.open('leafspace'); opening.onerror = () => reject(opening.error);
+ opening.onsuccess = () => {
+ const db = opening.result, tx = db.transaction('books', 'readonly'), request = tx.objectStore('books').getAll();
+ request.onsuccess = async () => { try { resolve(request.result[0].bytes ?? await request.result[0].blob.arrayBuffer()); } catch (error) { reject(error); } };
+ request.onerror = () => reject(request.error); tx.oncomplete = () => db.close(); tx.onabort = () => db.close();
+ };
+ });
+ return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))).map(byte => byte.toString(16).padStart(2, '0')).join('');
+ });
+}
+
+async function expectPage(region: Locator, pageNumber: number) {
+ await expect(region.locator('.react-pdf__Page')).toHaveAttribute('data-page-number', String(pageNumber));
+ await expect(region.locator('canvas')).toBeVisible();
+ await expect.poll(async () => {
+ const pixel = await region.locator('canvas').evaluate((canvas: HTMLCanvasElement) =>
+ Array.from(canvas.getContext('2d')!.getImageData(Math.floor(canvas.width * 50 / 420), Math.floor(canvas.height * 27 / 594), 1, 1).data));
+ return pixel[3] === 255 && colors[pageNumber - 1].every((channel, index) => Math.abs(channel - pixel[index]) <= 1);
+ }, { message: `Page ${pageNumber} has its own decoded color bar` }).toBe(true);
+}
+
+test('a numeric internal PDF link renders its unmounted target in the main reader', async ({ page }, info) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ const documentNode = await reader(page).locator('.react-pdf__Document').elementHandle(), before = await gate(page);
+ await annotation(reader(page), '10R').click();
+ await expectPage(reader(page), 2); await expect(page.locator('header')).toContainText('第 2 页');
+ await annotation(reader(page), '15R').click(); await expectPage(reader(page), 1);
+ await annotation(reader(page), '10R').focus(); await page.keyboard.press('Enter');
+ await expectPage(reader(page), 2); await expect(reader(page)).toBeFocused();
+ await page.keyboard.press('ArrowRight'); await expectPage(reader(page), 3);
+ expect(await documentNode!.evaluate(element => element.isConnected)).toBe(true); expect((await gate(page)).workers).toBe(before.workers);
+ await save(page); expect(await sourceHash(page)).toBe(createHash('sha256').update(readFileSync(fixture)).digest('hex'));
+ await reopenRecent(page, 'leafspace-links.pdf'); await expectPage(reader(page), 3);
+ await info.attach('internal-main-link-destination', { body: await page.screenshot(), contentType: 'image/png' });
+});
+
+test('a named internal PDF link navigates its reference even when main already renders the destination', async ({ page }, info) => {
+ test.skip(['tablet', 'mobile', 'mobile-webkit'].includes(info.project.name), 'Simultaneously visible main and reference ownership');
+ await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await page.getByRole('button', { name: /^速翻/ }).click(); await expect(quickFlip(page)).toBeVisible();
+ await page.keyboard.press('n');
+ const reference = page.getByRole('region', { name: /^参考阅读区/ }); await expectPage(reference, 1);
+ await reader(page).focus(); await page.keyboard.press('ArrowRight'); await expectPage(reader(page), 2);
+ await page.keyboard.press('ArrowRight'); await expectPage(reader(page), 3);
+ await annotation(reference, '11R').click();
+ await expectPage(reference, 3); await expectPage(reader(page), 3);
+ await annotation(reference, '16R').click(); await expectPage(reference, 1);
+ await annotation(reference, '11R').focus(); await page.keyboard.press('Enter');
+ await expectPage(reference, 3); await expect(reference).toBeFocused();
+ await page.keyboard.press('ArrowLeft'); await expectPage(reference, 2); await expectPage(reader(page), 3);
+ await expect(page.locator('header')).toContainText('第 3 页');
+ const saved = await save(page); expect(saved.currentPage).toBe(3); expect(saved.windows.find(window => window.id !== 'main')?.pageNumber).toBe(2);
+ await reopenRecent(page, 'leafspace-links.pdf'); await expectPage(reader(page), 3); await expectPage(reference, 2);
+ await info.attach('internal-reference-link-destination', { body: await page.screenshot(), contentType: 'image/png' });
+});
+
+for (const [id, kind] of [['11R', 'named'], ['12R', 'indirect-reference']] as const) {
+ test(`a ${kind} main-reader destination resolves through the real PDF worker`, async ({ page }, info) => {
+ await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ const external = annotation(reader(page), '14R');
+ await expect(external).toHaveAttribute('href', 'https://example.com/paper');
+ await expect(external).toHaveAttribute('rel', /noopener/); await expect(external).toHaveAttribute('rel', /noreferrer/);
+ await annotation(reader(page), id).click(); await expectPage(reader(page), 3);
+ await info.attach(`internal-${kind}-destination`, { body: await page.screenshot(), contentType: 'image/png' });
+ });
+}
+
+test('same-page link Enter retains annotation focus and existing owner-scoped scroll behavior', async ({ page }, info) => {
+ await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ for (let step = 0; step < 4; step++) await page.getByRole('button', { name: '放大', exact: true }).click();
+ await expect(page.getByRole('button', { name: '恢复适合宽度' })).toHaveText('207%'); await expectPage(reader(page), 1);
+ const link = annotation(reader(page), '13R'); await link.focus();
+ await page.keyboard.press('Enter'); await expectPage(reader(page), 1); await expect(link).toBeFocused();
+ await expect.poll(() => reader(page).evaluate(element => Math.abs(element.querySelector('.react-pdf__Page')!.getBoundingClientRect().top - element.getBoundingClientRect().top))).toBeLessThanOrEqual(1);
+ await expect(page.getByRole('button', { name: '恢复适合宽度' })).toHaveText('207%');
+ await info.attach('same-page-link-scroll', { body: await page.screenshot(), contentType: 'image/png' });
+});
+
+for (const newerFocus of ['main', 'reference-toolbar'] as const) {
+ test(`a delayed named reference link preserves newer ${newerFocus} focus`, async ({ page }, info) => {
+ test.skip(['tablet', 'mobile', 'mobile-webkit'].includes(info.project.name), 'Simultaneously visible reference and alternate focus target');
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await page.getByRole('button', { name: /^速翻/ }).click(); await expect(quickFlip(page)).toBeVisible(); await page.keyboard.press('n');
+ const reference = page.getByRole('region', { name: /^参考阅读区/ }); await expectPage(reference, 1);
+ await reader(page).focus(); await page.keyboard.press('ArrowRight'); await expectPage(reader(page), 2);
+ await page.evaluate(() => { (window as unknown as { leafspaceLinkGate: LinkGate }).leafspaceLinkGate.holding = true; });
+ await annotation(reference, '11R').focus(); await page.keyboard.press('Enter');
+ await expect.poll(async () => (await gate(page)).queued).toBe(1); await expectPage(reference, 1);
+ const newer = newerFocus === 'main' ? reader(page) : reference.locator('xpath=ancestor::*[@data-reader-shell][1]').getByRole('button', { name: '放大', exact: true });
+ await newer.focus();
+ await page.evaluate(() => (window as unknown as { leafspaceLinkGate: LinkGate }).leafspaceLinkGate.release());
+ await expectPage(reference, 3); await expectPage(reader(page), 2); await expect(newer).toBeFocused();
+ await info.attach(`delayed-link-${newerFocus}`, { body: await page.screenshot(), contentType: 'image/png' });
+ });
+}
+
+test('manual navigation away and back supersedes a pending PDF link', async ({ page }) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await holdNamedLink(page); await reader(page).focus();
+ await page.keyboard.press('ArrowRight'); await expectPage(reader(page), 2);
+ await page.keyboard.press('ArrowLeft'); await expectPage(reader(page), 1);
+ await releaseAndSettle(page); await expectPage(reader(page), 1); await expect(reader(page)).toBeFocused();
+});
+
+test('a newer numeric link supersedes a pending PDF link', async ({ page }) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await holdNamedLink(page); await annotation(reader(page), '10R').click(); await expectPage(reader(page), 2);
+ await releaseAndSettle(page); await expectPage(reader(page), 2);
+});
+
+for (const action of ['Home', 'page-input'] as const) {
+ test(`same-page ${action} navigation supersedes a pending PDF link`, async ({ page }) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await holdNamedLink(page);
+ if (action === 'Home') { await reader(page).focus(); await page.keyboard.press('Home'); }
+ else { const input = page.getByRole('textbox', { name: '输入页码' }); await input.fill('1'); await input.press('Enter'); }
+ await releaseAndSettle(page); await expectPage(reader(page), 1);
+ });
+}
+
+test('missing internal destination has dismissible feedback and keeps a reference window open on Escape', async ({ page }, info) => {
+ test.skip(['tablet', 'mobile', 'mobile-webkit'].includes(info.project.name), 'Simultaneously visible reference ownership');
+ await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await page.getByRole('button', { name: /^速翻/ }).click(); await expect(quickFlip(page)).toBeVisible(); await page.keyboard.press('n');
+ const reference = page.getByRole('region', { name: /^参考阅读区/ }); await expectPage(reference, 1);
+ await annotation(reference, '17R').click();
+ await expect(page.getByRole('alert')).toContainText('无法打开此链接');
+ await info.attach('missing-reference-link-feedback', { body: await page.screenshot(), contentType: 'image/png' });
+ await page.getByRole('button', { name: '关闭链接提示' }).focus(); await page.keyboard.press('Escape');
+ await expect(page.getByText('无法打开此链接。可尝试目录或页码导航。')).toHaveCount(0);
+ await expectPage(reference, 1); await expect(reference).toBeFocused(); await expect(page.locator('[data-floating-window]')).toHaveCount(1);
+ await annotation(reference, '10R').click(); await expectPage(reference, 2);
+});
+
+test('missing main-reader link remains readable and can be dismissed without losing its page', async ({ page }, info) => {
+ await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await annotation(reader(page), '17R').click();
+ const notice = page.getByRole('alert'); await expect(notice).toContainText('无法打开此链接');
+ const bounds = await notice.boundingBox(), viewport = page.viewportSize()!;
+ expect(bounds).not.toBeNull(); expect(bounds!.x).toBeGreaterThanOrEqual(0); expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(viewport.width);
+ await info.attach('missing-main-link-feedback', { body: await page.screenshot(), contentType: 'image/png' });
+ await page.getByRole('button', { name: '关闭链接提示' }).click();
+ await expect(notice).toHaveCount(0); await expect(reader(page)).toBeFocused(); await expectPage(reader(page), 1);
+ await annotation(reader(page), '10R').click(); await expectPage(reader(page), 2);
+});
+
+test('post-pinch internal-link ghost click is suppressed before PDF resolution while keyboard remains available', async ({ page }) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ const before = await gate(page);
+ const canceled = await reader(page).evaluate(element => {
+ const box = element.getBoundingClientRect(), x = box.x + box.width / 2, y = box.y + 100;
+ const touches = [1, 2].map((identifier, index) => ({ identifier, target: element, clientX: x + (index ? 40 : -40), clientY: y }));
+ for (const type of ['touchstart', 'touchend']) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperties(event, { touches: { value: type === 'touchstart' ? touches : [] }, changedTouches: { value: touches } });
+ element.dispatchEvent(event);
+ }
+ const link = element.querySelector('[data-annotation-id="11R"] a')!;
+ const click = new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 });
+ link.dispatchEvent(click);
+ return click.defaultPrevented;
+ });
+ expect(canceled).toBe(true); expect((await gate(page)).pending).toBe(before.pending); expect((await gate(page)).responses).toBe(before.responses);
+ await expectPage(reader(page), 1);
+ await annotation(reader(page), '11R').focus(); await page.keyboard.press('Enter'); await expectPage(reader(page), 3);
+});
+
+for (const action of ['open', 'cancel', 'commit'] as const) {
+ test(`QuickFlip ${action} supersedes a pending PDF link`, async ({ page }) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await holdNamedLink(page); await reader(page).focus(); await page.keyboard.press('Space'); await expect(quickFlip(page)).toBeVisible();
+ if (action === 'cancel') { await page.keyboard.press('Escape'); await expect(quickFlip(page)).toHaveCount(0); }
+ if (action === 'commit') {
+ await quickFlip(page).getByRole('button', { name: '选择第 2 页', exact: true }).click();
+ await quickFlip(page).getByRole('button', { name: '阅读此页', exact: true }).click(); await expectPage(reader(page), 2);
+ }
+ await releaseAndSettle(page);
+ const currentPaper = page.locator('[data-window-id="main"] .react-pdf__Page');
+ await expect(currentPaper).toHaveAttribute('data-page-number', action === 'commit' ? '2' : '1');
+ if (action === 'open') { await expect(quickFlip(page)).toBeVisible(); await page.keyboard.press('Escape'); }
+ await expectPage(reader(page), action === 'commit' ? 2 : 1); await expect(reader(page)).toBeFocused();
+ });
+}
+
+for (const action of ['commit', 'cancel'] as const) {
+ test(`timeline preview ${action} supersedes an older PDF link before pointer release`, async ({ page }) => {
+ await installGate(page); await page.goto('/'); await importBook(page, fixture); await expectPage(reader(page), 1);
+ await holdNamedLink(page);
+ const slider = page.getByRole('slider', { name: '跳转到页码' }), box = await slider.boundingBox();
+ if (!box) throw new Error('Missing timeline');
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); await page.mouse.down();
+ await expect(slider).toHaveValue('2'); await expect(slider).toHaveAttribute('aria-valuetext', /^预览:/);
+ await releaseAndSettle(page); await expectPage(reader(page), 1);
+ if (action === 'cancel') await page.keyboard.press('Escape');
+ await page.mouse.up(); await expectPage(reader(page), action === 'commit' ? 2 : 1);
+ });
+}
diff --git a/src/tests/e2e/reading-completion.test.ts b/src/tests/e2e/reading-completion.test.ts
index 0f9d6f1..5fdc968 100644
--- a/src/tests/e2e/reading-completion.test.ts
+++ b/src/tests/e2e/reading-completion.test.ts
@@ -85,6 +85,12 @@ test('five-page grid keeps every pane visible after repeated docking, floating a
await reopenRecent(page, 'leafspace-120-pages.pdf');
await expect(page.locator('[data-reader-pane]')).toHaveCount(5);
for (const number of [2, 4, 6, 8]) await expect(page.getByRole('region', { name: `参考阅读区,第 ${number} 页`, exact: true }).locator('canvas')).toBeVisible();
+ // Re-enabling a save after hydration must not animate through disabled opacity.
+ // Keep the full axe assertion below; this checks the styling cause directly.
+ for (const name of ['导入书籍', '保存现场']) {
+ const transition = await page.getByRole('button', { name, exact: true }).evaluate(element => getComputedStyle(element).transitionProperty.split(',').map(value => value.trim()));
+ expect(transition).not.toContain('opacity'); expect(transition).not.toContain('all');
+ }
const violations = (await new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa', 'wcag21aa']).analyze()).violations;
expect(violations).toEqual([]);
});
diff --git a/src/tests/fixtures/README.md b/src/tests/fixtures/README.md
index a64d624..1a5dbc2 100644
--- a/src/tests/fixtures/README.md
+++ b/src/tests/fixtures/README.md
@@ -2,6 +2,8 @@
These PDFs are generated in this repository and contain no personal or user-supplied document content. They have real page trees, content streams, xref tables, and numbered or raster-image pages so Playwright exercises PDF.js parsing and rendering rather than mocked canvases.
+`leafspace-links.pdf` has three labeled pages with distinct colored bars, valid numeric/named/indirect-reference destinations, same-page/back links and one `https://example.com/paper` URI inspected only as an attribute. It also includes one deliberate missing named destination to test local feedback. It contains no JavaScript, form or password. Regenerate with `node src/tests/fixtures/generate-linked-pages.mjs` using only Node built-ins. Standard Courier keeps fixture label metrics reproducible. SHA-256: `925e130ce20fbd917d8e4712447f73061f00808acba3ba9df91ea1d79bca3eb5`.
+
`leafspace-render-recovery.pdf` is a two-page 256×256 RGB raster control with red, green and white regions, small page labels and same-page internal link annotations. The full-page link exercises real PDF layer stacking above a rejected canvas. It contains no external URI, JavaScript, form or password. Regenerate with `node src/tests/fixtures/generate-render-recovery.mjs`; only Node built-ins are required. SHA-256: `be360fdfe93a8fea06be086c10f600ec30439905d4f58ef054151d051f780eda`.
- `leafspace-12-pages.pdf`: 12 portrait pages, distinctive page numbers and green bars
diff --git a/src/tests/fixtures/generate-linked-pages.mjs b/src/tests/fixtures/generate-linked-pages.mjs
new file mode 100644
index 0000000..5afe6e3
--- /dev/null
+++ b/src/tests/fixtures/generate-linked-pages.mjs
@@ -0,0 +1,26 @@
+// Self-contained, reproducible link-navigation PDF. No third-party content.
+import { writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+const objects = [];
+const add = value => objects.push(Buffer.from(value));
+add('<< /Type /Catalog /Pages 2 0 R /Names << /Dests << /Names [(chapter) [7 0 R /Fit]] >> >> >>');
+add('<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>');
+const colors = [[0.2, 0.5, 0.3], [0.1, 0.35, 0.7], [0.7, 0.25, 0.1]];
+for (let page = 1; page <= 3; page++) {
+ const labels = page === 1 ? ['Numeric link to page 2', 'Named link to page 3', 'Indirect link to page 3', 'Same page link', 'External URL (attribute check only)', 'Missing named destination'] : ['Back to page 1'];
+ const stream = `${colors[page - 1].join(' ')} rg 20 560 380 14 re f\n0 0 0 rg\nBT /F1 18 Tf 30 537 Td (LeafSpace links - Page ${page}) Tj ET\n`
+ + labels.map((label, index) => `BT /F1 12 Tf 35 ${510 - index * 45} Td (${label.replaceAll('(', '\\(').replaceAll(')', '\\)')}) Tj ET`).join('\n') + '\n';
+ const annotations = page === 1 ? '10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 17 0 R' : `${page + 13} 0 R`;
+ add(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 420 594] /Resources << /Font << /F1 9 0 R >> >> /Contents ${page * 2 + 2} 0 R /Annots [${annotations}] >>`);
+ add(`<< /Length ${Buffer.byteLength(stream)} >>\nstream\n${stream}endstream`);
+}
+add('<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>');
+const actions = ['/Dest [1 /Fit]', '/Dest (chapter)', '/Dest [7 0 R /Fit]', '/Dest [0 /Fit]', '/A << /S /URI /URI (https://example.com/paper) >>', '/Dest [0 /Fit]', '/Dest [0 /Fit]', '/Dest (missing)'];
+actions.forEach((action, index) => {
+ const row = index < 5 ? index : index === 7 ? 5 : 0;
+ add(`<< /Type /Annot /Subtype /Link /Rect [30 ${505 - row * 45} 370 ${526 - row * 45}] /Border [0 0 1] ${action} >>`);
+});
+const chunks = [Buffer.from('%PDF-1.4\n')], offsets = [0]; let length = chunks[0].length;
+objects.forEach((object, index) => { offsets.push(length); const chunk = Buffer.concat([Buffer.from(`${index + 1} 0 obj\n`), object, Buffer.from('\nendobj\n')]); chunks.push(chunk); length += chunk.length; });
+chunks.push(Buffer.from(`xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets.slice(1).map(offset => String(offset).padStart(10, '0') + ' 00000 n \n').join('')}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${length}\n%%EOF\n`));
+writeFileSync(fileURLToPath(new URL('./leafspace-links.pdf', import.meta.url)), Buffer.concat(chunks));
diff --git a/src/tests/fixtures/leafspace-links.pdf b/src/tests/fixtures/leafspace-links.pdf
new file mode 100644
index 0000000..70b38f4
Binary files /dev/null and b/src/tests/fixtures/leafspace-links.pdf differ
diff --git a/src/tests/ui/App.test.tsx b/src/tests/ui/App.test.tsx
index c26e30f..1e9baeb 100644
--- a/src/tests/ui/App.test.tsx
+++ b/src/tests/ui/App.test.tsx
@@ -98,6 +98,15 @@ describe('App document workflows', () => {
expect(recent).toHaveBeenCalledTimes(1);
});
+ it('restores full header-button contrast immediately when a control becomes enabled', async () => {
+ setupDependencies(); openExistingBook(); render();
+ for (const name of ['导入书籍', '保存现场']) {
+ const button = await screen.findByRole('button', { name });
+ expect(button).toHaveClass('transition-colors');
+ for (const unsafe of ['transition', 'transition-opacity', 'transition-all']) expect(button).not.toHaveClass(unsafe);
+ }
+ });
+
it('provides a live autosave getter that blocks an idle registration until import finishes', async () => {
const { register } = setupDependencies();
let finish!: () => void;
diff --git a/src/tests/ui/ReaderGestures.test.tsx b/src/tests/ui/ReaderGestures.test.tsx
index d440c85..69bc868 100644
--- a/src/tests/ui/ReaderGestures.test.tsx
+++ b/src/tests/ui/ReaderGestures.test.tsx
@@ -20,6 +20,20 @@ function setup(overflow = false, canSwipe = true) {
return { view, region, paper, onTurn, onZoom, touch, event };
}
describe('reader touch transactions', () => {
+ it('native suppression distinguishes pointing clicks from Firefox-style keyboard activation', () => {
+ const { event, touch, paper } = setup();
+ const now = vi.spyOn(performance, 'now').mockReturnValue(1000), clicked = vi.fn();
+ paper.addEventListener('click', clicked);
+ try {
+ event('touchstart', [touch(1, 100), touch(2, 200)]); event('touchend', []);
+ const pointer = new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 });
+ Object.defineProperty(pointer, 'pointerId', { value: 7 }); fireEvent(paper, pointer);
+ expect(pointer.defaultPrevented).toBe(true); expect(clicked).not.toHaveBeenCalled();
+ const keyboard = new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 });
+ Object.defineProperty(keyboard, 'pointerId', { value: -1 }); fireEvent(paper, keyboard);
+ expect(keyboard.defaultPrevented).toBe(false); expect(clicked).toHaveBeenCalledOnce();
+ } finally { now.mockRestore(); paper.removeEventListener('click', clicked); }
+ });
it('turns once for a deliberate horizontal swipe but ignores short or vertical movement', () => {
const { event, touch, onTurn } = setup();
event('touchstart', [touch(1, 300)]); event('touchmove', [touch(1, 180)]); event('touchend', [], [touch(1, 180)]);
diff --git a/src/tests/ui/ReaderPdfLinks.test.tsx b/src/tests/ui/ReaderPdfLinks.test.tsx
new file mode 100644
index 0000000..27a7b37
--- /dev/null
+++ b/src/tests/ui/ReaderPdfLinks.test.tsx
@@ -0,0 +1,290 @@
+import { StrictMode, useEffect, useRef, type PropsWithChildren, type Ref } from 'react';
+import type { PDFDocumentProxy } from 'pdfjs-dist';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ReaderViewport } from '../../components/reader/ReaderViewport';
+import { useBookStore } from '../../stores/bookStore';
+import { windowStore } from '../../stores/windowStore';
+import { quickFlipStore } from '../../stores/quickFlipStore';
+import { prepareHeldRead } from '../../services/HeldReadTransaction';
+
+type PdfStub = { numPages: number; getDestination: ReturnType; getPageIndex: ReturnType };
+type PageCallbacks = { onRenderError?: (error: Error) => void; onRenderSuccess?: () => void; onGetAnnotationsSuccess?: (items: unknown[]) => void };
+const life = vi.hoisted(() => ({ nextDocument: 0, documentMounts: 0, documentUnmounts: 0, pageMounts: 0,
+ documents: new Map void }>(), pages: new Map(), nativeClicks: [] as boolean[] }));
+function createPdf(): PdfStub { return { numPages: 12, getDestination: vi.fn().mockResolvedValue([{ num: 7, gen: 0 }]), getPageIndex: vi.fn().mockResolvedValue(2) }; }
+vi.mock('react-pdf', () => ({
+ pdfjs: { GlobalWorkerOptions: {}, version: 'test' },
+ Document: function MockDocument({ children, onLoadSuccess }: PropsWithChildren<{ onLoadSuccess?: (pdf: PDFDocumentProxy) => void }>) {
+ const id = useRef(0); if (!id.current) id.current = ++life.nextDocument;
+ const source = useRef(null); if (!source.current) source.current = createPdf();
+ const pdf = source.current, initial = useRef(onLoadSuccess);
+ life.documents.set(id.current, { pdf, loaded: initial.current });
+ useEffect(() => { life.documentMounts++; initial.current?.(pdf as unknown as PDFDocumentProxy); return () => { life.documentUnmounts++; }; }, [pdf]);
+ return {children}
;
+ },
+ Page: function MockPage(props: PageCallbacks & { pageNumber: number; inputRef?: Ref }) {
+ const id = useRef(0); if (!id.current) id.current = ++life.pageMounts;
+ life.pages.set(id.current, props);
+ const { pageNumber, onGetAnnotationsSuccess } = props;
+ useEffect(() => { onGetAnnotationsSuccess?.([{ id: 'local', annotationType: 2, dest: [6] }, { id: 'external', annotationType: 2, url: 'https://example.com/paper' }]); }, [pageNumber, onGetAnnotationsSuccess]);
+ const native = (event: React.MouseEvent) => { life.nativeClicks.push(event.defaultPrevented); event.preventDefault(); };
+ return ;
+ },
+}));
+vi.mock('../../services/ThumbnailService', () => ({ thumbnailService: { activateDocument: vi.fn(), releaseDocument: vi.fn(), ensureThumbnail: vi.fn().mockResolvedValue(undefined) } }));
+const observers: (() => void)[] = [];
+function load(initialPage = 1) { useBookStore.getState().setDocumentReady({ documentId: 'links', documentUrl: 'memory://links.pdf', totalPages: 12, initialPage }); }
+function Reference({ id }: { id: string }) {
+ const pageNumber = windowStore(state => state.windows.find(window => window.id === id)?.pageNumber ?? 1);
+ return ;
+}
+function geometry(region: HTMLElement) {
+ let width = 400;
+ Object.defineProperties(region, { clientWidth: { configurable: true, get: () => width }, clientHeight: { configurable: true, value: 300 } });
+ act(() => observers.forEach(observer => observer()));
+ return (nextWidth: number) => { width = nextWidth; act(() => observers.forEach(observer => observer())); };
+}
+const main = () => screen.getByRole('region', { name: '主阅读区' });
+const paper = (region: HTMLElement) => region.querySelector('.react-pdf__Page')!;
+const anchor = (region: HTMLElement) => region.querySelector('[data-annotation-id="local"] a')!;
+const pageCallbacks = (region: HTMLElement) => life.pages.get(Number(paper(region).dataset.pageMock))!;
+const documentState = (region: HTMLElement) => life.documents.get(Number(region.querySelector('[data-document]')!.dataset.document))!;
+function metadata(region: HTMLElement, destination: unknown, extra: Record = {}) { pageCallbacks(region).onGetAnnotationsSuccess?.([{ id: 'local', annotationType: 2, dest: destination, ...extra }, { id: 'external', annotationType: 2, url: 'https://example.com/paper' }]); }
+async function activate(region: HTMLElement, destination: unknown, extra: Record = {}) { await act(async () => { metadata(region, destination, extra); fireEvent.click(anchor(region)); }); }
+function deferred() { let resolve!: (value: unknown) => void, reject!: (error: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; }
+async function beginNamed(region: HTMLElement) { const pending = deferred(); documentState(region).pdf.getDestination.mockReturnValueOnce(pending.promise); await activate(region, 'chapter'); return pending; }
+async function resolve(pending: ReturnType, destination: unknown = [{ num: 7, gen: 0 }]) { await act(async () => pending.resolve(destination)); }
+
+beforeEach(() => {
+ useBookStore.getState().reset(); windowStore.getState().reset(); quickFlipStore.getState().reset();
+ Object.assign(life, { nextDocument: 0, documentMounts: 0, documentUnmounts: 0, pageMounts: 0 }); life.documents.clear(); life.pages.clear(); life.nativeClicks.length = 0; observers.length = 0;
+ vi.stubGlobal('ResizeObserver', class { constructor(callback: () => void) { observers.push(callback); } observe() {} disconnect() {} });
+ vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(1); vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});
+});
+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+describe('owner-scoped internal PDF link activation', () => {
+ it.each(['numeric', 'named', 'reference'])('resolves %s once through the captured public PDF proxy', async kind => {
+ load(); useBookStore.getState().setScale(2); render(); const pdf = documentState(main()).pdf;
+ await activate(main(), kind === 'numeric' ? [2] : kind === 'named' ? 'chapter' : [{ num: 7, gen: 0 }]);
+ expect(useBookStore.getState().currentPage).toBe(3); expect(useBookStore.getState().scale).toBe(2);
+ expect(pdf.getDestination).toHaveBeenCalledTimes(kind === 'named' ? 1 : 0);
+ expect(pdf.getPageIndex).toHaveBeenCalledTimes(kind === 'numeric' ? 0 : 1); expect(life.nativeClicks).toEqual([]);
+ });
+ it('treats implicit and explicit main IDs as the same Document owner', async () => {
+ load(); const view = render(); view.rerender();
+ await activate(main(), [6]); expect(useBookStore.getState().currentPage).toBe(7);
+ view.rerender(); await activate(main(), [3]); expect(useBookStore.getState().currentPage).toBe(4); expect(life.documentMounts).toBe(1);
+ });
+ it('keeps delayed reference completion source-owned after activity and focus move to main', async () => {
+ load(4); const id = windowStore.getState().openInNewWindow(1);
+ windowStore.getState().updateWindow(id, { viewport: { scale: 2, mode: 'pointer', scrollTop: 70, scrollLeft: 40 } });
+ render(<>>);
+ const reference = screen.getByRole('region', { name: '参考阅读区,第 1 页' }), pending = await beginNamed(reference);
+ main().focus(); const original = structuredClone(windowStore.getState().windows.find(window => window.id === 'main')); await resolve(pending);
+ expect(windowStore.getState().windows.find(window => window.id === id)?.pageNumber).toBe(3);
+ expect(windowStore.getState().windows.find(window => window.id === id)?.viewport?.scale).toBe(2);
+ expect(windowStore.getState().windows.find(window => window.id === 'main')).toEqual(original);
+ expect(windowStore.getState().activeWindowId).toBe('main'); expect(main()).toHaveFocus(); expect(useBookStore.getState().currentPage).toBe(4);
+ });
+ it('keeps Document alive across navigation, zoom, width, activation and raster retry', async () => {
+ load(); render(); const region = main(), resize = geometry(region), pdf = documentState(region).pdf;
+ await activate(region, [3]); fireEvent.click(screen.getByRole('button', { name: '放大' })); resize(500); region.focus();
+ act(() => pageCallbacks(region).onRenderError?.(new Error('controlled raster failure'))); fireEvent.click(screen.getByRole('button', { name: '重试此页' }));
+ act(() => pageCallbacks(region).onRenderSuccess?.());
+ expect(life.documentMounts).toBe(1); expect(life.documentUnmounts).toBe(0); expect(documentState(region).pdf).toBe(pdf);
+ await activate(region, [8]); expect(useBookStore.getState().currentPage).toBe(9);
+ });
+ it('retains same-page scoped scrolling and annotation focus without a state write', async () => {
+ load(); render(); const region = main(); geometry(region); await activate(region, [5]);
+ const scroll = vi.fn(); paper(region).scrollIntoView = scroll; anchor(region).focus(); const windows = windowStore.getState().windows, focus = vi.spyOn(region, 'focus');
+ await activate(region, [5]); expect(scroll).toHaveBeenCalledOnce(); expect(windowStore.getState().windows).toBe(windows); expect(anchor(region)).toHaveFocus(); expect(focus).not.toHaveBeenCalled();
+ });
+ it('rejects old sessions before commit and accepts a fresh same-URL source', async () => {
+ load(); render(); const old = documentState(main()), pending = await beginNamed(main());
+ act(() => { load(4); old.loaded?.(old.pdf as unknown as PDFDocumentProxy); }); await resolve(pending);
+ expect(useBookStore.getState().currentPage).toBe(4); expect(life.documentMounts).toBe(2); expect(life.documentUnmounts).toBe(1);
+ await activate(main(), [7]); expect(useBookStore.getState().currentPage).toBe(8); expect(documentState(main()).pdf).not.toBe(old.pdf);
+ });
+ it('rejects a source URL replacement even if the session is unchanged', async () => {
+ load(); render(); const pending = await beginNamed(main());
+ act(() => useBookStore.setState({ documentUrl: 'memory://replacement.pdf' })); await resolve(pending); expect(useBookStore.getState().currentPage).toBe(1);
+ await activate(main(), [6]); expect(useBookStore.getState().currentPage).toBe(7); expect(life.documentMounts).toBe(2);
+ });
+ it.each([false, true])('rejects unmounted readers even after same-session replacement (StrictMode %s)', async strict => {
+ load(); const node = () => strict ? : ;
+ const view = render(node()), pending = await beginNamed(main()); view.unmount(); render(node()); await resolve(pending);
+ expect(useBookStore.getState().currentPage).toBe(1); await activate(main(), [6]); expect(useBookStore.getState().currentPage).toBe(7);
+ });
+ it('rejects closed and replaced originating windows', async () => {
+ load(); const first = windowStore.getState().openInNewWindow(1), second = windowStore.getState().openInNewWindow(2);
+ const view = render(), pending = await beginNamed(screen.getByRole('region')); view.rerender(); await resolve(pending);
+ expect(windowStore.getState().windows.find(window => window.id === first)?.pageNumber).toBe(1);
+ const region = screen.getByRole('region'); await activate(region, [6]); expect(windowStore.getState().windows.find(window => window.id === second)?.pageNumber).toBe(7);
+ const closing = await beginNamed(region); act(() => windowStore.getState().closeWindow(second)); await resolve(closing);
+ expect(windowStore.getState().windows.find(window => window.id === second)).toBeUndefined(); expect(screen.queryByText(/无法打开此链接/)).toBeNull();
+ });
+ it('hands departing annotation focus back before the page-store mutation', async () => {
+ load(); render(); const region = main(); geometry(region); anchor(region).focus();
+ const observed: (Element | null)[] = [], stop = windowStore.subscribe((next, prev) => { if (next.windows[0].pageNumber !== prev.windows[0].pageNumber) observed.push(document.activeElement); });
+ const focus = vi.spyOn(region, 'focus'); await activate(region, [6]); stop();
+ expect(observed).toEqual([region]); expect(region).toHaveFocus(); expect(focus).toHaveBeenCalledWith({ preventScroll: true });
+ fireEvent.keyDown(region, { key: 'ArrowRight' }); expect(useBookStore.getState().currentPage).toBe(8);
+ });
+ it.each(['toolbar', 'page-input', 'body', 'reader'])('preserves newer %s focus during resolution', async target => {
+ load(); render(<>>); const region = main(); geometry(region); anchor(region).focus();
+ const pending = await beginNamed(region), newer = target === 'toolbar' ? screen.getByRole('button', { name: '放大' }) : target === 'page-input' ? screen.getByRole('textbox') : target === 'reader' ? region : document.body;
+ if (target === 'body') anchor(region).blur(); else newer.focus(); const focus = vi.spyOn(region, 'focus'); await resolve(pending);
+ expect(document.activeElement).toBe(newer); expect(focus).not.toHaveBeenCalled(); expect(useBookStore.getState().currentPage).toBe(3);
+ });
+ it.each(['hidden', 'inert', 'inactive'])('does not focus an annotation owner that became %s', async condition => {
+ load(); const other = windowStore.getState().openInNewWindow(1); render(); const region = main(), resize = geometry(region); anchor(region).focus(); const pending = await beginNamed(region);
+ if (condition === 'hidden') resize(0); if (condition === 'inert') region.setAttribute('inert', ''); if (condition === 'inactive') act(() => windowStore.getState().setActiveWindow(other));
+ const focus = vi.spyOn(region, 'focus'); await resolve(pending); expect(focus).not.toHaveBeenCalled(); expect(useBookStore.getState().currentPage).toBe(3);
+ });
+ it.each(['manual', 'away-back', 'link'])('a newer %s navigation permanently supersedes an older named link', async kind => {
+ load(); render(); const region = main(), pending = await beginNamed(region);
+ if (kind === 'link') await activate(region, [1]);
+ else act(() => { useBookStore.getState().setCurrentPage(2); if (kind === 'away-back') useBookStore.getState().setCurrentPage(1); });
+ await resolve(pending); expect(useBookStore.getState().currentPage).toBe(kind === 'away-back' ? 1 : 2);
+ });
+ it('a newer same-page link supersedes an older request without a page transition', async () => {
+ load(); render(); const region = main(), pending = await beginNamed(region);
+ await activate(region, [0]); await resolve(pending); expect(useBookStore.getState().currentPage).toBe(1);
+ });
+ it.each(['main', 'reference'])('a newer same-page choice in %s permanently cancels a pending named link', async kind => {
+ load(); const id = kind === 'main' ? 'main' : windowStore.getState().openInNewWindow(1);
+ render(kind === 'main' ? : );
+ const region = screen.getByRole('region');
+ for (const action of ['Home', 'active-navigation'] as const) {
+ const pending = await beginNamed(region);
+ if (action === 'Home') fireEvent.keyDown(region, { key: 'Home' });
+ else act(() => windowStore.getState().navigateActive(1));
+ await resolve(pending);
+ expect(windowStore.getState().windows.find(window => window.id === id)?.pageNumber).toBe(1);
+ }
+ });
+ it.each([1, 5])('preparing a held read to page %s supersedes an older link before its delayed commit', async target => {
+ load(); render(); const pending = await beginNamed(main());
+ let prepared!: ReturnType; act(() => { prepared = prepareHeldRead(target); });
+ await resolve(pending); expect(useBookStore.getState().currentPage).toBe(1);
+ act(() => { expect(prepared.commit()).toBe(true); });
+ expect(useBookStore.getState().currentPage).toBe(target); prepared.dispose();
+ });
+ it('reference geometry, activation and viewport writes do not supersede its pending link', async () => {
+ load(); const id = windowStore.getState().openInNewWindow(1); render();
+ const region = screen.getByRole('region'), pending = await beginNamed(region);
+ act(() => { windowStore.getState().setActiveWindow('main'); windowStore.getState().updateWindow(id, { x: 90, width: 400, isActive: true, zIndex: 5 });
+ windowStore.getState().updateWindow(id, { viewport: { scale: 2, scrollLeft: 20, scrollTop: 30 } }); });
+ await resolve(pending); expect(windowStore.getState().windows.find(window => window.id === id)?.pageNumber).toBe(3);
+ });
+ it('cancels during indirect reference resolution and catches a current reference rejection', async () => {
+ load(); render(); const region = main(), pdf = documentState(region).pdf;
+ const pending = deferred(); pdf.getPageIndex.mockReturnValueOnce(pending.promise);
+ await activate(region, [{ num: 7, gen: 0 }]); act(() => useBookStore.getState().setCurrentPage(1)); await resolve(pending, 2);
+ expect(useBookStore.getState().currentPage).toBe(1);
+ pdf.getPageIndex.mockRejectedValueOnce(new Error('missing reference')); await activate(region, [{ num: 7, gen: 0 }]);
+ expect(screen.getByRole('alert')).toHaveTextContent('无法打开此链接'); expect(useBookStore.getState().currentPage).toBe(1);
+ });
+ it('raster retry retires a pending link without reparsing the document', async () => {
+ load(); render(); const region = main(), pending = await beginNamed(region), pdf = documentState(region).pdf;
+ act(() => pageCallbacks(region).onRenderError?.(new Error('raster'))); fireEvent.click(screen.getByRole('button', { name: '重试此页' }));
+ await resolve(pending); expect(useBookStore.getState().currentPage).toBe(1); expect(documentState(region).pdf).toBe(pdf);
+ });
+ it.each(['main', 'reference'])('Escape dismisses the %s link notice before any window-close handler', async kind => {
+ load(); const id = windowStore.getState().openInNewWindow(1);
+ render(kind === 'main' ? : );
+ const region = screen.getByRole('region'), escaped = vi.fn(); window.addEventListener('keydown', escaped);
+ try {
+ await activate(region, [-1]); fireEvent.keyDown(screen.getByRole('button', { name: '关闭链接提示' }), { key: 'Escape' });
+ expect(screen.queryByRole('alert')).toBeNull(); expect(region).toHaveFocus(); expect(escaped).not.toHaveBeenCalled();
+ expect(windowStore.getState().windows).toHaveLength(2);
+ } finally { window.removeEventListener('keydown', escaped); }
+ });
+ it.each(['keyboard', 'keyboard-pointer', 'later-pointer'])('blocks post-pinch link ghost clicks while preserving %s activation', async next => {
+ load(); render(); const region = main(); geometry(region);
+ const frame = region.querySelector('.w-max')!;
+ vi.spyOn(frame, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 402, 602));
+ const now = vi.spyOn(performance, 'now').mockReturnValue(1000), pdf = documentState(region).pdf;
+ const touch = (identifier: number, clientX: number) => ({ identifier, clientX, clientY: 100, target: region });
+ const start = [touch(1, 100), touch(2, 200)];
+ fireEvent(region, new TouchEvent('touchstart', { bubbles: true, cancelable: true, touches: start as unknown as Touch[] }));
+ fireEvent(region, new TouchEvent('touchend', { bubbles: true, cancelable: true, touches: [], changedTouches: start as unknown as Touch[] }));
+ await act(async () => {
+ metadata(region, 'chapter');
+ const ghost = new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 });
+ Object.defineProperty(ghost, 'pointerId', { value: 7 }); fireEvent(anchor(region), ghost);
+ });
+ expect(pdf.getDestination).not.toHaveBeenCalled(); expect(useBookStore.getState().currentPage).toBe(1);
+ if (next === 'later-pointer') now.mockReturnValue(1601);
+ await act(async () => {
+ const event = new MouseEvent('click', { bubbles: true, cancelable: true, detail: next === 'keyboard' ? 0 : 1 });
+ if (next === 'keyboard-pointer') Object.defineProperty(event, 'pointerId', { value: -1 });
+ fireEvent(anchor(region), event);
+ });
+ expect(pdf.getDestination).toHaveBeenCalledOnce(); expect(useBookStore.getState().currentPage).toBe(3);
+ });
+ it('repeated same-destination activations complete only the latest ticket', async () => {
+ load(); render(); const region = main(); geometry(region); const scroll = vi.fn(); paper(region).scrollIntoView = scroll;
+ const first = await beginNamed(region), second = await beginNamed(region); await resolve(second, [0]); await resolve(first, [0]);
+ expect(scroll).toHaveBeenCalledOnce(); expect(useBookStore.getState().currentPage).toBe(1); expect(documentState(region).pdf.getDestination).toHaveBeenCalledTimes(2);
+ });
+ it.each(['open', 'cancel', 'commit'])('QuickFlip %s supersedes the originating reader link', async kind => {
+ load(); render(); const pending = await beginNamed(main());
+ act(() => { quickFlipStore.getState().open(); if (kind === 'commit') { quickFlipStore.getState().setSelectedPage(2); quickFlipStore.getState().commitSelection(); } else if (kind === 'cancel') quickFlipStore.getState().close(); });
+ await resolve(pending); expect(useBookStore.getState().currentPage).toBe(kind === 'commit' ? 2 : 1);
+ });
+ it('another pane opening QuickFlip does not cancel the source reader', async () => {
+ load(); const id = windowStore.getState().openInNewWindow(4); render(<>>);
+ const reference = screen.getByRole('region', { name: '参考阅读区,第 4 页' }), pending = await beginNamed(reference); main().focus(); act(() => quickFlipStore.getState().open()); await resolve(pending);
+ expect(windowStore.getState().windows.find(window => window.id === id)?.pageNumber).toBe(3); expect(useBookStore.getState().currentPage).toBe(1); expect(main()).toHaveFocus();
+ });
+ it('ignores old page/retry metadata and prevents stale internal native activation', async () => {
+ load(); render(); const region = main(), old = pageCallbacks(region);
+ act(() => { useBookStore.getState().setCurrentPage(2); });
+ await act(async () => { old.onGetAnnotationsSuccess?.([{ id: 'local', annotationType: 2, dest: [9] }]); fireEvent.click(anchor(region)); });
+ expect(useBookStore.getState().currentPage).toBe(7);
+ const beforeRetry = pageCallbacks(region); act(() => beforeRetry.onRenderError?.(new Error('raster'))); fireEvent.click(screen.getByRole('button', { name: '重试此页' }));
+ await act(async () => { beforeRetry.onGetAnnotationsSuccess?.([{ id: 'local', annotationType: 2, dest: [9] }]); fireEvent.click(anchor(region)); });
+ expect(useBookStore.getState().currentPage).toBe(7);
+ await activate(region, [3]); expect(useBookStore.getState().currentPage).toBe(4); expect(life.nativeClicks).toEqual([]);
+ });
+ it('blocks uncached or stale internal anchors without intercepting an external URI', async () => {
+ load(); render(); const region = main();
+ await act(async () => { pageCallbacks(region).onGetAnnotationsSuccess?.([]); fireEvent.click(anchor(region)); });
+ expect(useBookStore.getState().currentPage).toBe(1); expect(life.nativeClicks).toEqual([]);
+ fireEvent.click(region.querySelector('[data-annotation-id="external"] a')!); expect(life.nativeClicks).toEqual([false]);
+ await act(async () => { metadata(region, [6]); paper(region).dataset.pageNumber = '9'; fireEvent.click(anchor(region)); });
+ expect(useBookStore.getState().currentPage).toBe(1); expect(life.nativeClicks).toEqual([false]);
+ });
+ it('does not start a new internal request inside an inert or QuickFlip-owned reader', async () => {
+ load(); render(); const region = main(), pdf = documentState(region).pdf;
+ region.setAttribute('inert', ''); await activate(region, 'chapter'); region.removeAttribute('inert');
+ act(() => quickFlipStore.getState().open()); await activate(region, 'chapter');
+ expect(pdf.getDestination).not.toHaveBeenCalled(); expect(useBookStore.getState().currentPage).toBe(1); expect(life.nativeClicks).toEqual([]);
+ });
+ it.each(['url', 'action', 'attachment', 'setOCGState'])('preserves higher-priority %s annotations and external links', async field => {
+ load(); render(); await activate(main(), [6], { [field]: field === 'url' ? 'https://example.com/paper' : {} });
+ fireEvent.click(main().querySelector('[data-annotation-id="external"] a')!);
+ expect(life.nativeClicks).toEqual([false, false]); expect(useBookStore.getState().currentPage).toBe(1);
+ });
+ it.each([null, [], [-1], [1.5], [NaN], [Infinity], [12], [{}]])('reports an invalid owned destination %j without changing page or focus', async destination => {
+ load(); render(); const region = main(); geometry(region); anchor(region).focus();
+ if (destination === null) { documentState(region).pdf.getDestination.mockResolvedValueOnce(null); await activate(region, 'missing'); }
+ else await activate(region, destination);
+ expect(screen.getByRole('alert')).toHaveTextContent('无法打开此链接'); expect(useBookStore.getState().currentPage).toBe(1); expect(anchor(region)).toHaveFocus();
+ fireEvent.click(screen.getByRole('button', { name: '关闭链接提示' })); expect(region).toHaveFocus(); expect(screen.queryByRole('alert')).toBeNull();
+ });
+ it('reports only a current rejection; superseded failures never publish a notice', async () => {
+ load(); render(); const region = main(); const old = await beginNamed(region); await activate(region, [1]);
+ await act(async () => old.reject(new Error('retired read failure'))); expect(screen.queryByRole('alert')).toBeNull();
+ const current = await beginNamed(region); await act(async () => current.reject(new Error('current read failure'))); expect(screen.getByRole('alert')).toHaveTextContent('无法打开此链接');
+ await activate(region, [3]); expect(screen.queryByRole('alert')).toBeNull(); expect(useBookStore.getState().currentPage).toBe(4);
+ });
+});
diff --git a/src/tests/ui/TimelineBar.test.tsx b/src/tests/ui/TimelineBar.test.tsx
index f46420d..05a4e3c 100644
--- a/src/tests/ui/TimelineBar.test.tsx
+++ b/src/tests/ui/TimelineBar.test.tsx
@@ -14,6 +14,15 @@ function setup() {
}
describe('timeline preview', () => {
+ it('announces only accepted preview starts before changing or saving a page', () => {
+ const navigate = vi.fn(), start = vi.fn();
+ render();
+ const slider = screen.getByRole('slider'); slider.setPointerCapture = vi.fn();
+ fireEvent.pointerDown(slider, { pointerId: 1, button: 2 }); expect(start).not.toHaveBeenCalled();
+ fireEvent.pointerDown(slider, { pointerId: 1, button: 0 }); expect(start).toHaveBeenCalledOnce();
+ fireEvent.pointerDown(slider, { pointerId: 2, button: 0 }); expect(start).toHaveBeenCalledOnce();
+ expect(navigate).not.toHaveBeenCalled();
+ });
it('previews without navigation, commits once on release, and keeps keyboard changes immediate', () => {
const { start, move, end, navigate, slider } = setup();
start(); move();