vomebook commited on
Commit ·
67cbd61
1
Parent(s): 63e3e38
Fix Reader speech, progress undo and search keyboard actions
Browse filesFiles changed (9)
- static/reader/core/reader-bindings.mjs+5-3
- static/reader/ui/reader-speech.mjs+15-9
- static/search/history/application/controller.js+1-1
- static/search/results/application/interactions.js+13-4
- tests/reader/core/test_reader_bindings_boundary.mjs+46
- tests/reader/core/test_reader_regression.js+61
- tests/search/ui/history_quotation_contracts.mjs+16-1
- tests/search/ui/result_interactions_contracts.mjs+15
- typings/reader-speech-strict.d.ts+1-2
830 unmodified lines83183283383483583683783883984084116 unmodified lines858859860861862863864830 unmodified lines}function bindProgressActions() {const startSeeking = () => {if (readerContext.progressSeeking) return;readerContext.beginReaderNavigation();readerContext.progressSeeking = true;readerContext.previousProgressState = readerContext.captureProgressState();};const finishSeeking = () => {if (!readerContext.progressSeeking) return;16 unmodified linesreaderContext.progressRange.addEventListener("input", () => {readerContext.progressPercent.textContent = `${Number(readerContext.progressRange.value).toFixed(1)}%`;readerContext.progressRange.setAttribute("aria-valuetext", readerContext.progressPercent.textContent);readerContext.seekProgress(readerContext.progressRange.value, true);});for (const type of ["pointerup", "pointercancel"])readerContext.progressRange.addEventListener(type, finishSeeking);830 unmodified lines83183283383483583683783883984084116 unmodified lines858859860861862863864865866830 unmodified lines}function bindProgressActions() {let seekChanged = false;const startSeeking = () => {if (readerContext.progressSeeking) return;readerContext.progressSeeking = true;seekChanged = false;};const finishSeeking = () => {if (!readerContext.progressSeeking) return;16 unmodified linesreaderContext.progressRange.addEventListener("input", () => {readerContext.progressPercent.textContent = `${Number(readerContext.progressRange.value).toFixed(1)}%`;readerContext.progressRange.setAttribute("aria-valuetext", readerContext.progressPercent.textContent);// A key or pointer press may leave the value unchanged. Snapshot only on input.readerContext.seekProgress(readerContext.progressRange.value, readerContext.progressSeeking && seekChanged);seekChanged = true;});for (const type of ["pointerup", "pointercancel"])readerContext.progressRange.addEventListener(type, finishSeeking);
85 unmodified lines8687888990919233 unmodified lines126127128129130131132133134135136137138234 unmodified lines37337437537637737837938038138238338485 unmodified linesfunction foliateSections() {return (readerContext.epubBook?.sections || []).filter((section) => section.linear !== "no");}function chapterList() { return readerContext.chapterSearchConfiguration?.chapters || []; }function pageCount() { return Number(readerContext.documentState?.pageCount) || 0; }function hasText() {33 unmodified lines};}if (current === "epub-chapters") {const chapters = chapterList();/** @param {number} index */const root = (index) => readerContext.content.querySelector(`.reader-epub-chapter[data-chapter="${chapters[index]?.index}"]`);return {units: chapters.length, first: 0, root,load: async (index) => rootText(root(index) || await readerContext.chapterManifestLoader?.(chapters[index].index)),locate: (index) => readerContext.chapterManifestLoader?.(chapters[index].index)};}if (current === "pdf" || current === "pdf-pages") {234 unmodified lines.find((node) => node.getBoundingClientRect().bottom > box.top + 8);unit = article ? Number(/** @type {HTMLElement} */ (article).dataset.section) : 0;} else if (current === "epub-chapters") {const chapters = chapterList();const article = [...readerContext.content.querySelectorAll(".reader-epub-chapter[data-chapter]")].find((node) => node.getBoundingClientRect().bottom > box.top + 8);unit = article ? Math.max(0, chapters.findIndex((chapter) => String(chapter.index) === /** @type {HTMLElement} */ (article).dataset.chapter)) : 0;} else if (info.page) {unit = Math.max(1, Number(readerContext.pageAtMarker?.()) || Number(readerContext.documentState?.page) || 1);}const root = info.root(unit);if (!root) return { unit, offset: 0 };85 unmodified lines8687888990919233 unmodified lines126127128129130131132133134135136137138139140234 unmodified lines37537637737837938038138238338438538638738838939085 unmodified linesfunction foliateSections() {return (readerContext.epubBook?.sections || []).filter((section) => section.linear !== "no");}function chapterCount() { return readerContext.chapterManifestLoader?.count || 0; }function pageCount() { return Number(readerContext.documentState?.pageCount) || 0; }function hasText() {33 unmodified lines};}if (current === "epub-chapters") {// Valid chapter manifests have consecutive 1-based indices. Reading// their text doesn't require the optional full-text search index.const loader = readerContext.chapterManifestLoader;/** @param {number} index */const root = (index) => readerContext.content.querySelector(`.reader-epub-chapter[data-chapter="${index + 1}"]`);return {units: chapterCount(), first: 0, root,load: async (index) => rootText(root(index) || await loader?.(index + 1)),locate: (index) => loader?.(index + 1)};}if (current === "pdf" || current === "pdf-pages") {234 unmodified lines.find((node) => node.getBoundingClientRect().bottom > box.top + 8);unit = article ? Number(/** @type {HTMLElement} */ (article).dataset.section) : 0;} else if (current === "epub-chapters") {const article = [...readerContext.content.querySelectorAll(".reader-epub-chapter[data-chapter]")].find((node) => node.getBoundingClientRect().bottom > box.top + 8);const chapter = Number(/** @type {HTMLElement | undefined} */ (article)?.dataset.chapter);unit = Number.isInteger(chapter) && chapter >= 1 && chapter <= info.units ? chapter - 1 : 0;} else if (info.page) {// The marker returns a page element; the saved page can lag behind it.const marker = Number(readerContext.pageAtMarker?.()?.dataset.page);const page = Number.isInteger(marker) && marker >= info.first && marker < info.units? marker : Number(readerContext.documentState?.page) || info.first;unit = Math.max(info.first, Math.min(info.units - 1, page));}const root = info.root(unit);if (!root) return { unit, offset: 0 };
77 unmodified lines7879808182838477 unmodified linesconst next = event.key === 'ArrowDown' ? index + 1 : index - 1;event.preventDefault(); event.stopPropagation();if (next < 0) searchInput.focus({ preventScroll: true });else buttons[Math.min(next, buttons.length - 1)]?.focus({ preventScroll: true });}});/** @param {Event} event */77 unmodified lines7879808182838477 unmodified linesconst next = event.key === 'ArrowDown' ? index + 1 : index - 1;event.preventDefault(); event.stopPropagation();if (next < 0) searchInput.focus({ preventScroll: true });else buttons[Math.min(next, buttons.length - 1)]?.focus();}});/** @param {Event} event */
3 unmodified lines45678918 unmodified lines28293031323334353631 unmodified lines686970717273743 unmodified linesfunction create(deps) {const { elements, selection } = deps;function installSelection() {if (elements.multiSelectToggle) elements.multiSelectToggle.addEventListener("change", deps.updateSelectionUI);elements.resultsList.addEventListener("click", function(e) {18 unmodified linesif (elements.multiCopyLinks) elements.multiCopyLinks.addEventListener("click", function() {const links = deps.getSelectedFiles().map(item => deps.getCopyableLink(item.link));if (links.length === 0) { deps.showToast("未选中任何文件"); return; }navigator.clipboard.writeText(links.join("\n")).then(function() {deps.showToast("已复制 " + links.length + " 条链接");}).catch(function() { deps.showToast("复制失败"); });});if (elements.multiBatchDownload) elements.multiBatchDownload.addEventListener("click", function() {deps.startDownloadBatch(deps.getSelectedFiles());31 unmodified linese.preventDefault();const action = actionBtn.dataset.action;if (action === "copy") {try { await navigator.clipboard.writeText(/** @type {string} */ (actionBtn.dataset.link)); deps.showToast("链接已复制"); } catch { deps.showToast("复制失败"); }return;}if (action === "download") {3 unmodified lines456789101112131415161718192018 unmodified lines3940414243444531 unmodified lines777879808182833 unmodified linesfunction create(deps) {const { elements, selection } = deps;/** @param {string} text @param {string} success */async function copyLinks(text, success) {try {await navigator.clipboard.writeText(text);} catch {deps.showToast("复制失败");return;}deps.showToast(success);}function installSelection() {if (elements.multiSelectToggle) elements.multiSelectToggle.addEventListener("change", deps.updateSelectionUI);elements.resultsList.addEventListener("click", function(e) {18 unmodified linesif (elements.multiCopyLinks) elements.multiCopyLinks.addEventListener("click", function() {const links = deps.getSelectedFiles().map(item => deps.getCopyableLink(item.link));if (links.length === 0) { deps.showToast("未选中任何文件"); return; }return copyLinks(links.join("\n"), "已复制 " + links.length + " 条链接");});if (elements.multiBatchDownload) elements.multiBatchDownload.addEventListener("click", function() {deps.startDownloadBatch(deps.getSelectedFiles());31 unmodified linese.preventDefault();const action = actionBtn.dataset.action;if (action === "copy") {await copyLinks(/** @type {string} */ (actionBtn.dataset.link), "链接已复制");return;}if (action === "download") {
12345662 unmodified lines697071import { test } from 'node:test';import assert from 'node:assert/strict';import { createReaderBindings } from '../../../static/reader/core/reader-bindings.mjs';function storage(values = {}) {const data = new Map(Object.entries(values));62 unmodified linescallback();assert.deepEqual(coordinates, [1, 2]);});123456762 unmodified lines707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import { test } from 'node:test';import assert from 'node:assert/strict';import { createReaderBindings } from '../../../static/reader/core/reader-bindings.mjs';import { createReaderProgress } from '../../../static/reader/ui/reader-progress.mjs';function storage(values = {}) {const data = new Map(Object.entries(values));62 unmodified linescallback();assert.deepEqual(coordinates, [1, 2]);});test('pressing End on the progress slider at 100% preserves the previous seek for Undo', async (t) => {if (!globalThis.document) {globalThis.document = {};t.after(() => { delete globalThis.document; });}const range = Object.assign(new EventTarget(), { value: '0', setAttribute() {} });let generation = 0;const context = {capability: { mode: 'markdown' }, viewport: { scrollTop: 0, scrollHeight: 1000, clientHeight: 100 },progressRange: range, progressPercent: {}, progressUndo: new EventTarget(),chapterPrev: new EventTarget(), chapterNext: new EventTarget(),progressSeeking: false, previousProgressState: null, epubSeekPromise: Promise.resolve(),beginReaderNavigation() { return ++generation; },readerRuntime: { currentGeneration: () => generation },isReaderGenerationCurrent: (_, value) => value === generation,scheduleSave() {}, updateProgressTools() {}};const { seekProgress, captureProgressState, restoreProgressState, flushEpubSeek } = createReaderProgress(context);Object.assign(context, { seekProgress, captureProgressState, restoreProgressState, flushEpubSeek });createReaderBindings(context).bindProgressActions();const key = type => range.dispatchEvent(Object.assign(new Event(type), { key: 'End' }));const drag = (...values) => {range.dispatchEvent(new Event('pointerdown'));for (const value of values) {range.value = value;range.dispatchEvent(new Event('input'));}range.dispatchEvent(new Event('pointerup'));};drag('20');assert.deepEqual(context.previousProgressState, { scrollTop: 0 });drag('90', '100');assert.equal(context.viewport.scrollTop, 900);assert.deepEqual(context.previousProgressState, { scrollTop: 180 }, 'keep one undo point across drag events');// At the upper limit the browser emits key events, but no input event.const before = generation;key('keydown');key('keyup');context.progressUndo.dispatchEvent(new Event('click'));assert.equal(context.viewport.scrollTop, 180);assert.equal(generation, before + 1, 'only Undo should start a navigation');await context.epubSeekPromise;});
462 unmodified lines463464465462 unmodified linesif (expected === bookmark.scrollTop) assert.strictEqual(globalThis.location.searchParams.has('bookmark'), false)}})462 unmodified lines463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526462 unmodified linesif (expected === bookmark.scrollTop) assert.strictEqual(globalThis.location.searchParams.has('bookmark'), false)}})require('node:test')('Reader speech uses the visible PDF page and does not require a chapter search index', async (t) => {const { createReaderSpeech } = await import('../../../static/reader/ui/reader-speech.mjs')const keys = ['window', 'document', 'NodeFilter', 'CCRDSpeech', 'sessionStorage', 'localStorage']const previous = keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])t.after(() => {for (const [key, descriptor] of previous) {if (descriptor) Object.defineProperty(globalThis, key, descriptor)else delete globalThis[key]}})const published = []Object.assign(globalThis, {window: Object.assign(new EventTarget(), { name: '' }),document: Object.assign(new EventTarget(), { querySelector: () => null }),NodeFilter: { SHOW_TEXT: 4 },CCRDSpeech: { previewClosed() {}, previewLoaded: value => published.push(value.adapter) }})for (const key of ['sessionStorage', 'localStorage'])Object.defineProperty(globalThis, key, { configurable: true, value: { removeItem() {} } })const rect = { top: 0, bottom: 20, height: 20 }const textElement = (data, dataset = {}) => ({ dataset, getBoundingClientRect: () => rect, ownerDocument: {createTreeWalker() {let read = falsereturn { nextNode() { if (read) return null; read = true; return { data, length: data.length } } }},createRange: () => ({ setStart() {}, setEnd() {}, getClientRects: () => [rect], getBoundingClientRect: () => rect })} })const pdfText = textElement('Visible PDF text.')const pdfPage = { dataset: { page: '8', textReady: '1' }, querySelector: () => pdfText }const chapter = textElement('Second chapter text.', { chapter: '2' })const viewport = Object.assign(new EventTarget(), { getBoundingClientRect: () => ({ top: 0, bottom: 800 }) })let phaseconst context = {capability: { mode: 'pdf' }, sourceUrl: 'fixture', viewport,content: { querySelector: selector => selector.includes('data-page="8"') ? pdfPage : null },documentState: { page: 26, pageCount: 40 }, pageAtMarker: () => pdfPage,readerRuntime: { events: { on: (_, callback) => { phase = callback } } }}createReaderSpeech(context).installReaderSpeech()phase({ phase: 'ready' })await new Promise(setImmediate)assert.strictEqual(published.length, 1, 'a stale saved page must not hide speech on the visible page')const pdf = published[0]assert.strictEqual(pdf.base, 7)assert.strictEqual(pdf.partAt(await pdf.locateTop()).unit, 8)const loads = []Object.assign(context, { capability: { mode: 'epub-chapters' }, chapterSearchConfiguration: null,chapterManifestLoader: Object.assign(async index => { loads.push(index); return textElement('First chapter text.') }, { count: 2 }),content: { querySelector: selector => selector.includes('data-chapter="2"') ? chapter : null,querySelectorAll: () => [chapter] } })phase({ phase: 'ready' })assert.strictEqual(published.length, 2, 'a chapter manifest alone is sufficient for speech')const epub = published[1]const part = epub.partAt(await epub.locateTop())assert.strictEqual(part.unit, 1)assert.strictEqual(part.raw, 'Second chapter text.')assert.deepStrictEqual(loads, [1], 'translate player units to one-based Reader chapter indices')phase({ phase: 'disposed' })})
42 unmodified lines4344454647484985 unmodified lines13513613713813914042 unmodified linesb.dataset = kind === 'del' ? {del: row.dataset.query} : {};b.matches = selector => selector === '.history-' + kind;b.closest = selector => selector === '.history-item' ? row : selector.includes('.history-' + kind) ? b : null;b.focus = () => { c.document.activeElement = b; }; return b;}dropdown.contains = el => !!el && rows.includes(el.row);dropdown.querySelectorAll = selector => selector === '.history-item' ? rows : rows.map(row => row.text);85 unmodified linesassert.deepEqual(plain(c.getHistory()), []); assert.equal(f.dropdown.style.display, 'none'); assert.equal(c.document.activeElement, f.input);});test('history preserves listener order, live IME guards, hover/blur delay and long-press cancellation', async () => {const f = historyFixture(), {c} = f;assert.deepEqual(f.listeners.slice(0, 6).map(item => item.slice(0, 2)), [['input', 'focus'], ['box', 'focusout'], ['dropdown', 'mouseenter'], ['dropdown', 'mouseleave'], ['document', 'pointerdown'], ['box', 'keydown']]);42 unmodified lines4344454647484985 unmodified lines13513613713813914014114214314414514614714814915015115215315415542 unmodified linesb.dataset = kind === 'del' ? {del: row.dataset.query} : {};b.matches = selector => selector === '.history-' + kind;b.closest = selector => selector === '.history-item' ? row : selector.includes('.history-' + kind) ? b : null;b.focus = options => { c.document.activeElement = b; b.focusOptions = options; }; return b;}dropdown.contains = el => !!el && rows.includes(el.row);dropdown.querySelectorAll = selector => selector === '.history-item' ? rows : rows.map(row => row.text);85 unmodified linesassert.deepEqual(plain(c.getHistory()), []); assert.equal(f.dropdown.style.display, 'none'); assert.equal(c.document.activeElement, f.input);});test('history arrow navigation lets the browser scroll the focused entry into view', () => {const f = historyFixture(), {c} = f;c.saveHistory(Array.from({length: 20}, (_, i) => 'query ' + i));f.input.focus();for (let i = 0; i < f.rows.length; i++) {const event = f.key('ArrowDown', c.document.activeElement);assert.equal(event.prevented, true);assert.equal(c.document.activeElement, f.rows[i].text);assert.notEqual(f.rows[i].text.focusOptions?.preventScroll, true, 'focus must scroll entries in the overflow menu into view');}f.key('ArrowUp', c.document.activeElement);assert.equal(c.document.activeElement, f.rows[18].text);assert.notEqual(f.rows[18].text.focusOptions?.preventScroll, true);});test('history preserves listener order, live IME guards, hover/blur delay and long-press cancellation', async () => {const f = historyFixture(), {c} = f;assert.deepEqual(f.listeners.slice(0, 6).map(item => item.slice(0, 2)), [['input', 'focus'], ['box', 'focusout'], ['dropdown', 'mouseenter'], ['dropdown', 'mouseleave'], ['document', 'pointerdown'], ['box', 'keydown']]);
115 unmodified lines116117118119120121115 unmodified linesassert.equal(f.toasts.at(-1), '复制失败');});test('breadcrumb keyboard respects IME and native controls; route merges query and sidebar dataset differs by site', async () => {const f = fixture(), {c, DOM, click} = f;let activated = 0;115 unmodified lines116117118119120121122123124125126127128129130131132133134135136115 unmodified linesassert.equal(f.toasts.at(-1), '复制失败');});test('single and bulk copy report an unavailable clipboard or synchronous failure', async () => {const f = fixture(), {c, DOM, click} = f;const button = node({action: 'copy', link: 'copy-me'});button.closest = selector => selector === '[data-action]' ? button : null;c.selectedIndices = {0: true};for (const clipboard of [undefined, {writeText() { throw new Error('disabled'); }}]) {c.navigator.clipboard = clipboard;f.toasts.length = 0;await click(DOM.resultsList, button);await click(DOM.multiCopyLinks, DOM.multiCopyLinks);assert.deepEqual(f.toasts, ['复制失败', '复制失败']);assert.deepEqual(f.copied, []);}});test('breadcrumb keyboard respects IME and native controls; route merges query and sidebar dataset differs by site', async () => {const f = fixture(), {c, DOM, click} = f;let activated = 0;
7 unmodified lines891011121314157 unmodified linesepubBook: { sections: FoliateSection[] } | null;foliateSectionRoot(article: Element): Element | ShadowRoot;foliateSectionLoader: ((index: number) => Promise<unknown>) | null;chapterSearchConfiguration: { chapters: { index: number }[] } | null;chapterManifestLoader: ((index: number) => Promise<HTMLElement | null>) | null;documentState: { pageCount: number; page: number };ocrManifestUrl: string; pdfOcrManifest: object | null;pdfDocument: { getPage(page: number): Promise<PdfPage> } | null;7 unmodified lines8910111213147 unmodified linesepubBook: { sections: FoliateSection[] } | null;foliateSectionRoot(article: Element): Element | ShadowRoot;foliateSectionLoader: ((index: number) => Promise<unknown>) | null;chapterManifestLoader: (((index: number) => Promise<HTMLElement | null>) & { count: number }) | null;documentState: { pageCount: number; page: number };ocrManifestUrl: string; pdfOcrManifest: object | null;pdfDocument: { getPage(page: number): Promise<PdfPage> } | null;
static/reader/core/reader-bindings.mjs+5-3
static/reader/ui/reader-speech.mjs+15-9
static/search/history/application/controller.js+1-1
static/search/results/application/interactions.js+13-4
tests/reader/core/test_reader_bindings_boundary.mjs+46
tests/reader/core/test_reader_regression.js+61
tests/search/ui/history_quotation_contracts.mjs+16-1
tests/search/ui/result_interactions_contracts.mjs+15
typings/reader-speech-strict.d.ts+1-2