vomebook commited on
Commit ·
86eb73d
1
Parent(s): 5e71678
Type-check all first-party browser scripts
Browse files- jsconfig.check.json +10 -1
- static/app.js +30 -28
- static/reader/core/reader-bindings.mjs +22 -23
- static/reader/formats/reader-chapter-format.mjs +9 -7
- static/reader/formats/reader-foliate-format.mjs +6 -6
- static/reader/formats/reader-format-controller.mjs +5 -5
- static/reader/pdf/reader-pdf-page-window.mjs +12 -10
- tests/test_static_checks.py +72 -0
- tests/test_static_contract.py +2 -2
- typings/foliate/view.d.ts +3 -0
- typings/reader-globals.d.ts +102 -1
jsconfig.check.json
CHANGED
|
@@ -15,6 +15,12 @@
|
|
| 15 |
],
|
| 16 |
"/search/static/*": [
|
| 17 |
"./static/*"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
]
|
| 19 |
}
|
| 20 |
},
|
|
@@ -74,6 +80,9 @@
|
|
| 74 |
"static/search/download-controller.js",
|
| 75 |
"static/search/reader-navigation.js",
|
| 76 |
"static/search/search-session.js",
|
| 77 |
-
"static/tts-client.js"
|
|
|
|
|
|
|
|
|
|
| 78 |
]
|
| 79 |
}
|
|
|
|
| 15 |
],
|
| 16 |
"/search/static/*": [
|
| 17 |
"./static/*"
|
| 18 |
+
],
|
| 19 |
+
"/static/foliate-reader/view.js": [
|
| 20 |
+
"./typings/foliate/view.d.ts"
|
| 21 |
+
],
|
| 22 |
+
"/search/static/foliate-reader/view.js?reader-v1": [
|
| 23 |
+
"./typings/foliate/view.d.ts"
|
| 24 |
]
|
| 25 |
}
|
| 26 |
},
|
|
|
|
| 80 |
"static/search/download-controller.js",
|
| 81 |
"static/search/reader-navigation.js",
|
| 82 |
"static/search/search-session.js",
|
| 83 |
+
"static/tts-client.js",
|
| 84 |
+
"static/app.js",
|
| 85 |
+
"static/reader.js",
|
| 86 |
+
"static/reader/reader-components.mjs"
|
| 87 |
]
|
| 88 |
}
|
static/app.js
CHANGED
|
@@ -786,7 +786,7 @@ function validSearchPosition(value) {
|
|
| 786 |
}
|
| 787 |
|
| 788 |
async function initSearchPositions() {
|
| 789 |
-
await new Promise(resolve => {
|
| 790 |
const timer = setTimeout(resolve, 1500);
|
| 791 |
try {
|
| 792 |
const request = indexedDB.open("voice-search-positions", 4);
|
|
@@ -816,7 +816,7 @@ async function initSearchPositions() {
|
|
| 816 |
transaction.oncomplete = transaction.onabort = () => { clearTimeout(timer); resolve(); };
|
| 817 |
};
|
| 818 |
} catch (_) { clearTimeout(timer); resolve(); }
|
| 819 |
-
});
|
| 820 |
}
|
| 821 |
|
| 822 |
function rememberDisplayedSearchView() {
|
|
@@ -1086,7 +1086,7 @@ function isRecoverableSearchError(error) {
|
|
| 1086 |
}
|
| 1087 |
|
| 1088 |
function waitForSearchRecovery(signal, delay, local) {
|
| 1089 |
-
return new Promise((resolve, reject) => {
|
| 1090 |
let elapsed = false;
|
| 1091 |
const cleanup = () => {
|
| 1092 |
clearTimeout(timer);
|
|
@@ -1105,7 +1105,7 @@ function waitForSearchRecovery(signal, delay, local) {
|
|
| 1105 |
window.addEventListener("online", ready);
|
| 1106 |
window.addEventListener("pageshow", ready);
|
| 1107 |
if (signal.aborted) abort();
|
| 1108 |
-
});
|
| 1109 |
}
|
| 1110 |
|
| 1111 |
async function fetchPositionPageWithRecovery(query, page, signal, anchorId, demanded = () => true) {
|
|
@@ -2003,7 +2003,7 @@ function renderDropdown() {
|
|
| 2003 |
DOM.historyDropdown.innerHTML = html;
|
| 2004 |
DOM.historyDropdown.style.display = "";
|
| 2005 |
if (row) {
|
| 2006 |
-
var index = list.indexOf(row.dataset.query);
|
| 2007 |
var selector = index >= 0 && active.matches('.history-del') ? '.history-del' : '.history-text';
|
| 2008 |
DOM.historyDropdown.querySelectorAll('.history-item')[index >= 0 ? index : Math.min(oldIndex, list.length - 1)]
|
| 2009 |
.querySelector(selector).focus({ preventScroll: true });
|
|
@@ -2341,7 +2341,7 @@ function renderDownloadBatch() {
|
|
| 2341 |
panel.setAttribute("aria-label", "批量下载");
|
| 2342 |
panel.innerHTML = '<span role="status" aria-live="polite"></span><button type="button" data-queue="cancel">取消待下载</button><button type="button" data-queue="retry">重试失败项</button><button type="button" data-queue="close">关闭</button>';
|
| 2343 |
panel.addEventListener("click", event => {
|
| 2344 |
-
const action = event.target.dataset.queue;
|
| 2345 |
if (action === "cancel") {
|
| 2346 |
downloadBatch.cancelled = true;
|
| 2347 |
downloadBatch.abortController?.abort();
|
|
@@ -2353,9 +2353,9 @@ function renderDownloadBatch() {
|
|
| 2353 |
document.body.appendChild(panel);
|
| 2354 |
}
|
| 2355 |
panel.querySelector('[role="status"]').textContent = `${batch.cancelled ? "已取消待下载 · " : ""}已发起 ${batch.started}/${batch.items.length} · 失败 ${batch.failed.length}。请在浏览器下载列表查看文件进度。`;
|
| 2356 |
-
panel.querySelector('[data-queue="cancel"]').hidden = batch.done || batch.cancelled;
|
| 2357 |
-
panel.querySelector('[data-queue="retry"]').hidden = !batch.done || !batch.failed.length;
|
| 2358 |
-
panel.querySelector('[data-queue="close"]').hidden = !batch.done;
|
| 2359 |
}
|
| 2360 |
|
| 2361 |
function getSelectedFiles() {
|
|
@@ -3345,7 +3345,7 @@ function renderRepoListItems(repos) {
|
|
| 3345 |
}
|
| 3346 |
DOM.sidebarContent.innerHTML = html;
|
| 3347 |
if (focused) (Array.from(DOM.sidebarContent.querySelectorAll('.repo-list-item'))
|
| 3348 |
-
.find(node => node.dataset.repo === focused.dataset.repo) || DOM.leftSidebar).focus({ preventScroll: true });
|
| 3349 |
}
|
| 3350 |
|
| 3351 |
async function renderRepoList(routeId) {
|
|
@@ -3469,9 +3469,10 @@ async function renderBrowser(path, routeId) {
|
|
| 3469 |
const file = (displayedData.files || [])[index];
|
| 3470 |
if (!file) return;
|
| 3471 |
const readUrl = getBrowserFileReadUrl(file, currentRepo, path);
|
| 3472 |
-
|
| 3473 |
-
|
| 3474 |
-
|
|
|
|
| 3475 |
});
|
| 3476 |
});
|
| 3477 |
if (cached) return;
|
|
@@ -3529,7 +3530,7 @@ function createSidebarBreadcrumb(path) {
|
|
| 3529 |
}).join("");
|
| 3530 |
breadcrumb.querySelectorAll(".crumb-item").forEach(item => {
|
| 3531 |
item.addEventListener("click", () => {
|
| 3532 |
-
if (!item.classList.contains("current")) ROUTER.navigate("repo", STATE.repo, item.dataset.path);
|
| 3533 |
});
|
| 3534 |
});
|
| 3535 |
return breadcrumb;
|
|
@@ -3799,7 +3800,7 @@ function layoutResultScrollSegment(topH, endH, totalH, logicalTop) {
|
|
| 3799 |
|
| 3800 |
function reconcileVirtualRows(items, start, end, topH, bottomH) {
|
| 3801 |
const focused = document.activeElement;
|
| 3802 |
-
const focusedRow = DOM.resultsList.contains(focused) ? focused.closest('.result-item') : null;
|
| 3803 |
const focusedRecord = focusedRow && resultRowRecords.get(focusedRow);
|
| 3804 |
// Validate once before reusing rows, not once for every new row.
|
| 3805 |
ensureResultTemplateCache();
|
|
@@ -3843,7 +3844,7 @@ function reconcileVirtualRows(items, start, end, topH, bottomH) {
|
|
| 3843 |
const sameRecord = replacement && focusedRecord && resultRowRecords.get(replacement) === focusedRecord;
|
| 3844 |
const control = sameRecord && (focused === focusedRow ? replacement :
|
| 3845 |
Array.from(replacement.querySelectorAll('button,a,input,[role="button"]')).find(node =>
|
| 3846 |
-
node.className === focused.className && node.dataset.action === focused.dataset.action &&
|
| 3847 |
node.getAttribute('aria-label') === focused.getAttribute('aria-label')));
|
| 3848 |
if (!control) keyboardResultIndex = findVirtualIndex(logicalTop) - 1;
|
| 3849 |
(control || DOM.resultsContainer).focus({ preventScroll: true });
|
|
@@ -3854,8 +3855,8 @@ function reconcileVirtualRows(items, start, end, topH, bottomH) {
|
|
| 3854 |
}
|
| 3855 |
}
|
| 3856 |
|
| 3857 |
-
function scheduleVirtualRender() {
|
| 3858 |
-
const afterScroll =
|
| 3859 |
if (afterScroll && !VSCROLL.renderAfterScroll) {
|
| 3860 |
VSCROLL.renderAfterScroll = true;
|
| 3861 |
if (!VSCROLL.isDraggingThumb) maybeLoadNextPage();
|
|
@@ -4299,15 +4300,15 @@ function scheduleFilterSearch(clearResults = false) {
|
|
| 4299 |
}
|
| 4300 |
|
| 4301 |
function updateCurrentResultPosition() {
|
| 4302 |
-
const label = document.getElementById("current-result-position");
|
| 4303 |
if (!label) return;
|
| 4304 |
const editing = document.activeElement === label;
|
| 4305 |
label.hidden = !editing;
|
| 4306 |
if (STATE.results.length || STATE.total) {
|
| 4307 |
const index = findVirtualIndex(getResultScrollTop());
|
| 4308 |
-
if (!editing && label.value !== String(index + 1)) label.value = index + 1;
|
| 4309 |
const display = document.getElementById('result-position-display');
|
| 4310 |
-
if (display && display.textContent !== String(index + 1)) display.textContent = index + 1;
|
| 4311 |
}
|
| 4312 |
updateSearchPositionControls();
|
| 4313 |
}
|
|
@@ -5155,7 +5156,7 @@ function renderFilterTreeNodes(container, nodes, depth) {
|
|
| 5155 |
|
| 5156 |
function appendFilterTreeNode(container, node, depth, subtreeSet, selfSet, lookup) {
|
| 5157 |
const has = node.children && node.children.length > 0;
|
| 5158 |
-
const row = document.createElement("div");
|
| 5159 |
row.className = "filter-folder-item";
|
| 5160 |
row.style.setProperty("--fdepth", depth);
|
| 5161 |
row.dataset.path = node.path;
|
|
@@ -5168,7 +5169,7 @@ function appendFilterTreeNode(container, node, depth, subtreeSet, selfSet, looku
|
|
| 5168 |
toggle?.setAttribute('aria-label', (collapsed ? '展开子文件夹:' : '收起子文件夹:') + node.path);
|
| 5169 |
applyFolderSelectionToNode(node, row, subtreeSet, selfSet, lookup);
|
| 5170 |
if (has) {
|
| 5171 |
-
const childDiv = document.createElement("div");
|
| 5172 |
childDiv.className = "tree-children";
|
| 5173 |
childDiv.id = 'filter-folder-children-' + ++folderTreeControlId;
|
| 5174 |
childDiv.inert = collapsed;
|
|
@@ -5318,8 +5319,9 @@ async function fetchRandomReaderRecord(url, requestId, returnUrl) {
|
|
| 5318 |
const response = await fetch(url, { signal: controller.signal, cache: "no-store" });
|
| 5319 |
if (!response.ok) {
|
| 5320 |
await response.body?.cancel();
|
| 5321 |
-
const error = new Error(`HTTP ${response.status}`)
|
| 5322 |
-
|
|
|
|
| 5323 |
throw error;
|
| 5324 |
}
|
| 5325 |
return await response.json();
|
|
@@ -5376,7 +5378,7 @@ function isResultsAtBottom() {
|
|
| 5376 |
|
| 5377 |
function updatePagingStatus() {
|
| 5378 |
if (!DOM.loadInfo) return;
|
| 5379 |
-
let button = document.getElementById("paging-status");
|
| 5380 |
if (!button) {
|
| 5381 |
button = document.createElement("button");
|
| 5382 |
button.id = "paging-status";
|
|
@@ -5730,7 +5732,7 @@ function toggleRightSidebar(event) {
|
|
| 5730 |
}
|
| 5731 |
|
| 5732 |
function updateSidebarVisibility() {
|
| 5733 |
-
const main = document.querySelector('#main-content');
|
| 5734 |
const covered = STATE.isMobile && (STATE.leftSidebarOpen || STATE.rightSidebarOpen);
|
| 5735 |
const focusCovered = covered && main.contains(document.activeElement);
|
| 5736 |
main.inert = covered;
|
|
@@ -5788,7 +5790,7 @@ function setupKeyboard() {
|
|
| 5788 |
else closeLeftSidebar();
|
| 5789 |
return;
|
| 5790 |
}
|
| 5791 |
-
const isInput = target.isContentEditable || !!target.closest("input, textarea, select");
|
| 5792 |
if (isInput && !(target === DOM.searchInput && e.key === "Escape")) return;
|
| 5793 |
if (["Enter", "ArrowDown", "ArrowUp"].includes(e.key) && target.closest("button, a, [role='button']")) return;
|
| 5794 |
if (e.key === "/" && !isInput) { e.preventDefault(); DOM.searchInput.focus(); DOM.searchInput.select(); return; }
|
|
|
|
| 786 |
}
|
| 787 |
|
| 788 |
async function initSearchPositions() {
|
| 789 |
+
await /** @type {Promise<void>} */ (new Promise(resolve => {
|
| 790 |
const timer = setTimeout(resolve, 1500);
|
| 791 |
try {
|
| 792 |
const request = indexedDB.open("voice-search-positions", 4);
|
|
|
|
| 816 |
transaction.oncomplete = transaction.onabort = () => { clearTimeout(timer); resolve(); };
|
| 817 |
};
|
| 818 |
} catch (_) { clearTimeout(timer); resolve(); }
|
| 819 |
+
}));
|
| 820 |
}
|
| 821 |
|
| 822 |
function rememberDisplayedSearchView() {
|
|
|
|
| 1086 |
}
|
| 1087 |
|
| 1088 |
function waitForSearchRecovery(signal, delay, local) {
|
| 1089 |
+
return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
|
| 1090 |
let elapsed = false;
|
| 1091 |
const cleanup = () => {
|
| 1092 |
clearTimeout(timer);
|
|
|
|
| 1105 |
window.addEventListener("online", ready);
|
| 1106 |
window.addEventListener("pageshow", ready);
|
| 1107 |
if (signal.aborted) abort();
|
| 1108 |
+
}));
|
| 1109 |
}
|
| 1110 |
|
| 1111 |
async function fetchPositionPageWithRecovery(query, page, signal, anchorId, demanded = () => true) {
|
|
|
|
| 2003 |
DOM.historyDropdown.innerHTML = html;
|
| 2004 |
DOM.historyDropdown.style.display = "";
|
| 2005 |
if (row) {
|
| 2006 |
+
var index = list.indexOf(/** @type {HTMLElement} */ (row).dataset.query);
|
| 2007 |
var selector = index >= 0 && active.matches('.history-del') ? '.history-del' : '.history-text';
|
| 2008 |
DOM.historyDropdown.querySelectorAll('.history-item')[index >= 0 ? index : Math.min(oldIndex, list.length - 1)]
|
| 2009 |
.querySelector(selector).focus({ preventScroll: true });
|
|
|
|
| 2341 |
panel.setAttribute("aria-label", "批量下载");
|
| 2342 |
panel.innerHTML = '<span role="status" aria-live="polite"></span><button type="button" data-queue="cancel">取消待下载</button><button type="button" data-queue="retry">重试失败项</button><button type="button" data-queue="close">关闭</button>';
|
| 2343 |
panel.addEventListener("click", event => {
|
| 2344 |
+
const action = /** @type {HTMLElement} */ (event.target).dataset.queue;
|
| 2345 |
if (action === "cancel") {
|
| 2346 |
downloadBatch.cancelled = true;
|
| 2347 |
downloadBatch.abortController?.abort();
|
|
|
|
| 2353 |
document.body.appendChild(panel);
|
| 2354 |
}
|
| 2355 |
panel.querySelector('[role="status"]').textContent = `${batch.cancelled ? "已取消待下载 · " : ""}已发起 ${batch.started}/${batch.items.length} · 失败 ${batch.failed.length}。请在浏览器下载列表查看文件进度。`;
|
| 2356 |
+
/** @type {HTMLElement} */ (panel.querySelector('[data-queue="cancel"]')).hidden = batch.done || batch.cancelled;
|
| 2357 |
+
/** @type {HTMLElement} */ (panel.querySelector('[data-queue="retry"]')).hidden = !batch.done || !batch.failed.length;
|
| 2358 |
+
/** @type {HTMLElement} */ (panel.querySelector('[data-queue="close"]')).hidden = !batch.done;
|
| 2359 |
}
|
| 2360 |
|
| 2361 |
function getSelectedFiles() {
|
|
|
|
| 3345 |
}
|
| 3346 |
DOM.sidebarContent.innerHTML = html;
|
| 3347 |
if (focused) (Array.from(DOM.sidebarContent.querySelectorAll('.repo-list-item'))
|
| 3348 |
+
.find(node => node.dataset.repo === /** @type {HTMLElement} */ (focused).dataset.repo) || DOM.leftSidebar).focus({ preventScroll: true });
|
| 3349 |
}
|
| 3350 |
|
| 3351 |
async function renderRepoList(routeId) {
|
|
|
|
| 3469 |
const file = (displayedData.files || [])[index];
|
| 3470 |
if (!file) return;
|
| 3471 |
const readUrl = getBrowserFileReadUrl(file, currentRepo, path);
|
| 3472 |
+
const fileRow = /** @type {HTMLElement} */ (row);
|
| 3473 |
+
if (readUrl) fileRow.dataset.readUrl = readUrl;
|
| 3474 |
+
else delete fileRow.dataset.readUrl;
|
| 3475 |
+
row.querySelector('.browser-name').setAttribute('aria-label', (readUrl ? '打开阅读器:' : '下载文件:') + fileRow.dataset.filename);
|
| 3476 |
});
|
| 3477 |
});
|
| 3478 |
if (cached) return;
|
|
|
|
| 3530 |
}).join("");
|
| 3531 |
breadcrumb.querySelectorAll(".crumb-item").forEach(item => {
|
| 3532 |
item.addEventListener("click", () => {
|
| 3533 |
+
if (!item.classList.contains("current")) ROUTER.navigate("repo", STATE.repo, /** @type {HTMLElement} */ (item).dataset.path);
|
| 3534 |
});
|
| 3535 |
});
|
| 3536 |
return breadcrumb;
|
|
|
|
| 3800 |
|
| 3801 |
function reconcileVirtualRows(items, start, end, topH, bottomH) {
|
| 3802 |
const focused = document.activeElement;
|
| 3803 |
+
const focusedRow = DOM.resultsList.contains(focused) ? /** @type {HTMLElement} */ (focused.closest('.result-item')) : null;
|
| 3804 |
const focusedRecord = focusedRow && resultRowRecords.get(focusedRow);
|
| 3805 |
// Validate once before reusing rows, not once for every new row.
|
| 3806 |
ensureResultTemplateCache();
|
|
|
|
| 3844 |
const sameRecord = replacement && focusedRecord && resultRowRecords.get(replacement) === focusedRecord;
|
| 3845 |
const control = sameRecord && (focused === focusedRow ? replacement :
|
| 3846 |
Array.from(replacement.querySelectorAll('button,a,input,[role="button"]')).find(node =>
|
| 3847 |
+
node.className === focused.className && node.dataset.action === /** @type {HTMLElement} */ (focused).dataset.action &&
|
| 3848 |
node.getAttribute('aria-label') === focused.getAttribute('aria-label')));
|
| 3849 |
if (!control) keyboardResultIndex = findVirtualIndex(logicalTop) - 1;
|
| 3850 |
(control || DOM.resultsContainer).focus({ preventScroll: true });
|
|
|
|
| 3855 |
}
|
| 3856 |
}
|
| 3857 |
|
| 3858 |
+
function scheduleVirtualRender(scrollIntent = false) {
|
| 3859 |
+
const afterScroll = scrollIntent === true;
|
| 3860 |
if (afterScroll && !VSCROLL.renderAfterScroll) {
|
| 3861 |
VSCROLL.renderAfterScroll = true;
|
| 3862 |
if (!VSCROLL.isDraggingThumb) maybeLoadNextPage();
|
|
|
|
| 4300 |
}
|
| 4301 |
|
| 4302 |
function updateCurrentResultPosition() {
|
| 4303 |
+
const label = /** @type {HTMLInputElement | null} */ (document.getElementById("current-result-position"));
|
| 4304 |
if (!label) return;
|
| 4305 |
const editing = document.activeElement === label;
|
| 4306 |
label.hidden = !editing;
|
| 4307 |
if (STATE.results.length || STATE.total) {
|
| 4308 |
const index = findVirtualIndex(getResultScrollTop());
|
| 4309 |
+
if (!editing && label.value !== String(index + 1)) label.value = String(index + 1);
|
| 4310 |
const display = document.getElementById('result-position-display');
|
| 4311 |
+
if (display && display.textContent !== String(index + 1)) display.textContent = String(index + 1);
|
| 4312 |
}
|
| 4313 |
updateSearchPositionControls();
|
| 4314 |
}
|
|
|
|
| 5156 |
|
| 5157 |
function appendFilterTreeNode(container, node, depth, subtreeSet, selfSet, lookup) {
|
| 5158 |
const has = node.children && node.children.length > 0;
|
| 5159 |
+
const row = /** @type {HTMLDivElement & {_folderNode?: unknown}} */ (document.createElement("div"));
|
| 5160 |
row.className = "filter-folder-item";
|
| 5161 |
row.style.setProperty("--fdepth", depth);
|
| 5162 |
row.dataset.path = node.path;
|
|
|
|
| 5169 |
toggle?.setAttribute('aria-label', (collapsed ? '展开子文件夹:' : '收起子文件夹:') + node.path);
|
| 5170 |
applyFolderSelectionToNode(node, row, subtreeSet, selfSet, lookup);
|
| 5171 |
if (has) {
|
| 5172 |
+
const childDiv = /** @type {HTMLDivElement & {_folderPath?: string, _folderNode?: unknown, _folderDepth?: number, _childrenRendered?: boolean}} */ (document.createElement("div"));
|
| 5173 |
childDiv.className = "tree-children";
|
| 5174 |
childDiv.id = 'filter-folder-children-' + ++folderTreeControlId;
|
| 5175 |
childDiv.inert = collapsed;
|
|
|
|
| 5319 |
const response = await fetch(url, { signal: controller.signal, cache: "no-store" });
|
| 5320 |
if (!response.ok) {
|
| 5321 |
await response.body?.cancel();
|
| 5322 |
+
const error = Object.assign(new Error(`HTTP ${response.status}`), {
|
| 5323 |
+
permanent: response.status < 500 && ![408, 429].includes(response.status)
|
| 5324 |
+
});
|
| 5325 |
throw error;
|
| 5326 |
}
|
| 5327 |
return await response.json();
|
|
|
|
| 5378 |
|
| 5379 |
function updatePagingStatus() {
|
| 5380 |
if (!DOM.loadInfo) return;
|
| 5381 |
+
let button = /** @type {HTMLButtonElement | null} */ (document.getElementById("paging-status"));
|
| 5382 |
if (!button) {
|
| 5383 |
button = document.createElement("button");
|
| 5384 |
button.id = "paging-status";
|
|
|
|
| 5732 |
}
|
| 5733 |
|
| 5734 |
function updateSidebarVisibility() {
|
| 5735 |
+
const main = /** @type {HTMLElement} */ (document.querySelector('#main-content'));
|
| 5736 |
const covered = STATE.isMobile && (STATE.leftSidebarOpen || STATE.rightSidebarOpen);
|
| 5737 |
const focusCovered = covered && main.contains(document.activeElement);
|
| 5738 |
main.inert = covered;
|
|
|
|
| 5790 |
else closeLeftSidebar();
|
| 5791 |
return;
|
| 5792 |
}
|
| 5793 |
+
const isInput = (target instanceof HTMLElement && target.isContentEditable) || !!target.closest("input, textarea, select");
|
| 5794 |
if (isInput && !(target === DOM.searchInput && e.key === "Escape")) return;
|
| 5795 |
if (["Enter", "ArrowDown", "ArrowUp"].includes(e.key) && target.closest("button, a, [role='button']")) return;
|
| 5796 |
if (e.key === "/" && !isInput) { e.preventDefault(); DOM.searchInput.focus(); DOM.searchInput.select(); return; }
|
static/reader/core/reader-bindings.mjs
CHANGED
|
@@ -105,13 +105,13 @@ export function createReaderBindings(readerContext) {
|
|
| 105 |
}
|
| 106 |
if (
|
| 107 |
["history", "history-clear", "history-remove"].includes(change.type) &&
|
| 108 |
-
!document.querySelector("#history-panel").hidden
|
| 109 |
)
|
| 110 |
readerContext.renderHistory();
|
| 111 |
if (
|
| 112 |
["bookmark", "bookmark-remove"].includes(change.type) &&
|
| 113 |
(readerContext.panelState.showingAllBookmarks || !change.url || change.url === readerContext.sourceUrl) &&
|
| 114 |
-
!document.querySelector("#bookmarks-panel").hidden
|
| 115 |
)
|
| 116 |
readerContext.renderBookmarks();
|
| 117 |
})
|
|
@@ -266,7 +266,7 @@ export function createReaderBindings(readerContext) {
|
|
| 266 |
readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
|
| 267 |
readerContext.contentSanitizerObserver = new MutationObserver(() => {
|
| 268 |
const seen = new Set();
|
| 269 |
-
for (const article of document.querySelectorAll(".foliate-continuous > article[data-section]")) {
|
| 270 |
article.querySelectorAll("style,link[rel=stylesheet]").forEach((node) => node.remove());
|
| 271 |
const index = article.dataset.section;
|
| 272 |
if (seen.has(index)) article.remove();
|
|
@@ -332,8 +332,8 @@ export function createReaderBindings(readerContext) {
|
|
| 332 |
readerContext.mediaPanel
|
| 333 |
.querySelector(".media-panel-bookmark")
|
| 334 |
.addEventListener("click", (event) => readerContext.openBookmarkPopover(event.currentTarget));
|
| 335 |
-
document.querySelector(".page-controls").hidden = !readerContext.capability.features.pagination;
|
| 336 |
-
document.querySelector(".zoom-controls").hidden = !readerContext.capability.features.zoom;
|
| 337 |
|
| 338 |
readerContext.status.hidden = true;
|
| 339 |
readerContext.mediaTab.setAttribute("aria-controls", "media-panel");
|
|
@@ -388,15 +388,15 @@ export function createReaderBindings(readerContext) {
|
|
| 388 |
location.assign("/");
|
| 389 |
});
|
| 390 |
// Replay a Back tap made before this handler was bound.
|
| 391 |
-
if (window.__VOICE_READER_EARLY_BACK__?.()) document.querySelector("#back").click();
|
| 392 |
}
|
| 393 |
|
| 394 |
function bindZoomAndPageControls() {
|
| 395 |
readerContext.setZoom(readerContext.documentState.zoom * 100, false);
|
| 396 |
-
for (const [id, delta] of [
|
| 397 |
["#zoom-out", -10],
|
| 398 |
["#zoom-in", 10]
|
| 399 |
-
]) {
|
| 400 |
document.querySelector(id).addEventListener("click", () => {
|
| 401 |
readerContext.setZoom(Number(readerContext.zoomInput.value) + delta);
|
| 402 |
});
|
|
@@ -443,11 +443,11 @@ export function createReaderBindings(readerContext) {
|
|
| 443 |
|
| 444 |
document.addEventListener("click", async (event) => {
|
| 445 |
const path = event.composedPath(),
|
| 446 |
-
link = path.find((node) => node instanceof Element && node.matches?.("a[href]")),
|
| 447 |
-
article = path.find(
|
| 448 |
(node) =>
|
| 449 |
node instanceof Element && node.matches?.(".foliate-continuous article[data-section]")
|
| 450 |
-
);
|
| 451 |
if (!link || !article || !readerContext.epubRendition?.book) return;
|
| 452 |
const raw = link.getAttribute("href") || "";
|
| 453 |
if (raw.startsWith("/api/reader-resource?")) return;
|
|
@@ -473,7 +473,7 @@ export function createReaderBindings(readerContext) {
|
|
| 473 |
readerContext.bookmarkRibbon.addEventListener("click", () => readerContext.openBookmarkPopover(readerContext.bookmarkRibbon));
|
| 474 |
document.querySelector("#bookmark-cancel").addEventListener("click", readerContext.closeBookmarkPopover);
|
| 475 |
document.querySelector("#bookmark-add").addEventListener("click", async (event) => {
|
| 476 |
-
const button = event.currentTarget,
|
| 477 |
editing = readerContext.panelState.editingBookmark;
|
| 478 |
const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();
|
| 479 |
const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,
|
|
@@ -497,7 +497,7 @@ export function createReaderBindings(readerContext) {
|
|
| 497 |
);
|
| 498 |
const invoker = readerContext.bookmarkInvoker;
|
| 499 |
readerContext.closeBookmarkPopover();
|
| 500 |
-
if (!document.querySelector("#bookmarks-panel").hidden) {
|
| 501 |
await readerContext.renderBookmarks();
|
| 502 |
if (editing && invoker && !invoker.isConnected && document.activeElement === document.body)
|
| 503 |
(
|
|
@@ -532,12 +532,12 @@ export function createReaderBindings(readerContext) {
|
|
| 532 |
first.focus();
|
| 533 |
}
|
| 534 |
});
|
| 535 |
-
for (const button of document.querySelectorAll(".reader-panel-tabs button"))
|
| 536 |
button.addEventListener("click", () => readerContext.selectPanel(button.dataset.panel));
|
| 537 |
-
document.querySelector(".reader-panel-tabs").addEventListener("keydown", (event) => {
|
| 538 |
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
|
| 539 |
-
const tabs = [...document.querySelectorAll(".reader-panel-tabs button:not([hidden])")],
|
| 540 |
-
current = tabs.
|
| 541 |
if (current < 0) return;
|
| 542 |
event.preventDefault();
|
| 543 |
const next =
|
|
@@ -555,7 +555,7 @@ export function createReaderBindings(readerContext) {
|
|
| 555 |
readerContext.bookmarksAllButton.setAttribute("aria-pressed", String(readerContext.panelState.showingAllBookmarks));
|
| 556 |
readerContext.renderBookmarks();
|
| 557 |
});
|
| 558 |
-
for (const button of document.querySelectorAll(".panel-search-toggle")) {
|
| 559 |
button.classList.remove("icon-button");
|
| 560 |
button.classList.add("text-action");
|
| 561 |
button.textContent = "搜索";
|
|
@@ -569,7 +569,7 @@ export function createReaderBindings(readerContext) {
|
|
| 569 |
readerContext.setPanelSearchOpen(button, button.getAttribute("aria-expanded") !== "true")
|
| 570 |
);
|
| 571 |
}
|
| 572 |
-
for (const input of document.querySelectorAll(".panel-search")) {
|
| 573 |
const view = input.closest(".reader-panel-view");
|
| 574 |
input.type = "search";
|
| 575 |
input.setAttribute(
|
|
@@ -577,7 +577,7 @@ export function createReaderBindings(readerContext) {
|
|
| 577 |
`搜索${view.querySelector(".panel-view-header strong")?.textContent || "列表"}`
|
| 578 |
);
|
| 579 |
input.addEventListener("input", (event) => {
|
| 580 |
-
if (!event.isComposing) readerContext.filterPanel(view);
|
| 581 |
});
|
| 582 |
input.addEventListener("compositionend", () => readerContext.filterPanel(view));
|
| 583 |
}
|
|
@@ -619,8 +619,7 @@ export function createReaderBindings(readerContext) {
|
|
| 619 |
)
|
| 620 |
readerContext.applyReaderTheme(event.data.theme, false);
|
| 621 |
});
|
| 622 |
-
document
|
| 623 |
-
.querySelector("#history")
|
| 624 |
.addEventListener("click", (event) =>
|
| 625 |
readerContext.setReaderPanelOpen(document.querySelector("#history").getAttribute("aria-expanded") !== "true", false, event.detail === 0)
|
| 626 |
);
|
|
@@ -708,7 +707,7 @@ export function createReaderBindings(readerContext) {
|
|
| 708 |
// Separators (line ends, inter-block gaps) are selectable text nodes
|
| 709 |
// directly inside the layer; a focus there is already valid text.
|
| 710 |
const focusElement = selection.focusNode?.nodeType === Node.ELEMENT_NODE
|
| 711 |
-
? selection.focusNode : selection.focusNode?.parentElement;
|
| 712 |
if (focusElement?.closest(".reader-pdf-text")) return;
|
| 713 |
const beforeAnchor = selection.focusNode && selection.anchorNode &&
|
| 714 |
(selection.focusNode === selection.anchorNode
|
|
|
|
| 105 |
}
|
| 106 |
if (
|
| 107 |
["history", "history-clear", "history-remove"].includes(change.type) &&
|
| 108 |
+
!/** @type {HTMLElement} */ (document.querySelector("#history-panel")).hidden
|
| 109 |
)
|
| 110 |
readerContext.renderHistory();
|
| 111 |
if (
|
| 112 |
["bookmark", "bookmark-remove"].includes(change.type) &&
|
| 113 |
(readerContext.panelState.showingAllBookmarks || !change.url || change.url === readerContext.sourceUrl) &&
|
| 114 |
+
!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden
|
| 115 |
)
|
| 116 |
readerContext.renderBookmarks();
|
| 117 |
})
|
|
|
|
| 266 |
readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
|
| 267 |
readerContext.contentSanitizerObserver = new MutationObserver(() => {
|
| 268 |
const seen = new Set();
|
| 269 |
+
for (const article of /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll(".foliate-continuous > article[data-section]"))) {
|
| 270 |
article.querySelectorAll("style,link[rel=stylesheet]").forEach((node) => node.remove());
|
| 271 |
const index = article.dataset.section;
|
| 272 |
if (seen.has(index)) article.remove();
|
|
|
|
| 332 |
readerContext.mediaPanel
|
| 333 |
.querySelector(".media-panel-bookmark")
|
| 334 |
.addEventListener("click", (event) => readerContext.openBookmarkPopover(event.currentTarget));
|
| 335 |
+
/** @type {HTMLElement} */ (document.querySelector(".page-controls")).hidden = !readerContext.capability.features.pagination;
|
| 336 |
+
/** @type {HTMLElement} */ (document.querySelector(".zoom-controls")).hidden = !readerContext.capability.features.zoom;
|
| 337 |
|
| 338 |
readerContext.status.hidden = true;
|
| 339 |
readerContext.mediaTab.setAttribute("aria-controls", "media-panel");
|
|
|
|
| 388 |
location.assign("/");
|
| 389 |
});
|
| 390 |
// Replay a Back tap made before this handler was bound.
|
| 391 |
+
if (window.__VOICE_READER_EARLY_BACK__?.()) /** @type {HTMLButtonElement} */ (document.querySelector("#back")).click();
|
| 392 |
}
|
| 393 |
|
| 394 |
function bindZoomAndPageControls() {
|
| 395 |
readerContext.setZoom(readerContext.documentState.zoom * 100, false);
|
| 396 |
+
for (const [id, delta] of /** @type {[string, number][]} */ ([
|
| 397 |
["#zoom-out", -10],
|
| 398 |
["#zoom-in", 10]
|
| 399 |
+
])) {
|
| 400 |
document.querySelector(id).addEventListener("click", () => {
|
| 401 |
readerContext.setZoom(Number(readerContext.zoomInput.value) + delta);
|
| 402 |
});
|
|
|
|
| 443 |
|
| 444 |
document.addEventListener("click", async (event) => {
|
| 445 |
const path = event.composedPath(),
|
| 446 |
+
link = /** @type {Element | undefined} */ (path.find((node) => node instanceof Element && node.matches?.("a[href]"))),
|
| 447 |
+
article = /** @type {HTMLElement | undefined} */ (path.find(
|
| 448 |
(node) =>
|
| 449 |
node instanceof Element && node.matches?.(".foliate-continuous article[data-section]")
|
| 450 |
+
));
|
| 451 |
if (!link || !article || !readerContext.epubRendition?.book) return;
|
| 452 |
const raw = link.getAttribute("href") || "";
|
| 453 |
if (raw.startsWith("/api/reader-resource?")) return;
|
|
|
|
| 473 |
readerContext.bookmarkRibbon.addEventListener("click", () => readerContext.openBookmarkPopover(readerContext.bookmarkRibbon));
|
| 474 |
document.querySelector("#bookmark-cancel").addEventListener("click", readerContext.closeBookmarkPopover);
|
| 475 |
document.querySelector("#bookmark-add").addEventListener("click", async (event) => {
|
| 476 |
+
const button = /** @type {HTMLButtonElement} */ (event.currentTarget),
|
| 477 |
editing = readerContext.panelState.editingBookmark;
|
| 478 |
const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();
|
| 479 |
const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,
|
|
|
|
| 497 |
);
|
| 498 |
const invoker = readerContext.bookmarkInvoker;
|
| 499 |
readerContext.closeBookmarkPopover();
|
| 500 |
+
if (!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden) {
|
| 501 |
await readerContext.renderBookmarks();
|
| 502 |
if (editing && invoker && !invoker.isConnected && document.activeElement === document.body)
|
| 503 |
(
|
|
|
|
| 532 |
first.focus();
|
| 533 |
}
|
| 534 |
});
|
| 535 |
+
for (const button of /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll(".reader-panel-tabs button")))
|
| 536 |
button.addEventListener("click", () => readerContext.selectPanel(button.dataset.panel));
|
| 537 |
+
/** @type {HTMLElement} */ (document.querySelector(".reader-panel-tabs")).addEventListener("keydown", (event) => {
|
| 538 |
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
|
| 539 |
+
const tabs = [.../** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll(".reader-panel-tabs button:not([hidden])"))],
|
| 540 |
+
current = tabs.findIndex(tab => tab === document.activeElement);
|
| 541 |
if (current < 0) return;
|
| 542 |
event.preventDefault();
|
| 543 |
const next =
|
|
|
|
| 555 |
readerContext.bookmarksAllButton.setAttribute("aria-pressed", String(readerContext.panelState.showingAllBookmarks));
|
| 556 |
readerContext.renderBookmarks();
|
| 557 |
});
|
| 558 |
+
for (const button of /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll(".panel-search-toggle"))) {
|
| 559 |
button.classList.remove("icon-button");
|
| 560 |
button.classList.add("text-action");
|
| 561 |
button.textContent = "搜索";
|
|
|
|
| 569 |
readerContext.setPanelSearchOpen(button, button.getAttribute("aria-expanded") !== "true")
|
| 570 |
);
|
| 571 |
}
|
| 572 |
+
for (const input of /** @type {NodeListOf<HTMLInputElement>} */ (document.querySelectorAll(".panel-search"))) {
|
| 573 |
const view = input.closest(".reader-panel-view");
|
| 574 |
input.type = "search";
|
| 575 |
input.setAttribute(
|
|
|
|
| 577 |
`搜索${view.querySelector(".panel-view-header strong")?.textContent || "列表"}`
|
| 578 |
);
|
| 579 |
input.addEventListener("input", (event) => {
|
| 580 |
+
if (!/** @type {InputEvent} */ (event).isComposing) readerContext.filterPanel(view);
|
| 581 |
});
|
| 582 |
input.addEventListener("compositionend", () => readerContext.filterPanel(view));
|
| 583 |
}
|
|
|
|
| 619 |
)
|
| 620 |
readerContext.applyReaderTheme(event.data.theme, false);
|
| 621 |
});
|
| 622 |
+
/** @type {HTMLButtonElement} */ (document.querySelector("#history"))
|
|
|
|
| 623 |
.addEventListener("click", (event) =>
|
| 624 |
readerContext.setReaderPanelOpen(document.querySelector("#history").getAttribute("aria-expanded") !== "true", false, event.detail === 0)
|
| 625 |
);
|
|
|
|
| 707 |
// Separators (line ends, inter-block gaps) are selectable text nodes
|
| 708 |
// directly inside the layer; a focus there is already valid text.
|
| 709 |
const focusElement = selection.focusNode?.nodeType === Node.ELEMENT_NODE
|
| 710 |
+
? /** @type {Element} */ (selection.focusNode) : selection.focusNode?.parentElement;
|
| 711 |
if (focusElement?.closest(".reader-pdf-text")) return;
|
| 712 |
const beforeAnchor = selection.focusNode && selection.anchorNode &&
|
| 713 |
(selection.focusNode === selection.anchorNode
|
static/reader/formats/reader-chapter-format.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
| 2 |
// cross-volume sidebar targets that point back into volume 1. Its own verified
|
| 3 |
// "总目录" links and each volume's adjacent "书名页" independently identify
|
| 4 |
// these destinations. Never apply this correction to another manifest version.
|
|
|
|
| 5 |
const REVIEWED_TOC_CORRECTIONS = new Map([
|
| 6 |
["7b150f1ba768d3bf4380b805676a32b8b2c18d7a8b4efb75be49a38da1dbf3a8", [
|
| 7 |
[1, "费曼物理学讲义:新千年版.第1卷", 4, "", 4, "chapter", 3],
|
|
@@ -223,7 +224,7 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 223 |
}
|
| 224 |
if (element.hasAttribute("srcset")) element.removeAttribute("srcset");
|
| 225 |
}
|
| 226 |
-
const article = document.createElement("article");
|
| 227 |
article.className = "reader-markdown reader-epub-chapter";
|
| 228 |
article.dataset.chapter = String(chapter.index);
|
| 229 |
if (doc.body?.id) article.id = doc.body.id;
|
|
@@ -268,6 +269,7 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 268 |
throw error;
|
| 269 |
});
|
| 270 |
};
|
|
|
|
| 271 |
const activateChapter = async (chapter, generation, destination = "") => {
|
| 272 |
chapterFocusIndex = chapter.index;
|
| 273 |
navigationProtectionCleanup?.();
|
|
@@ -320,8 +322,8 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 320 |
}
|
| 321 |
};
|
| 322 |
frame.addEventListener("click", async (event) => {
|
| 323 |
-
const link = event.target.closest?.("a[href]");
|
| 324 |
-
const article = link?.closest(".reader-epub-chapter");
|
| 325 |
if (
|
| 326 |
!article ||
|
| 327 |
event.button !== 0 ||
|
|
@@ -361,7 +363,7 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 361 |
});
|
| 362 |
const chapterVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({
|
| 363 |
limit: 12,
|
| 364 |
-
getLoaded: () => [...frame.querySelectorAll(":scope > .reader-epub-chapter")],
|
| 365 |
getIndex: article => Number(article.dataset.chapter),
|
| 366 |
getHeight: article => article.getBoundingClientRect().height,
|
| 367 |
canVirtualize: article => {
|
|
@@ -376,7 +378,7 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 376 |
},
|
| 377 |
virtualize: (article, index, height) => {
|
| 378 |
loaded.delete(index);
|
| 379 |
-
const marker = ensureSentinel(chapterAt(index));
|
| 380 |
const style = getComputedStyle(article);
|
| 381 |
marker.classList.add("reader-chapter-placeholder");
|
| 382 |
marker.style.height = `${height}px`;
|
|
@@ -419,7 +421,7 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 419 |
chapterWindowFrame = 0;
|
| 420 |
if (!chapterWindowReady || readerContext.readerAbortController.signal.aborted) return;
|
| 421 |
const view = readerContext.viewport.getBoundingClientRect();
|
| 422 |
-
const rows = [...frame.querySelectorAll(":scope > [data-chapter]")];
|
| 423 |
const current = rows.find(row => {
|
| 424 |
const rect = row.getBoundingClientRect();
|
| 425 |
return rect.top <= view.top + 80 && rect.bottom > view.top + 80;
|
|
@@ -446,7 +448,7 @@ export function createReaderChapterFormat(readerContext) {
|
|
| 446 |
if (!chapterWindowReady || chapterNavigating || readerContext.readerAbortController.signal.aborted) return;
|
| 447 |
for (const entry of entries) {
|
| 448 |
if (!entry.isIntersecting) continue;
|
| 449 |
-
const chapter = chapterAt(Number(entry.target.dataset.chapter));
|
| 450 |
if (chapter) fetchChapter(chapter).catch(() => {});
|
| 451 |
}
|
| 452 |
}, { root: readerContext.viewport });
|
|
|
|
| 2 |
// cross-volume sidebar targets that point back into volume 1. Its own verified
|
| 3 |
// "总目录" links and each volume's adjacent "书名页" independently identify
|
| 4 |
// these destinations. Never apply this correction to another manifest version.
|
| 5 |
+
/** @type {Map<string, [number, string, number, string, number, string, number][]>} */
|
| 6 |
const REVIEWED_TOC_CORRECTIONS = new Map([
|
| 7 |
["7b150f1ba768d3bf4380b805676a32b8b2c18d7a8b4efb75be49a38da1dbf3a8", [
|
| 8 |
[1, "费曼物理学讲义:新千年版.第1卷", 4, "", 4, "chapter", 3],
|
|
|
|
| 224 |
}
|
| 225 |
if (element.hasAttribute("srcset")) element.removeAttribute("srcset");
|
| 226 |
}
|
| 227 |
+
const article = /** @type {HTMLElement & {_chapterSearchHead?: Node | null}} */ (document.createElement("article"));
|
| 228 |
article.className = "reader-markdown reader-epub-chapter";
|
| 229 |
article.dataset.chapter = String(chapter.index);
|
| 230 |
if (doc.body?.id) article.id = doc.body.id;
|
|
|
|
| 269 |
throw error;
|
| 270 |
});
|
| 271 |
};
|
| 272 |
+
/** @param {string | {fragment?: string}} destination */
|
| 273 |
const activateChapter = async (chapter, generation, destination = "") => {
|
| 274 |
chapterFocusIndex = chapter.index;
|
| 275 |
navigationProtectionCleanup?.();
|
|
|
|
| 322 |
}
|
| 323 |
};
|
| 324 |
frame.addEventListener("click", async (event) => {
|
| 325 |
+
const link = /** @type {Element} */ (event.target).closest?.("a[href]");
|
| 326 |
+
const article = /** @type {HTMLElement | null | undefined} */ (link?.closest(".reader-epub-chapter"));
|
| 327 |
if (
|
| 328 |
!article ||
|
| 329 |
event.button !== 0 ||
|
|
|
|
| 363 |
});
|
| 364 |
const chapterVirtualizer = VoiceOfMLReaderVirtual.createSectionVirtualizer({
|
| 365 |
limit: 12,
|
| 366 |
+
getLoaded: () => [.../** @type {NodeListOf<HTMLElement & {_chapterSearchHead?: Node | null}>} */ (frame.querySelectorAll(":scope > .reader-epub-chapter"))],
|
| 367 |
getIndex: article => Number(article.dataset.chapter),
|
| 368 |
getHeight: article => article.getBoundingClientRect().height,
|
| 369 |
canVirtualize: article => {
|
|
|
|
| 378 |
},
|
| 379 |
virtualize: (article, index, height) => {
|
| 380 |
loaded.delete(index);
|
| 381 |
+
const marker = /** @type {HTMLButtonElement} */ (ensureSentinel(chapterAt(index)));
|
| 382 |
const style = getComputedStyle(article);
|
| 383 |
marker.classList.add("reader-chapter-placeholder");
|
| 384 |
marker.style.height = `${height}px`;
|
|
|
|
| 421 |
chapterWindowFrame = 0;
|
| 422 |
if (!chapterWindowReady || readerContext.readerAbortController.signal.aborted) return;
|
| 423 |
const view = readerContext.viewport.getBoundingClientRect();
|
| 424 |
+
const rows = [...frame.querySelectorAll(":scope > [data-chapter]")].map(row => /** @type {HTMLElement} */ (row));
|
| 425 |
const current = rows.find(row => {
|
| 426 |
const rect = row.getBoundingClientRect();
|
| 427 |
return rect.top <= view.top + 80 && rect.bottom > view.top + 80;
|
|
|
|
| 448 |
if (!chapterWindowReady || chapterNavigating || readerContext.readerAbortController.signal.aborted) return;
|
| 449 |
for (const entry of entries) {
|
| 450 |
if (!entry.isIntersecting) continue;
|
| 451 |
+
const chapter = chapterAt(Number(/** @type {HTMLElement} */ (entry.target).dataset.chapter));
|
| 452 |
if (chapter) fetchChapter(chapter).catch(() => {});
|
| 453 |
}
|
| 454 |
}, { root: readerContext.viewport });
|
static/reader/formats/reader-foliate-format.mjs
CHANGED
|
@@ -22,7 +22,7 @@ export function createReaderFoliateFormat(readerContext) {
|
|
| 22 |
|
| 23 |
function syncFoliateScrollLocation() {
|
| 24 |
if (!readerContext.foliateContinuous || !readerContext.navigationState.tocEntries.length) return;
|
| 25 |
-
const rows = [...document.querySelectorAll(".foliate-continuous article[data-section]")],
|
| 26 |
top = readerContext.viewport.getBoundingClientRect().top + 80;
|
| 27 |
let sectionIndex = -1,
|
| 28 |
sectionNode = null;
|
|
@@ -87,7 +87,7 @@ export function createReaderFoliateFormat(readerContext) {
|
|
| 87 |
function trimFoliateSections() {
|
| 88 |
if (!readerContext.foliateContinuous || !readerContext.foliateSectionVirtualizer) return;
|
| 89 |
const marker = readerContext.viewport.getBoundingClientRect().top + 80,
|
| 90 |
-
rows = [...document.querySelectorAll(".foliate-continuous article[data-section]")],
|
| 91 |
current =
|
| 92 |
rows.find((row) => {
|
| 93 |
const rect = row.getBoundingClientRect();
|
|
@@ -185,7 +185,7 @@ export function createReaderFoliateFormat(readerContext) {
|
|
| 185 |
selected = [];
|
| 186 |
let offset = 0;
|
| 187 |
while (walker.nextNode()) {
|
| 188 |
-
const node = walker.currentNode,
|
| 189 |
end = offset + node.length;
|
| 190 |
for (const interval of intervals)
|
| 191 |
if (interval.start < end && interval.end > offset)
|
|
@@ -211,7 +211,7 @@ export function createReaderFoliateFormat(readerContext) {
|
|
| 211 |
// Sections are prepared off-DOM; lazy images cannot enter a viewport yet.
|
| 212 |
image.loading = "eager";
|
| 213 |
image.decoding = "async";
|
| 214 |
-
if (!image.complete) await new Promise((resolve) => {
|
| 215 |
const finish = () => {
|
| 216 |
image.removeEventListener("load", finish);
|
| 217 |
image.removeEventListener("error", finish);
|
|
@@ -222,7 +222,7 @@ export function createReaderFoliateFormat(readerContext) {
|
|
| 222 |
image.addEventListener("load", finish, { once: true });
|
| 223 |
image.addEventListener("error", finish, { once: true });
|
| 224 |
if (image.complete) finish();
|
| 225 |
-
});
|
| 226 |
if (active) {
|
| 227 |
try { await image.decode?.(); } catch (_) {}
|
| 228 |
}
|
|
@@ -353,7 +353,7 @@ export function createReaderFoliateFormat(readerContext) {
|
|
| 353 |
signal.throwIfAborted();
|
| 354 |
readerContext.assertReaderActive();
|
| 355 |
for (const node of doc.querySelectorAll("style,link")) node.remove();
|
| 356 |
-
const article = document.createElement("article");
|
| 357 |
article.dataset.section = String(index);
|
| 358 |
const shadow = article.attachShadow({ mode: "open" }),
|
| 359 |
baseStyle = document.createElement("style"),
|
|
|
|
| 22 |
|
| 23 |
function syncFoliateScrollLocation() {
|
| 24 |
if (!readerContext.foliateContinuous || !readerContext.navigationState.tocEntries.length) return;
|
| 25 |
+
const rows = [...document.querySelectorAll(".foliate-continuous article[data-section]")].map(row => /** @type {HTMLElement} */ (row)),
|
| 26 |
top = readerContext.viewport.getBoundingClientRect().top + 80;
|
| 27 |
let sectionIndex = -1,
|
| 28 |
sectionNode = null;
|
|
|
|
| 87 |
function trimFoliateSections() {
|
| 88 |
if (!readerContext.foliateContinuous || !readerContext.foliateSectionVirtualizer) return;
|
| 89 |
const marker = readerContext.viewport.getBoundingClientRect().top + 80,
|
| 90 |
+
rows = [...document.querySelectorAll(".foliate-continuous article[data-section]")].map(row => /** @type {HTMLElement} */ (row)),
|
| 91 |
current =
|
| 92 |
rows.find((row) => {
|
| 93 |
const rect = row.getBoundingClientRect();
|
|
|
|
| 185 |
selected = [];
|
| 186 |
let offset = 0;
|
| 187 |
while (walker.nextNode()) {
|
| 188 |
+
const node = /** @type {Text} */ (walker.currentNode),
|
| 189 |
end = offset + node.length;
|
| 190 |
for (const interval of intervals)
|
| 191 |
if (interval.start < end && interval.end > offset)
|
|
|
|
| 211 |
// Sections are prepared off-DOM; lazy images cannot enter a viewport yet.
|
| 212 |
image.loading = "eager";
|
| 213 |
image.decoding = "async";
|
| 214 |
+
if (!image.complete) await /** @type {Promise<void>} */ (new Promise((resolve) => {
|
| 215 |
const finish = () => {
|
| 216 |
image.removeEventListener("load", finish);
|
| 217 |
image.removeEventListener("error", finish);
|
|
|
|
| 222 |
image.addEventListener("load", finish, { once: true });
|
| 223 |
image.addEventListener("error", finish, { once: true });
|
| 224 |
if (image.complete) finish();
|
| 225 |
+
}));
|
| 226 |
if (active) {
|
| 227 |
try { await image.decode?.(); } catch (_) {}
|
| 228 |
}
|
|
|
|
| 353 |
signal.throwIfAborted();
|
| 354 |
readerContext.assertReaderActive();
|
| 355 |
for (const node of doc.querySelectorAll("style,link")) node.remove();
|
| 356 |
+
const article = /** @type {HTMLElement & {_resolveSearchAnchor?: ((anchor: (source: Document) => Range) => {node: Text; start: number; end: number}[] | null) | null}} */ (document.createElement("article"));
|
| 357 |
article.dataset.section = String(index);
|
| 358 |
const shadow = article.attachShadow({ mode: "open" }),
|
| 359 |
baseStyle = document.createElement("style"),
|
static/reader/formats/reader-format-controller.mjs
CHANGED
|
@@ -162,7 +162,7 @@ export function createReaderFormatController(readerContext) {
|
|
| 162 |
readerContext.readerRuntime.update("source", { extension: readerContext.extension });
|
| 163 |
readerContext.capability = readerContext.readerRuntime.negotiate(VoiceOfMLReader.capability(readerContext.extension));
|
| 164 |
readerContext.content.dataset.mode = readerContext.capability.mode;
|
| 165 |
-
document.querySelector(".page-controls").hidden = true;
|
| 166 |
}
|
| 167 |
readerContext.syncCapabilityControls();
|
| 168 |
readerContext.downloadButton.href = readerContext.readerDownloadUrl(readerContext.documentState.title, readerContext.downloadUrl);
|
|
@@ -174,7 +174,7 @@ export function createReaderFormatController(readerContext) {
|
|
| 174 |
readerContext.formatAdapters.activate(readerContext.capability.mode);
|
| 175 |
readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
|
| 176 |
if (readerContext.validOcr(readerContext.ocrUrl)) {
|
| 177 |
-
const ocr = document.querySelector("#ocr") || document.createElement("a");
|
| 178 |
ocr.id = "ocr";
|
| 179 |
ocr.className = "text-button";
|
| 180 |
ocr.target = "_blank";
|
|
@@ -266,13 +266,13 @@ export function createReaderFormatController(readerContext) {
|
|
| 266 |
function syncCapabilityControls() {
|
| 267 |
readerContext.content.dataset.mode = readerContext.capability.mode || "unsupported";
|
| 268 |
readerContext.pageInvertToggle.hidden = !["pdf", "pdf-pages"].includes(readerContext.capability.mode);
|
| 269 |
-
document.querySelector(".page-controls").hidden = !readerContext.capability.features.pagination;
|
| 270 |
-
document.querySelector(".zoom-controls").hidden = !readerContext.capability.features.zoom;
|
| 271 |
readerContext.mediaTab.hidden = !readerContext.capability.features.media;
|
| 272 |
const noNativeText = !!readerContext.pdfDocument?.readerNoSearchableText && !readerContext.ocrManifestUrl && !readerContext.ocrUrl;
|
| 273 |
const searchOpen = readerContext.panelState.selected === "full-search";
|
| 274 |
if (noNativeText && !searchOpen && document.activeElement === readerContext.fullSearchButton)
|
| 275 |
-
document.querySelector("#history").focus({ preventScroll: true });
|
| 276 |
readerContext.fullSearchButton.hidden = !readerContext.capability.features.search || (noNativeText && !searchOpen) || (readerContext.capability.mode === "pdf-pages" && !readerContext.ocrManifestUrl && (!readerContext.pdfHybridUrl || readerContext.pdfHybridSearchUnavailable));
|
| 277 |
readerContext.bookmarkRibbon.hidden = !readerContext.capability.features.bookmarks;
|
| 278 |
readerContext.readingProgressSummary.querySelector(".reader-progress-bookmark").hidden =
|
|
|
|
| 162 |
readerContext.readerRuntime.update("source", { extension: readerContext.extension });
|
| 163 |
readerContext.capability = readerContext.readerRuntime.negotiate(VoiceOfMLReader.capability(readerContext.extension));
|
| 164 |
readerContext.content.dataset.mode = readerContext.capability.mode;
|
| 165 |
+
/** @type {HTMLElement} */ (document.querySelector(".page-controls")).hidden = true;
|
| 166 |
}
|
| 167 |
readerContext.syncCapabilityControls();
|
| 168 |
readerContext.downloadButton.href = readerContext.readerDownloadUrl(readerContext.documentState.title, readerContext.downloadUrl);
|
|
|
|
| 174 |
readerContext.formatAdapters.activate(readerContext.capability.mode);
|
| 175 |
readerContext.applyReaderMetadata(readerContext.resolvedReaderData);
|
| 176 |
if (readerContext.validOcr(readerContext.ocrUrl)) {
|
| 177 |
+
const ocr = /** @type {HTMLAnchorElement} */ (document.querySelector("#ocr")) || document.createElement("a");
|
| 178 |
ocr.id = "ocr";
|
| 179 |
ocr.className = "text-button";
|
| 180 |
ocr.target = "_blank";
|
|
|
|
| 266 |
function syncCapabilityControls() {
|
| 267 |
readerContext.content.dataset.mode = readerContext.capability.mode || "unsupported";
|
| 268 |
readerContext.pageInvertToggle.hidden = !["pdf", "pdf-pages"].includes(readerContext.capability.mode);
|
| 269 |
+
/** @type {HTMLElement} */ (document.querySelector(".page-controls")).hidden = !readerContext.capability.features.pagination;
|
| 270 |
+
/** @type {HTMLElement} */ (document.querySelector(".zoom-controls")).hidden = !readerContext.capability.features.zoom;
|
| 271 |
readerContext.mediaTab.hidden = !readerContext.capability.features.media;
|
| 272 |
const noNativeText = !!readerContext.pdfDocument?.readerNoSearchableText && !readerContext.ocrManifestUrl && !readerContext.ocrUrl;
|
| 273 |
const searchOpen = readerContext.panelState.selected === "full-search";
|
| 274 |
if (noNativeText && !searchOpen && document.activeElement === readerContext.fullSearchButton)
|
| 275 |
+
/** @type {HTMLElement} */ (document.querySelector("#history")).focus({ preventScroll: true });
|
| 276 |
readerContext.fullSearchButton.hidden = !readerContext.capability.features.search || (noNativeText && !searchOpen) || (readerContext.capability.mode === "pdf-pages" && !readerContext.ocrManifestUrl && (!readerContext.pdfHybridUrl || readerContext.pdfHybridSearchUnavailable));
|
| 277 |
readerContext.bookmarkRibbon.hidden = !readerContext.capability.features.bookmarks;
|
| 278 |
readerContext.readingProgressSummary.querySelector(".reader-progress-bookmark").hidden =
|
static/reader/pdf/reader-pdf-page-window.mjs
CHANGED
|
@@ -543,7 +543,7 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 543 |
(items) => {
|
| 544 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 545 |
for (const entry of items) if (entry.isIntersecting) {
|
| 546 |
-
entry.target.dataset.renderVisible = readerContext.isPdfPageVisible(entry.target) ? "1" : "0";
|
| 547 |
readerContext.renderPdfInBackground(entry.target);
|
| 548 |
}
|
| 549 |
},
|
|
@@ -553,11 +553,11 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 553 |
(items) => {
|
| 554 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 555 |
for (const entry of items) {
|
| 556 |
-
entry.target.dataset.renderVisible = entry.isIntersecting ? "1" : "0";
|
| 557 |
if (entry.isIntersecting) {
|
| 558 |
readerContext.promotePdfRenderWaiter(entry.target);
|
| 559 |
readerContext.renderPdfInBackground(entry.target, false, readerContext.pdfPagePriority(entry.target));
|
| 560 |
-
if (entry.target.dataset.renderState === "rendered") readerContext.renderPdfOcrText(entry.target);
|
| 561 |
}
|
| 562 |
}
|
| 563 |
},
|
|
@@ -709,7 +709,7 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 709 |
};
|
| 710 |
readerContext.status.textContent = "正在检查文档";
|
| 711 |
document.querySelector("#page-total").textContent = "";
|
| 712 |
-
const gateControls = document.querySelector(".page-controls"), gateWasHidden = gateControls.hidden;
|
| 713 |
gateControls.hidden = true;
|
| 714 |
try {
|
| 715 |
if (!readerContext.restorationFailed && canPreview && !readerContext.ocrManifestUrl &&
|
|
@@ -810,7 +810,9 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 810 |
});
|
| 811 |
warmTask.catch(() => {});
|
| 812 |
controls.hidden = false;
|
| 813 |
-
const total =
|
|
|
|
|
|
|
| 814 |
const inputHidden = readerContext.pageInput.hidden, totalHidden = total.hidden;
|
| 815 |
const previousLabel = previous.getAttribute("aria-label"), nextLabel = next.getAttribute("aria-label");
|
| 816 |
const previousWasDisabled = previous.disabled, nextWasDisabled = next.disabled;
|
|
@@ -912,9 +914,9 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 912 |
};
|
| 913 |
const previewObserver=new IntersectionObserver(entries=>{
|
| 914 |
for (const entry of entries) {
|
| 915 |
-
if (!previewActive || !entry.isIntersecting || entry.target.dataset.renderState === "rendered") continue;
|
| 916 |
cancelWarm?.();
|
| 917 |
-
const shell=entry.target;
|
| 918 |
renderPreview(shell);
|
| 919 |
if (Number(shell.dataset.page) === previewCount && readerContext.isPdfPageVisible(shell)) requestMore();
|
| 920 |
}
|
|
@@ -1146,7 +1148,7 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 1146 |
(entries) =>
|
| 1147 |
entries.forEach((entry) => {
|
| 1148 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 1149 |
-
entry.target.dataset.renderVisible = entry.isIntersecting && readerContext.isPdfPageVisible(entry.target) ? "1" : "0";
|
| 1150 |
if (entry.isIntersecting) readerContext.renderPdfInBackground(entry.target);
|
| 1151 |
}),
|
| 1152 |
{ root: document.querySelector("#viewport"), rootMargin: `${readerContext.PDF_PREFETCH_MARGIN}px 0px` }
|
|
@@ -1155,10 +1157,10 @@ export function createReaderPdfPageWindow(readerContext) {
|
|
| 1155 |
(entries) =>
|
| 1156 |
entries.forEach((entry) => {
|
| 1157 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 1158 |
-
entry.target.dataset.renderVisible = entry.isIntersecting ? "1" : "0";
|
| 1159 |
if (entry.isIntersecting) {
|
| 1160 |
readerContext.promotePdfRenderWaiter(entry.target);
|
| 1161 |
-
if (readerContext.pdfUserHasScrolled || entry.target.dataset.renderState !== "rendering")
|
| 1162 |
readerContext.renderPdfInBackground(entry.target, false, readerContext.pdfPagePriority(entry.target));
|
| 1163 |
}
|
| 1164 |
}),
|
|
|
|
| 543 |
(items) => {
|
| 544 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 545 |
for (const entry of items) if (entry.isIntersecting) {
|
| 546 |
+
/** @type {HTMLElement} */ (entry.target).dataset.renderVisible = readerContext.isPdfPageVisible(entry.target) ? "1" : "0";
|
| 547 |
readerContext.renderPdfInBackground(entry.target);
|
| 548 |
}
|
| 549 |
},
|
|
|
|
| 553 |
(items) => {
|
| 554 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 555 |
for (const entry of items) {
|
| 556 |
+
/** @type {HTMLElement} */ (entry.target).dataset.renderVisible = entry.isIntersecting ? "1" : "0";
|
| 557 |
if (entry.isIntersecting) {
|
| 558 |
readerContext.promotePdfRenderWaiter(entry.target);
|
| 559 |
readerContext.renderPdfInBackground(entry.target, false, readerContext.pdfPagePriority(entry.target));
|
| 560 |
+
if (/** @type {HTMLElement} */ (entry.target).dataset.renderState === "rendered") readerContext.renderPdfOcrText(entry.target);
|
| 561 |
}
|
| 562 |
}
|
| 563 |
},
|
|
|
|
| 709 |
};
|
| 710 |
readerContext.status.textContent = "正在检查文档";
|
| 711 |
document.querySelector("#page-total").textContent = "";
|
| 712 |
+
const gateControls = /** @type {HTMLElement} */ (document.querySelector(".page-controls")), gateWasHidden = gateControls.hidden;
|
| 713 |
gateControls.hidden = true;
|
| 714 |
try {
|
| 715 |
if (!readerContext.restorationFailed && canPreview && !readerContext.ocrManifestUrl &&
|
|
|
|
| 810 |
});
|
| 811 |
warmTask.catch(() => {});
|
| 812 |
controls.hidden = false;
|
| 813 |
+
const total = /** @type {HTMLElement} */ (document.querySelector("#page-total")),
|
| 814 |
+
previous = /** @type {HTMLButtonElement} */ (document.querySelector("#page-prev")),
|
| 815 |
+
next = /** @type {HTMLButtonElement} */ (document.querySelector("#page-next"));
|
| 816 |
const inputHidden = readerContext.pageInput.hidden, totalHidden = total.hidden;
|
| 817 |
const previousLabel = previous.getAttribute("aria-label"), nextLabel = next.getAttribute("aria-label");
|
| 818 |
const previousWasDisabled = previous.disabled, nextWasDisabled = next.disabled;
|
|
|
|
| 914 |
};
|
| 915 |
const previewObserver=new IntersectionObserver(entries=>{
|
| 916 |
for (const entry of entries) {
|
| 917 |
+
if (!previewActive || !entry.isIntersecting || /** @type {HTMLElement} */ (entry.target).dataset.renderState === "rendered") continue;
|
| 918 |
cancelWarm?.();
|
| 919 |
+
const shell=/** @type {HTMLElement} */ (entry.target);
|
| 920 |
renderPreview(shell);
|
| 921 |
if (Number(shell.dataset.page) === previewCount && readerContext.isPdfPageVisible(shell)) requestMore();
|
| 922 |
}
|
|
|
|
| 1148 |
(entries) =>
|
| 1149 |
entries.forEach((entry) => {
|
| 1150 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 1151 |
+
/** @type {HTMLElement} */ (entry.target).dataset.renderVisible = entry.isIntersecting && readerContext.isPdfPageVisible(entry.target) ? "1" : "0";
|
| 1152 |
if (entry.isIntersecting) readerContext.renderPdfInBackground(entry.target);
|
| 1153 |
}),
|
| 1154 |
{ root: document.querySelector("#viewport"), rootMargin: `${readerContext.PDF_PREFETCH_MARGIN}px 0px` }
|
|
|
|
| 1157 |
(entries) =>
|
| 1158 |
entries.forEach((entry) => {
|
| 1159 |
if (readerContext.readerAbortController.signal.aborted) return;
|
| 1160 |
+
/** @type {HTMLElement} */ (entry.target).dataset.renderVisible = entry.isIntersecting ? "1" : "0";
|
| 1161 |
if (entry.isIntersecting) {
|
| 1162 |
readerContext.promotePdfRenderWaiter(entry.target);
|
| 1163 |
+
if (readerContext.pdfUserHasScrolled || /** @type {HTMLElement} */ (entry.target).dataset.renderState !== "rendering")
|
| 1164 |
readerContext.renderPdfInBackground(entry.target, false, readerContext.pdfPagePriority(entry.target));
|
| 1165 |
}
|
| 1166 |
}),
|
tests/test_static_checks.py
CHANGED
|
@@ -115,6 +115,78 @@ class StaticGateTests(unittest.TestCase):
|
|
| 115 |
source.write_text('VoiceOfMLReaderSecurity.createByteBudget("not a number");\n')
|
| 116 |
self.assert_check(self.run_check(*check), False, "TS2345")
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
def test_worker_type_contract_rejects_invalid_responses(self):
|
| 119 |
source = self.root / "static/worker.js"
|
| 120 |
config = self.root / "jsconfig.json"
|
|
|
|
| 115 |
source.write_text('VoiceOfMLReaderSecurity.createByteBudget("not a number");\n')
|
| 116 |
self.assert_check(self.run_check(*check), False, "TS2345")
|
| 117 |
|
| 118 |
+
def test_chapter_scheduler_type_contract_rejects_invalid_index(self):
|
| 119 |
+
source = self.root / "static/chapter-usage.js"
|
| 120 |
+
config = self.root / "jsconfig.json"
|
| 121 |
+
config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True,
|
| 122 |
+
"strict": False, "skipLibCheck": True, "target": "esnext"},
|
| 123 |
+
"files": [str(ROOT / "typings/reader-globals.d.ts"), "static/chapter-usage.js"]}))
|
| 124 |
+
check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config]
|
| 125 |
+
create = ('const chapters = VoiceOfMLReaderChapters.createChapterScheduler({ '
|
| 126 |
+
'create: async (index, signal, priority) => index });\n')
|
| 127 |
+
source.write_text(create + 'chapters.load(42);\n')
|
| 128 |
+
self.assert_check(self.run_check(*check), True, "")
|
| 129 |
+
source.write_text(create + 'chapters.load("not a chapter number");\n')
|
| 130 |
+
self.assert_check(self.run_check(*check), False, "TS2345")
|
| 131 |
+
|
| 132 |
+
def test_static_globals_match_their_runtime_implementations(self):
|
| 133 |
+
# Compile the actual classic scripts with their public declarations so
|
| 134 |
+
# that an incorrect hand-written interface cannot hide behind any.
|
| 135 |
+
source = self.root / "static/global-contract.js"
|
| 136 |
+
config = self.root / "jsconfig.json"
|
| 137 |
+
config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True,
|
| 138 |
+
"strict": False, "skipLibCheck": True, "target": "esnext", "moduleDetection": "force"},
|
| 139 |
+
"files": [str(ROOT / "typings/reader-globals.d.ts"),
|
| 140 |
+
str(ROOT / "static/search/search-session.js"),
|
| 141 |
+
str(ROOT / "static/search/download-controller.js"),
|
| 142 |
+
str(ROOT / "static/search/reader-navigation.js"), "static/global-contract.js"]}))
|
| 143 |
+
source.write_text("console.log('contracts loaded');\n")
|
| 144 |
+
check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config]
|
| 145 |
+
self.assert_check(self.run_check(*check), True, "")
|
| 146 |
+
|
| 147 |
+
def test_every_first_party_browser_script_is_type_checked(self):
|
| 148 |
+
compiler = ROOT / "node_modules/typescript/bin/tsc"
|
| 149 |
+
checked = set()
|
| 150 |
+
for config in ("jsconfig.check.json", "jsconfig.service-worker.json"):
|
| 151 |
+
options = json.loads((ROOT / config).read_text())["compilerOptions"]
|
| 152 |
+
self.assertTrue(options.get("allowJs"), config)
|
| 153 |
+
self.assertTrue(options.get("checkJs"), config)
|
| 154 |
+
self.assertTrue(options.get("noEmit"), config)
|
| 155 |
+
self.assertFalse(options.get("noCheck", False), config)
|
| 156 |
+
result = subprocess.run(["node", compiler, "--project", config, "--listFilesOnly"],
|
| 157 |
+
cwd=ROOT, text=True, stdout=subprocess.PIPE,
|
| 158 |
+
stderr=subprocess.STDOUT, timeout=30)
|
| 159 |
+
self.assertEqual(result.returncode, 0, result.stdout)
|
| 160 |
+
checked.update(Path(line).resolve() for line in result.stdout.splitlines())
|
| 161 |
+
sources = {path.resolve() for path in (ROOT / "static").rglob("*")
|
| 162 |
+
if path.is_file() and path.suffix in (".js", ".mjs")
|
| 163 |
+
and "vendor" not in path.parts and "foliate-reader" not in path.parts}
|
| 164 |
+
self.assertFalse(sources - checked, f"browser scripts missing from type check: {sorted(sources - checked)}")
|
| 165 |
+
for path in sources:
|
| 166 |
+
self.assertNotRegex(path.read_text(), r"@ts-(?:nocheck|ignore|expect-error)\b", str(path))
|
| 167 |
+
|
| 168 |
+
def test_entry_points_reject_type_errors_with_production_config(self):
|
| 169 |
+
# Exercise the real project config in an isolated copy rather than
|
| 170 |
+
# merely checking that the two entry paths appear in --listFilesOnly.
|
| 171 |
+
for path in (ROOT / "static").rglob("*"):
|
| 172 |
+
if (path.is_file() and path.suffix in (".js", ".mjs")
|
| 173 |
+
and "vendor" not in path.parts and "foliate-reader" not in path.parts):
|
| 174 |
+
target = self.root / path.relative_to(ROOT)
|
| 175 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 176 |
+
shutil.copyfile(path, target)
|
| 177 |
+
shutil.copytree(ROOT / "static/vendor/djvu-rs-reader", self.root / "static/vendor/djvu-rs-reader")
|
| 178 |
+
shutil.copytree(ROOT / "typings", self.root / "typings")
|
| 179 |
+
shutil.copyfile(ROOT / "jsconfig.check.json", self.root / "jsconfig.check.json")
|
| 180 |
+
check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", "jsconfig.check.json"]
|
| 181 |
+
self.assert_check(self.run_check(*check), True, "")
|
| 182 |
+
for relative in ("static/app.js", "static/reader.js"):
|
| 183 |
+
source = self.root / relative
|
| 184 |
+
original = source.read_text()
|
| 185 |
+
with self.subTest(entry=relative):
|
| 186 |
+
source.write_text(original + '\n/** @type {number} */ const __staticGateBadType = "wrong";\n')
|
| 187 |
+
self.assert_check(self.run_check(*check), False, "TS2322")
|
| 188 |
+
source.write_text(original)
|
| 189 |
+
|
| 190 |
def test_worker_type_contract_rejects_invalid_responses(self):
|
| 191 |
source = self.root / "static/worker.js"
|
| 192 |
config = self.root / "jsconfig.json"
|
tests/test_static_contract.py
CHANGED
|
@@ -259,7 +259,7 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 259 |
self.assertIn("converted_reader_indices(assets, full_repo)", backend)
|
| 260 |
self.assertIn("loadReaderAssets().then(refreshResultReaderActions)", self.js)
|
| 261 |
self.assertIn('id="page-number"', reader_html)
|
| 262 |
-
assert_source_contains(self, 'document.querySelector(".page-controls").hidden = !capability.features.pagination', reader)
|
| 263 |
self.assertRegex(reader_css, r'prefers-contrast\s*:\s*more')
|
| 264 |
assert_source_contains(self, 'Number(existing.result.lastReadAt) > Number(entry.lastReadAt)', reader_store)
|
| 265 |
self.assertIn('BroadcastChannel', reader_store)
|
|
@@ -515,7 +515,7 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 515 |
self.assertIn('function reconcileVirtualRows(items, start, end, topH, bottomH)', self.js)
|
| 516 |
self.assertIn('Number(row.dataset.contentVersion) !== VSCROLL.contentVersion', self.js)
|
| 517 |
self.assertIn('VSCROLL.templateCache.size > 240', self.js)
|
| 518 |
-
self.assertIn('function scheduleVirtualRender()', self.js)
|
| 519 |
self.assertIn('scheduleVirtualRender()', self.js)
|
| 520 |
self.assertIn('scheduleVirtualRender(true)', self.js)
|
| 521 |
self.assertIn('renderAfterScroll: false', self.js)
|
|
|
|
| 259 |
self.assertIn("converted_reader_indices(assets, full_repo)", backend)
|
| 260 |
self.assertIn("loadReaderAssets().then(refreshResultReaderActions)", self.js)
|
| 261 |
self.assertIn('id="page-number"', reader_html)
|
| 262 |
+
assert_source_contains(self, 'document.querySelector(".page-controls")).hidden = !capability.features.pagination', reader)
|
| 263 |
self.assertRegex(reader_css, r'prefers-contrast\s*:\s*more')
|
| 264 |
assert_source_contains(self, 'Number(existing.result.lastReadAt) > Number(entry.lastReadAt)', reader_store)
|
| 265 |
self.assertIn('BroadcastChannel', reader_store)
|
|
|
|
| 515 |
self.assertIn('function reconcileVirtualRows(items, start, end, topH, bottomH)', self.js)
|
| 516 |
self.assertIn('Number(row.dataset.contentVersion) !== VSCROLL.contentVersion', self.js)
|
| 517 |
self.assertIn('VSCROLL.templateCache.size > 240', self.js)
|
| 518 |
+
self.assertIn('function scheduleVirtualRender(scrollIntent = false)', self.js)
|
| 519 |
self.assertIn('scheduleVirtualRender()', self.js)
|
| 520 |
self.assertIn('scheduleVirtualRender(true)', self.js)
|
| 521 |
self.assertIn('renderAfterScroll: false', self.js)
|
typings/foliate/view.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// The pinned Foliate module registers <foliate-view> as a side effect.
|
| 2 |
+
// Reader uses the custom-element interface declared in reader-globals.d.ts.
|
| 3 |
+
export {};
|
typings/reader-globals.d.ts
CHANGED
|
@@ -70,10 +70,106 @@ interface ReaderRequestManagerApi { createReaderRequestManager(options?: object)
|
|
| 70 |
interface ReaderRuntimeApi { createReaderRuntime(): any }
|
| 71 |
interface ReaderAdaptersApi { createAdapterRegistry(): any }
|
| 72 |
interface ReaderScrollApi { createScrollAnchorManager(options: {viewport: Element; candidates: () => unknown}): any }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
declare var VoiceOfMLReaderRequests: ReaderRequestManagerApi;
|
| 74 |
declare var VoiceOfMLReaderRuntime: ReaderRuntimeApi;
|
| 75 |
declare var VoiceOfMLReaderAdapters: ReaderAdaptersApi;
|
| 76 |
declare var VoiceOfMLReaderScroll: ReaderScrollApi;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
declare var DOMPurify: {
|
| 78 |
sanitize(input: string, options: {RETURN_DOM_FRAGMENT: true; [key: string]: unknown}): DocumentFragment;
|
| 79 |
sanitize(input: string, options?: object): string;
|
|
@@ -106,10 +202,15 @@ interface Window {
|
|
| 106 |
VoiceOfMLReaderRuntime: ReaderRuntimeApi;
|
| 107 |
VoiceOfMLReaderAdapters: ReaderAdaptersApi;
|
| 108 |
VoiceOfMLReaderScroll: ReaderScrollApi;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
__VOICE_PDF_PRELOAD__?: any;
|
| 110 |
__VOICE_READER_CHAPTER_PRELOAD__?: any;
|
| 111 |
__VOICE_READER_RESOLVE__?: any;
|
| 112 |
-
__VOICE_READER_EARLY_BACK__?: boolean;
|
| 113 |
VoiceOfMLReaderPdfDiagnostics?: any;
|
| 114 |
fetchFile?: any;
|
| 115 |
RufflePlayer?: any;
|
|
|
|
| 70 |
interface ReaderRuntimeApi { createReaderRuntime(): any }
|
| 71 |
interface ReaderAdaptersApi { createAdapterRegistry(): any }
|
| 72 |
interface ReaderScrollApi { createScrollAnchorManager(options: {viewport: Element; candidates: () => unknown}): any }
|
| 73 |
+
interface ChapterScheduler<T> {
|
| 74 |
+
load(index: number, demand?: boolean, exclusive?: boolean): Promise<T>;
|
| 75 |
+
prefetch(indices: number[]): void;
|
| 76 |
+
dispose(): void;
|
| 77 |
+
readonly activeCount: number;
|
| 78 |
+
readonly pendingCount: number;
|
| 79 |
+
}
|
| 80 |
+
interface ReaderChaptersApi {
|
| 81 |
+
createChapterScheduler<T>(options: {
|
| 82 |
+
create(index: number, signal: AbortSignal, priority: "high" | "low"): T | Promise<T>;
|
| 83 |
+
concurrency?: number;
|
| 84 |
+
speculativeLimit?: number;
|
| 85 |
+
}): ChapterScheduler<T>;
|
| 86 |
+
createChapterRepository<T>(options: {
|
| 87 |
+
count: number;
|
| 88 |
+
find(index: number): T | null;
|
| 89 |
+
create(index: number): T | Promise<T>;
|
| 90 |
+
commit?(index: number, value: T): T;
|
| 91 |
+
}): {
|
| 92 |
+
load(index: number): Promise<T | null>;
|
| 93 |
+
release(index: number): boolean;
|
| 94 |
+
dispose(): void;
|
| 95 |
+
readonly pending: Promise<T | null>[];
|
| 96 |
+
readonly disposed: boolean;
|
| 97 |
+
};
|
| 98 |
+
}
|
| 99 |
+
interface ReaderVirtualApi {
|
| 100 |
+
createSectionVirtualizer<T extends Element>(options: {
|
| 101 |
+
limit: number;
|
| 102 |
+
getLoaded(): T[];
|
| 103 |
+
getIndex(node: T): number;
|
| 104 |
+
getHeight(node: T): number;
|
| 105 |
+
virtualize(node: T, index: number, height: number): unknown;
|
| 106 |
+
release(index: number): unknown;
|
| 107 |
+
preserve?(change: () => void): void;
|
| 108 |
+
canVirtualize?(node: T, index: number): boolean;
|
| 109 |
+
}): { trim(centerIndex: number): {removed: number; retained: number}; dispose(): void; readonly limit: number };
|
| 110 |
+
}
|
| 111 |
declare var VoiceOfMLReaderRequests: ReaderRequestManagerApi;
|
| 112 |
declare var VoiceOfMLReaderRuntime: ReaderRuntimeApi;
|
| 113 |
declare var VoiceOfMLReaderAdapters: ReaderAdaptersApi;
|
| 114 |
declare var VoiceOfMLReaderScroll: ReaderScrollApi;
|
| 115 |
+
declare var VoiceOfMLReaderChapters: ReaderChaptersApi;
|
| 116 |
+
declare var VoiceOfMLReaderVirtual: ReaderVirtualApi;
|
| 117 |
+
|
| 118 |
+
interface SearchSessionApi {
|
| 119 |
+
createSearchSession(options: {canPersist(): boolean; canRestore(target?: URL): boolean}): {
|
| 120 |
+
openSearchSessionDB(): Promise<IDBDatabase>;
|
| 121 |
+
persistSearchSession(): Promise<void>;
|
| 122 |
+
restoreSearchSession(): Promise<boolean>;
|
| 123 |
+
};
|
| 124 |
+
}
|
| 125 |
+
interface DownloadControllerApi {
|
| 126 |
+
createDownloadController(options: {
|
| 127 |
+
buildCheckUrl(link: string): string;
|
| 128 |
+
buildDownloadUrl(filename: string, link: string): string;
|
| 129 |
+
triggerDownload(url: string): void;
|
| 130 |
+
showToast(message: string, duration?: number): void;
|
| 131 |
+
isSpeculativeAllowed?(): boolean;
|
| 132 |
+
isBatchActive?(): boolean;
|
| 133 |
+
timeout?: number;
|
| 134 |
+
}): {
|
| 135 |
+
downloadChecks: Map<string, unknown>;
|
| 136 |
+
downloadCheckQueue: unknown[];
|
| 137 |
+
pendingDownloads: Map<string, unknown>;
|
| 138 |
+
checkDownload(link: string, speculative?: boolean, signal?: AbortSignal): Promise<boolean | string>;
|
| 139 |
+
runDownloadCheck(item: unknown): Promise<void>;
|
| 140 |
+
pumpDownloadChecks(): void;
|
| 141 |
+
scheduleDownloadLaunch(filename: string, link: string, cancelled: () => boolean): Promise<boolean>;
|
| 142 |
+
downloadFile(filename: string, link: string, options?: {button?: HTMLElement; quiet?: boolean; skipCheck?: boolean; signal?: AbortSignal; batch?: object}): Promise<boolean>;
|
| 143 |
+
readonly activeDownloadChecks: number;
|
| 144 |
+
};
|
| 145 |
+
}
|
| 146 |
+
interface SearchReaderNavigationApi {
|
| 147 |
+
createNavigation(readerPath: string, options?: {resume?(url: string): void; close?(): void}): {
|
| 148 |
+
parse(raw: string): URL;
|
| 149 |
+
mergeSearchParams(target: string | URL, source: URLSearchParams | string, options?: {hashRoute?: boolean; keys?: readonly string[]}): URL;
|
| 150 |
+
saved(): {readerUrl?: string; shareUrl?: string; returnScroll?: unknown} | null;
|
| 151 |
+
prepare(raw: string, returnUrl: string): URL;
|
| 152 |
+
remember(url: URL, returnScroll: object, replace?: boolean): void;
|
| 153 |
+
mount(url: URL): HTMLIFrameElement;
|
| 154 |
+
unmount(keepSpeech?: boolean): HTMLElement | null;
|
| 155 |
+
dismiss(): void;
|
| 156 |
+
replace(raw: string, returnScroll: object): HTMLIFrameElement;
|
| 157 |
+
accepts(event: MessageEvent): boolean;
|
| 158 |
+
persistProgress(progress: object): void;
|
| 159 |
+
readonly returnFocus: HTMLElement | null;
|
| 160 |
+
};
|
| 161 |
+
}
|
| 162 |
+
declare var VoiceOfMLSearchSession: SearchSessionApi;
|
| 163 |
+
declare var VoiceOfMLDownloadController: DownloadControllerApi;
|
| 164 |
+
declare var VoiceOfMLReaderNavigation: SearchReaderNavigationApi;
|
| 165 |
+
|
| 166 |
+
// The imported module registers this custom element; it does not export the
|
| 167 |
+
// book to our code. The concrete sections are provided by the chosen engine.
|
| 168 |
+
interface FoliateViewElement extends HTMLElement {
|
| 169 |
+
open(file: File): Promise<void>;
|
| 170 |
+
book: { sections: Array<{linear?: string}> };
|
| 171 |
+
}
|
| 172 |
+
interface HTMLElementTagNameMap { "foliate-view": FoliateViewElement }
|
| 173 |
declare var DOMPurify: {
|
| 174 |
sanitize(input: string, options: {RETURN_DOM_FRAGMENT: true; [key: string]: unknown}): DocumentFragment;
|
| 175 |
sanitize(input: string, options?: object): string;
|
|
|
|
| 202 |
VoiceOfMLReaderRuntime: ReaderRuntimeApi;
|
| 203 |
VoiceOfMLReaderAdapters: ReaderAdaptersApi;
|
| 204 |
VoiceOfMLReaderScroll: ReaderScrollApi;
|
| 205 |
+
VoiceOfMLReaderChapters: ReaderChaptersApi;
|
| 206 |
+
VoiceOfMLReaderVirtual: ReaderVirtualApi;
|
| 207 |
+
VoiceOfMLSearchSession: SearchSessionApi;
|
| 208 |
+
VoiceOfMLDownloadController: DownloadControllerApi;
|
| 209 |
+
VoiceOfMLReaderNavigation: SearchReaderNavigationApi;
|
| 210 |
__VOICE_PDF_PRELOAD__?: any;
|
| 211 |
__VOICE_READER_CHAPTER_PRELOAD__?: any;
|
| 212 |
__VOICE_READER_RESOLVE__?: any;
|
| 213 |
+
__VOICE_READER_EARLY_BACK__?: () => boolean;
|
| 214 |
VoiceOfMLReaderPdfDiagnostics?: any;
|
| 215 |
fetchFile?: any;
|
| 216 |
RufflePlayer?: any;
|