From 68a24129b702083e2df7e5669e50931cb5c24a0b Mon Sep 17 00:00:00 2001 From: nkAnF Date: Sun, 4 Oct 2026 08:53:42 +0800 Subject: [PATCH 1/3] fix: follow internal PDF links in their originating reader --- README.md | 1 + playwright.config.ts | 6 +- src/components/reader/ReaderViewport.tsx | 38 ++++ src/tests/e2e/README.md | 5 + src/tests/e2e/pdf-links.test.ts | 134 ++++++++++++++ src/tests/fixtures/README.md | 2 + src/tests/fixtures/generate-linked-pages.mjs | 26 +++ src/tests/fixtures/leafspace-links.pdf | Bin 0 -> 2701 bytes src/tests/ui/ReaderPdfLinks.test.tsx | 177 +++++++++++++++++++ 9 files changed, 386 insertions(+), 3 deletions(-) create mode 100644 src/tests/e2e/pdf-links.test.ts create mode 100644 src/tests/fixtures/generate-linked-pages.mjs create mode 100644 src/tests/fixtures/leafspace-links.pdf create mode 100644 src/tests/ui/ReaderPdfLinks.test.tsx diff --git a/README.md b/README.md index 353c84a..e6b0881 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ npm run test:e2e - 浮窗拖动、缩放和分栏调整在失焦、切换标签页或松开鼠标时结束;拖动中按 Esc 只取消本次拖动,不关闭窗口 - 最多新建 4 个参考窗口。可选择并排或平铺 2–5 页;手机通过「打开的页面」切换主视角与参考页 - 速翻、目录、底部时间轴和页码输入跟随当前活动窗口。页码输入按 Enter 确认,Esc 取消 +- PDF 内部链接在原阅读窗口打开目标页,保留其他窗口的位置和缩放;用 Enter 跳到其他页后,可继续用方向键翻页。链接解析期间若已把焦点移到工具栏或其他窗口,不会把焦点抢回 - 最多新增到 12 张夹页,可通过上下移动按钮调整顺序;移除正在对照的夹页时可选择是否保留窗口 - 点击左上角 LeafSpace 回到书库。切换书籍、回到书库前,会先保存当前现场 - 页码、缩放、夹页与窗口布局在操作停止后自动保存;切到后台时会尽早尝试保存待存更改。只有真正保存完成才显示「已保存到本机」。存储失败或上次现场未恢复时仍需明确重试,后台保存不能保证在系统结束进程前完成 diff --git a/playwright.config.ts b/playwright.config.ts index 6b2c431..fefefec 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', '**/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', '**/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', '**/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', '**/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', '**/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', '**/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/components/reader/ReaderViewport.tsx b/src/components/reader/ReaderViewport.tsx index 652d2bc..1374fa3 100644 --- a/src/components/reader/ReaderViewport.tsx +++ b/src/components/reader/ReaderViewport.tsx @@ -71,6 +71,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 +94,37 @@ export const ReaderViewport: React.FC = ({ pageNumber, isMain = false, wi renderGeneration.current += 1; }; }, []); + const effectiveWindowId = windowId ?? 'main'; + const linkOwner = useMemo(() => ({ sessionId, documentUrl, windowId: effectiveWindowId }), [sessionId, documentUrl, effectiveWindowId]); + const liveLinkOwner = useRef(linkOwner); + useLayoutEffect(() => { + liveLinkOwner.current = linkOwner; + return () => { if (liveLinkOwner.current === linkOwner) liveLinkOwner.current = null; }; + }, [linkOwner]); + const handlePdfLink = useCallback(({ pageNumber: destination }: { pageNumber: number }) => { + const book = useBookStore.getState(), workspace = useWindowStore.getState(); + if (!mounted.current || liveLinkOwner.current !== linkOwner || book.status !== 'ready' + || book.sessionId !== linkOwner.sessionId || book.documentUrl !== linkOwner.documentUrl + || !Number.isInteger(destination) || destination < 1 || destination > book.totalPages) return; + const origin = workspace.windows.find(window => window.id === linkOwner.windowId); + if (!origin) return; + const container = containerRef.current, pageElement = pageElementRef.current; + const visibleOwner = container?.isConnected && container.clientWidth > 0 && container.clientHeight > 0 && !container.closest('[inert]'); + const currentPageElement = pageElement?.isConnected && container?.contains(pageElement) + && pageElement.dataset.pageNumber === String(origin.pageNumber); + if (origin.pageNumber === destination) { + // Preserve React-PDF's existing same-page behavior, scoped to this pane. + if (visibleOwner && currentPageElement) pageElement.scrollIntoView(); + return; + } + // The departing annotation will disappear. Hand back only focus it still + // owns; asynchronous completion must not steal newer pane/toolbar focus. + if (visibleOwner && currentPageElement && workspace.activeWindowId === linkOwner.windowId + && pageElement.querySelector('.annotationLayer')?.contains(document.activeElement)) { + container.focus({ preventScroll: true }); + } + workspace.updateWindow(linkOwner.windowId, { pageNumber: destination }); + }, [linkOwner]); const [renderFeedback, setRenderFeedback] = useState(null); const showRenderFailure = renderFeedback?.kind === 'failed' && renderFeedback.token === renderToken; const showRenderRetry = renderFeedback?.kind === 'retrying' && renderFeedback.context === renderContext && renderFeedback.attempt === retryAttempt; @@ -722,13 +754,19 @@ 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={
正在渲染...
} > region.locator(`.annotationLayer [data-annotation-id="${id}"] a`); +type LinkGate = { holding: boolean; queued: number; workers: number; release: () => void }; +const gate = (page: Page) => page.evaluate(() => { + const { holding, queued, workers } = (window as unknown as { leafspaceLinkGate: LinkGate }).leafspaceLinkGate; + return { holding, queued, workers }; +}); +async function installGate(page: Page) { + await page.addInitScript(() => { + const pending: (() => void)[] = []; + const state = { holding: false, queued: 0, workers: 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 { + constructor(url: string | URL, options?: WorkerOptions) { super(url, options); state.workers++; } + postMessage(message: unknown, options?: StructuredSerializeOptions | Transferable[]) { + const request = message as { action?: string; data?: { id?: string } }; + 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 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' }); + }); +} diff --git a/src/tests/fixtures/README.md b/src/tests/fixtures/README.md index ef1f5b4..5ace96c 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, licensed, or external 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 contains no JavaScript, form, password or malformed destination. Regenerate with `node src/tests/fixtures/generate-linked-pages.mjs` using only Node built-ins. Standard Courier keeps fixture label metrics reproducible. SHA-256: `d27092b1a73d6e207a3eaa3a521344edc0df846d7a50a22ea6f7123c6c916f16`. + `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..4e625d8 --- /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)'] : ['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' : `${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]']; +actions.forEach((action, index) => { + const row = index < 5 ? index : 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 0000000000000000000000000000000000000000..528b4ec7607796f215881fe60ab057a48a7fe574 GIT binary patch literal 2701 zcmcImT~Fdb6n*cnxGyI7Ano*l<`q|bl`g=%=L?a8jSeF)@Aw)o$m?3< zs`#(4O*_$&XG+LZmK1Z6rbRa7vq(oLek0rO`(%VFy1B%c1% z2`N>Xgl;yIP_t5Cl5MxY#4P6h^bMvK`n$FTUeA33b0qR~BctskgA^lZqydATE?2aS z4J8V*<=|?od6^_BUQHQg8v!HG@T(}sihh~)t+q;rveltT7HSDj;L$9(l7g=dtBV=B zIB3@axd7_Yx4;Q4z+_Uu+@N|E-ZT0W-6acQG6x48od6~?=nMs)k24+#SjEX}4rf4^ z0y~At3*1b0akh^0z{3$J?ryUdGLCcgiTH9Sx|PHCc7c|#6mJ6ql`*FWG560qwKae^-8yaU-F`6FViLu{=~Q{I-46&weUrm{6-K z!)w|FD2u2~sQA@7&9!o*j!Vjib=;8hzFTL%XZGtrYw)KAa#=Bu>$DG4S!30qn!D%7 zP&APK>$MJrP&UA;E{@_!AFG4J)pgwWX1dfnZVcwb=(hOiES1XgAEqhZ_&QsOZj`Rg zjAyjN^$IMvEn-zC-H}#4!k2eOu4>+gM*hD#Z&J`wWr1PsUf_EkYUv#IHau$df@Ei7 z3_GmbLPV!#bG)Ws5aMa5`Somk$cHw@aAVeOwvVK%`MF-BKjzuU*_xm4H0rXzY4pcJ zx7kb2MaewOXIo*ThRu4F8cOnbC8Yi>IgbD0&yWC>Buy2N9E|8F<%&zCpMq`oJmci# I=J&w(2Vc~|6951J literal 0 HcmV?d00001 diff --git a/src/tests/ui/ReaderPdfLinks.test.tsx b/src/tests/ui/ReaderPdfLinks.test.tsx new file mode 100644 index 0000000..161511b --- /dev/null +++ b/src/tests/ui/ReaderPdfLinks.test.tsx @@ -0,0 +1,177 @@ +import { useEffect, useRef, type PropsWithChildren, type Ref } from 'react'; +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'; + +type LinkCallback = (target: { pageNumber: number }) => void; +type PageCallbacks = { onRenderError?: (error: Error) => void; onRenderSuccess?: () => void }; +const life = vi.hoisted(() => ({ nextDocument: 0, documentMounts: 0, documentUnmounts: 0, pageMounts: 0, + initialLinks: new Map(), pages: new Map() })); +vi.mock('react-pdf', () => ({ + pdfjs: { GlobalWorkerOptions: {}, version: 'test' }, + Document: function MockDocument({ children, onItemClick }: PropsWithChildren<{ onItemClick?: LinkCallback }>) { + const id = useRef(0); if (!id.current) id.current = ++life.nextDocument; + // React-PDF's viewer captures its initial callback in useRef. Reading the + // latest prop here would hide document-replacement ownership defects. + const initial = useRef(onItemClick); life.initialLinks.set(id.current, initial.current); + useEffect(() => { life.documentMounts++; return () => { life.documentUnmounts++; }; }, []); + 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); + return ; + }, +})); +vi.mock('../../services/ThumbnailService', () => ({ thumbnailService: { activateDocument: vi.fn(), releaseDocument: vi.fn(), ensureThumbnail: vi.fn().mockResolvedValue(undefined) } })); +const observers: (() => void)[] = []; +function load(initialPage = 3) { + 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())); }; +} +function callback(region: HTMLElement) { return life.initialLinks.get(Number(region.querySelector('[data-document]')!.getAttribute('data-document'))); } +function navigate(link: LinkCallback | undefined, pageNumber: number) { act(() => link?.({ pageNumber })); } +const main = () => screen.getByRole('region', { name: '主阅读区' }); +const paper = (region: HTMLElement) => region.querySelector('.react-pdf__Page')!; +const anchor = (region: HTMLElement) => region.querySelector('.annotationLayer a')!; + +beforeEach(() => { + useBookStore.getState().reset(); windowStore.getState().reset(); + Object.assign(life, { nextDocument: 0, documentMounts: 0, documentUnmounts: 0, pageMounts: 0 }); life.initialLinks.clear(); life.pages.clear(); 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 links', () => { + it('navigates main using the resolved page and keeps its independent scale', () => { + load(); useBookStore.getState().setScale(2); render(); + navigate(callback(main()), 7); + expect(useBookStore.getState().currentPage).toBe(7); expect(useBookStore.getState().scale).toBe(2); + expect(windowStore.getState().windows[0].pageNumber).toBe(7); + }); + + it('treats implicit and explicit main IDs as the same Document owner', () => { + load(); const view = render(); const initial = callback(main()); + view.rerender(); navigate(initial, 7); + expect(useBookStore.getState().currentPage).toBe(7); + view.rerender(); navigate(initial, 4); + expect(useBookStore.getState().currentPage).toBe(4); expect(life.documentMounts).toBe(1); + }); + + it('keeps delayed reference completion owned by its source after activity and focus move elsewhere', () => { + load(); 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 页' }), link = callback(reference); + main().focus(); const originalMain = structuredClone(windowStore.getState().windows.find(window => window.id === 'main')); + navigate(link, 8); + const current = windowStore.getState(); + expect(current.windows.find(window => window.id === id)?.pageNumber).toBe(8); + expect(current.windows.find(window => window.id === id)?.viewport?.scale).toBe(2); + expect(current.windows.find(window => window.id === 'main')).toEqual(originalMain); + expect(current.activeWindowId).toBe('main'); expect(main()).toHaveFocus(); expect(useBookStore.getState().currentPage).toBe(3); + }); + + it('retains initial Document callbacks through page, zoom, width, activation and raster retry changes', () => { + load(); render(); const region = main(), resize = geometry(region), link = callback(region); + navigate(link, 4); fireEvent.click(screen.getByRole('button', { name: '放大' })); resize(500); region.focus(); + act(() => life.pages.get(life.pageMounts)?.onRenderError?.(new Error('controlled raster failure'))); + fireEvent.click(screen.getByRole('button', { name: '重试此页' })); + act(() => life.pages.get(life.pageMounts)?.onRenderSuccess?.()); + expect(life.documentMounts).toBe(1); expect(life.documentUnmounts).toBe(0); expect(callback(region)).toBe(link); + navigate(link, 9); expect(useBookStore.getState().currentPage).toBe(9); + }); + + it('keeps same-page scrolling scoped to the currently displayed Page without moving focus', () => { + load(); render(); const region = main(); geometry(region); + navigate(callback(region), 6); const scroll = vi.fn(); paper(region).scrollIntoView = scroll; anchor(region).focus(); + const windows = windowStore.getState().windows, focus = vi.spyOn(region, 'focus'); + navigate(callback(region), 6); + expect(scroll).toHaveBeenCalledOnce(); expect(windowStore.getState().windows).toBe(windows); + expect(anchor(region)).toHaveFocus(); expect(focus).not.toHaveBeenCalled(); + }); + + it('rejects a retired session before commit and accepts links from a fresh same-URL Document', () => { + load(); render(); const old = callback(main()); + act(() => { load(4); old?.({ pageNumber: 9 }); }); + expect(useBookStore.getState().currentPage).toBe(4); expect(life.documentMounts).toBe(2); expect(life.documentUnmounts).toBe(1); + navigate(callback(main()), 8); expect(useBookStore.getState().currentPage).toBe(8); + navigate(old, 2); expect(useBookStore.getState().currentPage).toBe(8); + }); + + it('retires a source URL change even when its session number is retained', () => { + load(); render(); const old = callback(main()); + act(() => useBookStore.setState({ documentUrl: 'memory://replacement.pdf' })); + navigate(old, 10); expect(useBookStore.getState().currentPage).toBe(3); + navigate(callback(main()), 7); expect(useBookStore.getState().currentPage).toBe(7); expect(life.documentMounts).toBe(2); + }); + + it('rejects callbacks from an unmounted reader even if a replacement uses the same session', () => { + load(); const view = render(); const old = callback(main()); view.unmount(); + render(); navigate(old, 10); + expect(useBookStore.getState().currentPage).toBe(3); navigate(callback(main()), 7); expect(useBookStore.getState().currentPage).toBe(7); + }); + + it('rejects a closed origin and never redirects a stale owner callback to another reader', () => { + load(); const first = windowStore.getState().openInNewWindow(1), second = windowStore.getState().openInNewWindow(2); + const view = render(); const old = callback(screen.getByRole('region')); + view.rerender(); navigate(old, 8); + expect(windowStore.getState().windows.find(window => window.id === first)?.pageNumber).toBe(1); + navigate(callback(screen.getByRole('region')), 7); expect(windowStore.getState().windows.find(window => window.id === second)?.pageNumber).toBe(7); + const retired = callback(screen.getByRole('region')); + act(() => { windowStore.getState().closeWindow(second); retired?.({ pageNumber: 6 }); }); + expect(windowStore.getState().windows.find(window => window.id === second)).toBeUndefined(); + }); + + it('hands disappearing annotation focus to its reader before cross-page navigation', () => { + load(); render(); const region = main(); geometry(region); anchor(region).focus(); + const observedFocus: (Element | null)[] = []; + const unsubscribe = windowStore.subscribe((state, previous) => { + if (state.windows[0].pageNumber !== previous.windows[0].pageNumber) observedFocus.push(document.activeElement); + }); + const focus = vi.spyOn(region, 'focus'); navigate(callback(region), 7); unsubscribe(); + expect(observedFocus).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 without redundant handback', target => { + load(); render(<>); const region = main(); geometry(region); + anchor(region).focus(); + const 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'); navigate(callback(region), 7); + expect(document.activeElement).toBe(newer); expect(focus).not.toHaveBeenCalled(); expect(useBookStore.getState().currentPage).toBe(7); + }); + + it.each(['hidden', 'inert', 'inactive'])('does not focus an annotation owner that became %s', condition => { + load(); const other = windowStore.getState().openInNewWindow(1); render(); + const region = main(), resize = geometry(region); anchor(region).focus(); + 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'); navigate(callback(region), 7); + expect(focus).not.toHaveBeenCalled(); expect(useBookStore.getState().currentPage).toBe(7); + }); + + it('validates destination bounds before any navigation or focus write', () => { + load(); render(); const region = main(); geometry(region); anchor(region).focus(); + const windows = windowStore.getState().windows, focus = vi.spyOn(region, 'focus'); + for (const value of [0, -1, 1.5, NaN, Infinity, 13]) navigate(callback(region), value); + expect(windowStore.getState().windows).toBe(windows); expect(anchor(region)).toHaveFocus(); expect(focus).not.toHaveBeenCalled(); + }); +}); From af72ee036db743b15f4dbfa924c72c5c0768004b Mon Sep 17 00:00:00 2001 From: nkAnF Date: Sun, 4 Oct 2026 13:14:15 +0800 Subject: [PATCH 2/3] fix: preserve Firefox keyboard links after touch gestures Recognize the native non-pointing pointer ID in both React and native click guards. Keep real ghost clicks suppressed and retain the browser activation assertion. Add responsive missing-link feedback evidence. Co-authored-by: Codex --- src/hooks/useReaderGestures.ts | 10 +++++++--- src/tests/e2e/pdf-links.test.ts | 13 +++++++++++++ src/tests/ui/ReaderGestures.test.tsx | 14 ++++++++++++++ src/tests/ui/ReaderPdfLinks.test.tsx | 14 +++++++++++--- 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/hooks/useReaderGestures.ts b/src/hooks/useReaderGestures.ts index d0305ec..979dd32 100644 --- a/src/hooks/useReaderGestures.ts +++ b/src/hooks/useReaderGestures.ts @@ -32,9 +32,13 @@ export function useReaderGestures(options: Options) { 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. Keyboard activation (detail=0) stays available. - const suppressClick = useCallback((event: Pick) => { - if (event.detail === 0 || performance.now() >= suppressClickUntil.current) return false; + // 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; }, []); diff --git a/src/tests/e2e/pdf-links.test.ts b/src/tests/e2e/pdf-links.test.ts index 6ff0733..6f50f0b 100644 --- a/src/tests/e2e/pdf-links.test.ts +++ b/src/tests/e2e/pdf-links.test.ts @@ -185,12 +185,25 @@ test('missing internal destination has dismissible feedback and keeps a referenc 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); 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 index 7f3b0b8..27a7b37 100644 --- a/src/tests/ui/ReaderPdfLinks.test.tsx +++ b/src/tests/ui/ReaderPdfLinks.test.tsx @@ -207,7 +207,7 @@ describe('owner-scoped internal PDF link activation', () => { expect(windowStore.getState().windows).toHaveLength(2); } finally { window.removeEventListener('keydown', escaped); } }); - it.each(['keyboard', 'later-pointer'])('blocks post-pinch link ghost clicks while preserving %s activation', async next => { + 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)); @@ -216,10 +216,18 @@ describe('owner-scoped internal PDF link activation', () => { 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'); fireEvent.click(anchor(region), { detail: 1 }); }); + 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 () => { fireEvent.click(anchor(region), { detail: next === 'keyboard' ? 0 : 1 }); }); + 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 () => { From dc71947bb4bc8bf92435540cdcaa3e74cc2e7d38 Mon Sep 17 00:00:00 2001 From: nkAnF Date: Sun, 4 Oct 2026 13:40:48 +0800 Subject: [PATCH 3/3] fix: restore enabled controls without low-contrast fades Keep hover color transitions while restoring enabled opacity immediately. Retain full accessibility checks and allow normal runner variance for the complete single-worker WebKit gate. Co-authored-by: Codex --- .github/workflows/quality.yml | 4 +++- src/app/App.tsx | 6 ++++-- src/tests/e2e/reading-completion.test.ts | 6 ++++++ src/tests/ui/App.test.tsx | 9 +++++++++ 4 files changed, 22 insertions(+), 3 deletions(-) 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/src/app/App.tsx b/src/app/App.tsx index 0556fff..f3e8620 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -26,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(); 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/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;