vomebook commited on
Commit ·
975d991
1
Parent(s): 489d865
retire native DOCX reader
Browse files- scripts/build/build_static_assets.mjs +1 -1
- scripts/build/check_reader_release.mjs +1 -1
- static/reader-resources.js +1 -12
- static/reader.css +4 -67
- static/reader.js +1 -17
- static/reader/core/reader-bindings.mjs +0 -5
- static/reader/core/reader-contract.js +2 -5
- static/reader/core/reader-document-loader.mjs +0 -5
- static/reader/core/reader-source.mjs +0 -1
- static/reader/formats/reader-docx-format.mjs +0 -129
- static/reader/formats/reader-format-controller.mjs +0 -1
- static/reader/reader-components.mjs +0 -1
- static/reader/search/reader-search-backends.mjs +1 -1
- static/reader/ui/reader-navigation.mjs +1 -1
- static/reader/ui/reader-progress.mjs +3 -3
- static/reader/ui/reader-ui.mjs +0 -2
- tests/test_reader_architecture.js +2 -2
- tests/test_reader_format_pipeline.py +3 -6
- tests/test_reader_live_formats.py +2 -9
- tests/test_reader_optimizations.py +6 -113
- tests/test_reader_performance.py +18 -62
- tests/test_reader_refactor.py +15 -24
- tests/test_reader_regression.js +5 -2
- tests/test_reader_style.py +4 -20
- tests/test_static_contract.py +8 -13
scripts/build/build_static_assets.mjs
CHANGED
|
@@ -18,7 +18,7 @@ function rewrite(text, filename) {
|
|
| 18 |
return quote + pinned + quote;
|
| 19 |
});
|
| 20 |
text = text.replace(/VoiceOfMLReaderResources\.engineAssets\(([\w$]+),\s*"(\/static\/)"\)/g,
|
| 21 |
-
(_, extension, base) => "(" + JSON.stringify(Object.fromEntries(["pdf", "epub", "mobi", "azw", "azw3", "fb2", "fbz", "
|
| 22 |
text = text.replace(/VoiceOfMLReaderResources\.(shellAssets|runtimePaths)\("(\/static\/)"\)/g,
|
| 23 |
(_, method, base) => JSON.stringify(resources[method](base)));
|
| 24 |
for (const [original, versioned] of replacements) text = text.split(original).join(versioned);
|
|
|
|
| 18 |
return quote + pinned + quote;
|
| 19 |
});
|
| 20 |
text = text.replace(/VoiceOfMLReaderResources\.engineAssets\(([\w$]+),\s*"(\/static\/)"\)/g,
|
| 21 |
+
(_, extension, base) => "(" + JSON.stringify(Object.fromEntries(["pdf", "epub", "mobi", "azw", "azw3", "fb2", "fbz", "md", "markdown", "html", "htm"].map(ext => [ext, resources.engineAssets(ext, base)]))) + `[${extension}]||[])`);
|
| 22 |
text = text.replace(/VoiceOfMLReaderResources\.(shellAssets|runtimePaths)\("(\/static\/)"\)/g,
|
| 23 |
(_, method, base) => JSON.stringify(resources[method](base)));
|
| 24 |
for (const [original, versioned] of replacements) text = text.split(original).join(versioned);
|
scripts/build/check_reader_release.mjs
CHANGED
|
@@ -201,7 +201,7 @@ function crossCheck(githubRoot, hfRoot) {
|
|
| 201 |
"reader/ui/reader-document-styles.mjs",
|
| 202 |
"reader/core/reader-diagnostics.mjs", "reader/core/reader-lifecycle.mjs", "reader/ui/reader-bookmarks.mjs",
|
| 203 |
"reader/formats/reader-media-format.mjs", "reader/core/reader-document-loader.mjs", "reader/formats/reader-html-format.mjs",
|
| 204 |
-
"reader/formats/reader-text-format.mjs", "reader/formats/reader-chapter-format.mjs",
|
| 205 |
"reader/pdf/pdf-worker-wrapper.mjs"
|
| 206 |
];
|
| 207 |
for (const file of exact) {
|
|
|
|
| 201 |
"reader/ui/reader-document-styles.mjs",
|
| 202 |
"reader/core/reader-diagnostics.mjs", "reader/core/reader-lifecycle.mjs", "reader/ui/reader-bookmarks.mjs",
|
| 203 |
"reader/formats/reader-media-format.mjs", "reader/core/reader-document-loader.mjs", "reader/formats/reader-html-format.mjs",
|
| 204 |
+
"reader/formats/reader-text-format.mjs", "reader/formats/reader-chapter-format.mjs",
|
| 205 |
"reader/pdf/pdf-worker-wrapper.mjs"
|
| 206 |
];
|
| 207 |
for (const file of exact) {
|
static/reader-resources.js
CHANGED
|
@@ -22,16 +22,6 @@
|
|
| 22 |
file: "purify.min.js",
|
| 23 |
sha256: "2c90a9b46d6463f26038a29b686e82bc91de01fdac9d5229e7cfe3b360134ea2"
|
| 24 |
},
|
| 25 |
-
jszip: {
|
| 26 |
-
url: "https://cdn.jsdelivr.net/npm/jszip@3.10.2/dist/jszip.min.js",
|
| 27 |
-
file: "jszip.min.js",
|
| 28 |
-
sha256: "7f839b2d4688b845c105ebf5d2f9803075f91ea0fe72bdaac176c3a04dd3d2c1"
|
| 29 |
-
},
|
| 30 |
-
docx: {
|
| 31 |
-
url: "https://cdn.jsdelivr.net/npm/docx-preview@0.4.1/dist/docx-preview.min.js",
|
| 32 |
-
file: "docx-preview.min.js",
|
| 33 |
-
sha256: "c4a133c65a112799e35b143c572dfff9e923a3bf39b5fd3b07a06aa0f8f530c2"
|
| 34 |
-
},
|
| 35 |
ruffle: {
|
| 36 |
url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js",
|
| 37 |
file: "ruffle.js",
|
|
@@ -101,7 +91,7 @@
|
|
| 101 |
"reader/formats/reader-foliate-format.mjs", "reader/ui/reader-progress.mjs", "reader/ui/reader-bookmarks.mjs", "reader/formats/reader-media-format.mjs",
|
| 102 |
"reader/core/reader-document-loader.mjs", "reader/pdf/reader-pdf-page-window.mjs", "reader/pdf/reader-pdf-text-runtime.mjs",
|
| 103 |
"reader/formats/reader-html-format.mjs", "reader/pdf/reader-pdf-renderer.mjs", "reader/formats/reader-text-format.mjs",
|
| 104 |
-
"reader/formats/reader-chapter-format.mjs", "reader/formats/reader-
|
| 105 |
"reader/pdf/reader-pdf-engine.mjs", "reader/pdf/reader-pdf-search.mjs", "reader/core/reader-bindings.mjs", "reader/ui/reader-document-styles.mjs"
|
| 106 |
]);
|
| 107 |
const readerFiles = Object.freeze([
|
|
@@ -158,7 +148,6 @@
|
|
| 158 |
];
|
| 159 |
if (["epub", "mobi", "azw", "azw3", "fb2", "fbz"].includes(extension))
|
| 160 |
return [base + "foliate-reader/view.js" + foliateSuffix];
|
| 161 |
-
if (extension === "docx") return [vendorUrl("jszip", base), vendorUrl("docx", base)];
|
| 162 |
if (["md", "markdown", "html", "htm"].includes(extension))
|
| 163 |
return [vendorUrl("marked", base), vendorUrl("purify", base)];
|
| 164 |
return [];
|
|
|
|
| 22 |
file: "purify.min.js",
|
| 23 |
sha256: "2c90a9b46d6463f26038a29b686e82bc91de01fdac9d5229e7cfe3b360134ea2"
|
| 24 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
ruffle: {
|
| 26 |
url: "https://unpkg.com/@ruffle-rs/ruffle@0.7.1/ruffle.js",
|
| 27 |
file: "ruffle.js",
|
|
|
|
| 91 |
"reader/formats/reader-foliate-format.mjs", "reader/ui/reader-progress.mjs", "reader/ui/reader-bookmarks.mjs", "reader/formats/reader-media-format.mjs",
|
| 92 |
"reader/core/reader-document-loader.mjs", "reader/pdf/reader-pdf-page-window.mjs", "reader/pdf/reader-pdf-text-runtime.mjs",
|
| 93 |
"reader/formats/reader-html-format.mjs", "reader/pdf/reader-pdf-renderer.mjs", "reader/formats/reader-text-format.mjs",
|
| 94 |
+
"reader/formats/reader-chapter-format.mjs", "reader/formats/reader-format-controller.mjs",
|
| 95 |
"reader/pdf/reader-pdf-engine.mjs", "reader/pdf/reader-pdf-search.mjs", "reader/core/reader-bindings.mjs", "reader/ui/reader-document-styles.mjs"
|
| 96 |
]);
|
| 97 |
const readerFiles = Object.freeze([
|
|
|
|
| 148 |
];
|
| 149 |
if (["epub", "mobi", "azw", "azw3", "fb2", "fbz"].includes(extension))
|
| 150 |
return [base + "foliate-reader/view.js" + foliateSuffix];
|
|
|
|
| 151 |
if (["md", "markdown", "html", "htm"].includes(extension))
|
| 152 |
return [vendorUrl("marked", base), vendorUrl("purify", base)];
|
| 153 |
return [];
|
static/reader.css
CHANGED
|
@@ -1000,13 +1000,6 @@ body {
|
|
| 1000 |
@keyframes reader-page-loading-reveal {
|
| 1001 |
to { opacity: 1; }
|
| 1002 |
}
|
| 1003 |
-
.reader-docx-page {
|
| 1004 |
-
content-visibility: auto;
|
| 1005 |
-
contain-intrinsic-block-size: auto var(--reader-docx-height, 1123px);
|
| 1006 |
-
}
|
| 1007 |
-
.reader-docx-page:focus-within {
|
| 1008 |
-
content-visibility: visible;
|
| 1009 |
-
}
|
| 1010 |
.reader-page canvas {
|
| 1011 |
display: block;
|
| 1012 |
position: relative;
|
|
@@ -1255,7 +1248,7 @@ body {
|
|
| 1255 |
height: 100%;
|
| 1256 |
min-height: 320px;
|
| 1257 |
}
|
| 1258 |
-
/* Isolated HTML
|
| 1259 |
.html-frame {
|
| 1260 |
display: block;
|
| 1261 |
width: 100%;
|
|
@@ -1272,47 +1265,16 @@ body {
|
|
| 1272 |
max-width: none;
|
| 1273 |
padding: 0;
|
| 1274 |
}
|
| 1275 |
-
.docx-body {
|
| 1276 |
-
overflow-x: auto;
|
| 1277 |
-
color: #e7e9eb;
|
| 1278 |
-
}
|
| 1279 |
-
.docx-body .reader-docx-wrapper {
|
| 1280 |
-
background: transparent;
|
| 1281 |
-
padding: 0;
|
| 1282 |
-
zoom: var(--reader-zoom);
|
| 1283 |
-
width: 100%;
|
| 1284 |
-
max-width: none;
|
| 1285 |
-
align-items: stretch;
|
| 1286 |
-
}
|
| 1287 |
-
.docx-body .reader-docx-wrapper > section.reader-docx {
|
| 1288 |
-
width: 100% !important;
|
| 1289 |
-
max-width: none;
|
| 1290 |
-
box-sizing: border-box;
|
| 1291 |
-
padding-left: clamp(16px, 5vw, 2cm) !important;
|
| 1292 |
-
padding-right: clamp(16px, 5vw, 2cm) !important;
|
| 1293 |
-
margin: 0 auto 18px;
|
| 1294 |
-
box-shadow: 0 2px 14px #0008;
|
| 1295 |
-
}
|
| 1296 |
-
.docx-body.reader-document-dark .reader-docx {
|
| 1297 |
-
background: #181b1e !important;
|
| 1298 |
-
color: #e7e9eb !important;
|
| 1299 |
-
}
|
| 1300 |
-
.docx-body.reader-document-dark .reader-docx :where(:not(svg, svg *, img, canvas, video, audio, math, math *)),
|
| 1301 |
:root[data-theme="dark"] .reader-epub-chapter :where(:not(svg, svg *, img, canvas, video, audio, math, math *)) {
|
| 1302 |
color: inherit !important;
|
| 1303 |
background-color: transparent !important;
|
| 1304 |
border-color: #4a5056 !important;
|
| 1305 |
text-shadow: none !important;
|
| 1306 |
}
|
| 1307 |
-
.docx-body.reader-document-dark .reader-docx :is(table, pre, code, blockquote) {
|
| 1308 |
-
background-color: #202428 !important;
|
| 1309 |
-
}
|
| 1310 |
-
.docx-body.reader-document-dark .reader-docx a,
|
| 1311 |
:root[data-theme="dark"] .reader-epub-chapter a {
|
| 1312 |
color: #8ab4e8 !important;
|
| 1313 |
}
|
| 1314 |
-
:root[data-theme="dark"] .reader-epub-chapter mark.full-search-highlight
|
| 1315 |
-
.docx-body.reader-document-dark .reader-docx mark.full-search-highlight {
|
| 1316 |
background: #ffd54f !important;
|
| 1317 |
color: #111 !important;
|
| 1318 |
}
|
|
@@ -1391,14 +1353,9 @@ body {
|
|
| 1391 |
color: #202124;
|
| 1392 |
}
|
| 1393 |
:root[data-theme="light"] .reader-text,
|
| 1394 |
-
:root[data-theme="light"] .reader-markdown
|
| 1395 |
-
:root[data-theme="light"] .docx-body {
|
| 1396 |
color: #202124;
|
| 1397 |
}
|
| 1398 |
-
:root[data-theme="light"] .docx-body .reader-docx {
|
| 1399 |
-
background: #fff !important;
|
| 1400 |
-
color: #202124 !important;
|
| 1401 |
-
}
|
| 1402 |
:root[data-theme="light"] .full-search-input {
|
| 1403 |
background: #f3f5f6;
|
| 1404 |
border-color: #c7ccd0;
|
|
@@ -1455,9 +1412,7 @@ body {
|
|
| 1455 |
:root.theme-transition .bookmark-popover,
|
| 1456 |
:root.theme-transition .bookmark-popover button,
|
| 1457 |
:root.theme-transition .reader-text,
|
| 1458 |
-
:root.theme-transition .reader-markdown
|
| 1459 |
-
:root.theme-transition .docx-body,
|
| 1460 |
-
:root.theme-transition .docx-body .reader-docx {
|
| 1461 |
transition:
|
| 1462 |
background-color 260ms ease,
|
| 1463 |
color 260ms ease,
|
|
@@ -1548,24 +1503,6 @@ body {
|
|
| 1548 |
.foliate-continuous > article {
|
| 1549 |
overflow-wrap: anywhere;
|
| 1550 |
}
|
| 1551 |
-
.docx-body,
|
| 1552 |
-
.docx-body .reader-docx-wrapper {
|
| 1553 |
-
min-width: 0;
|
| 1554 |
-
max-width: 100%;
|
| 1555 |
-
box-sizing: border-box;
|
| 1556 |
-
}
|
| 1557 |
-
.docx-body .reader-docx-wrapper > section.reader-docx {
|
| 1558 |
-
width: 100% !important;
|
| 1559 |
-
max-width: none;
|
| 1560 |
-
min-width: 0;
|
| 1561 |
-
overflow-wrap: anywhere;
|
| 1562 |
-
}
|
| 1563 |
-
.docx-body .reader-docx-wrapper img,
|
| 1564 |
-
.docx-body .reader-docx-wrapper svg,
|
| 1565 |
-
.docx-body .reader-docx-wrapper video {
|
| 1566 |
-
max-width: 100%;
|
| 1567 |
-
height: auto;
|
| 1568 |
-
}
|
| 1569 |
.html-frame {
|
| 1570 |
height: calc(100dvh - var(--reader-toolbar-height));
|
| 1571 |
}
|
|
|
|
| 1000 |
@keyframes reader-page-loading-reveal {
|
| 1001 |
to { opacity: 1; }
|
| 1002 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1003 |
.reader-page canvas {
|
| 1004 |
display: block;
|
| 1005 |
position: relative;
|
|
|
|
| 1248 |
height: 100%;
|
| 1249 |
min-height: 320px;
|
| 1250 |
}
|
| 1251 |
+
/* Isolated HTML */
|
| 1252 |
.html-frame {
|
| 1253 |
display: block;
|
| 1254 |
width: 100%;
|
|
|
|
| 1265 |
max-width: none;
|
| 1266 |
padding: 0;
|
| 1267 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1268 |
:root[data-theme="dark"] .reader-epub-chapter :where(:not(svg, svg *, img, canvas, video, audio, math, math *)) {
|
| 1269 |
color: inherit !important;
|
| 1270 |
background-color: transparent !important;
|
| 1271 |
border-color: #4a5056 !important;
|
| 1272 |
text-shadow: none !important;
|
| 1273 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1274 |
:root[data-theme="dark"] .reader-epub-chapter a {
|
| 1275 |
color: #8ab4e8 !important;
|
| 1276 |
}
|
| 1277 |
+
:root[data-theme="dark"] .reader-epub-chapter mark.full-search-highlight {
|
|
|
|
| 1278 |
background: #ffd54f !important;
|
| 1279 |
color: #111 !important;
|
| 1280 |
}
|
|
|
|
| 1353 |
color: #202124;
|
| 1354 |
}
|
| 1355 |
:root[data-theme="light"] .reader-text,
|
| 1356 |
+
:root[data-theme="light"] .reader-markdown {
|
|
|
|
| 1357 |
color: #202124;
|
| 1358 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1359 |
:root[data-theme="light"] .full-search-input {
|
| 1360 |
background: #f3f5f6;
|
| 1361 |
border-color: #c7ccd0;
|
|
|
|
| 1412 |
:root.theme-transition .bookmark-popover,
|
| 1413 |
:root.theme-transition .bookmark-popover button,
|
| 1414 |
:root.theme-transition .reader-text,
|
| 1415 |
+
:root.theme-transition .reader-markdown {
|
|
|
|
|
|
|
| 1416 |
transition:
|
| 1417 |
background-color 260ms ease,
|
| 1418 |
color 260ms ease,
|
|
|
|
| 1503 |
.foliate-continuous > article {
|
| 1504 |
overflow-wrap: anywhere;
|
| 1505 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1506 |
.html-frame {
|
| 1507 |
height: calc(100dvh - var(--reader-toolbar-height));
|
| 1508 |
}
|
static/reader.js
CHANGED
|
@@ -42,7 +42,6 @@ import {
|
|
| 42 |
createReaderPdfRenderer,
|
| 43 |
createReaderTextFormat,
|
| 44 |
createReaderChapterFormat,
|
| 45 |
-
createReaderDocxFormat,
|
| 46 |
createReaderFormatController,
|
| 47 |
createReaderPdfEngine,
|
| 48 |
createReaderPdfSearch
|
|
@@ -53,13 +52,11 @@ const readerContext = {
|
|
| 53 |
get DISCOURSE_HTML_STYLE() { return DISCOURSE_HTML_STYLE; },
|
| 54 |
get DISCOURSE_POST_SELECTOR() { return DISCOURSE_POST_SELECTOR; },
|
| 55 |
get DISCOURSE_TITLE_SELECTOR() { return DISCOURSE_TITLE_SELECTOR; },
|
| 56 |
-
get DOCX_PREVIEW_URL() { return DOCX_PREVIEW_URL; },
|
| 57 |
get EPUB_HTML_TAGS() { return EPUB_HTML_TAGS; },
|
| 58 |
get EPUB_HTML_VOID_TAGS() { return EPUB_HTML_VOID_TAGS; },
|
| 59 |
get FOLIATE_LOADED_SECTION_LIMIT() { return FOLIATE_LOADED_SECTION_LIMIT; },
|
| 60 |
get FOLIATE_PREFETCH_MARGIN() { return FOLIATE_PREFETCH_MARGIN; },
|
| 61 |
get HTML_FRAME_STYLE() { return HTML_FRAME_STYLE; },
|
| 62 |
-
get JSZIP_URL() { return JSZIP_URL; },
|
| 63 |
get MARKED_URL() { return MARKED_URL; },
|
| 64 |
get PDFJS_CMAP_URL() { return PDFJS_CMAP_URL; },
|
| 65 |
get PDFJS_STANDARD_FONT_URL() { return PDFJS_STANDARD_FONT_URL; },
|
|
@@ -126,7 +123,6 @@ const readerContext = {
|
|
| 126 |
get createV3Repository() { return createV3Repository; },
|
| 127 |
get detectTextEncoding() { return detectTextEncoding; }, set detectTextEncoding(value) { detectTextEncoding = value; },
|
| 128 |
get documentState() { return documentState; },
|
| 129 |
-
get docxPageNodes() { return docxPageNodes; }, set docxPageNodes(value) { docxPageNodes = value; },
|
| 130 |
get domSearch() { return domSearch; },
|
| 131 |
get downloadButton() { return downloadButton; },
|
| 132 |
get downloadFeedback() { return downloadFeedback; },
|
|
@@ -190,7 +186,6 @@ const readerContext = {
|
|
| 190 |
get isReaderGenerationCurrent() { return isReaderGenerationCurrent; }, set isReaderGenerationCurrent(value) { isReaderGenerationCurrent = value; },
|
| 191 |
get lastSavedProgress() { return lastSavedProgress; }, set lastSavedProgress(value) { lastSavedProgress = value; },
|
| 192 |
get loadChapterManifestDocument() { return loadChapterManifestDocument; }, set loadChapterManifestDocument(value) { loadChapterManifestDocument = value; },
|
| 193 |
-
get loadDocxDocument() { return loadDocxDocument; }, set loadDocxDocument(value) { loadDocxDocument = value; },
|
| 194 |
get loadHtmlDocument() { return loadHtmlDocument; }, set loadHtmlDocument(value) { loadHtmlDocument = value; },
|
| 195 |
get loadImageDocument() { return loadImageDocument; }, set loadImageDocument(value) { loadImageDocument = value; },
|
| 196 |
get loadMarkdownDocument() { return loadMarkdownDocument; }, set loadMarkdownDocument(value) { loadMarkdownDocument = value; },
|
|
@@ -338,7 +333,6 @@ const readerContext = {
|
|
| 338 |
get releasePdfWorker() { return releasePdfWorker; }, set releasePdfWorker(value) { releasePdfWorker = value; },
|
| 339 |
get renderBookmarks() { return renderBookmarks; }, set renderBookmarks(value) { renderBookmarks = value; },
|
| 340 |
get renderChapterManifest() { return renderChapterManifest; }, set renderChapterManifest(value) { renderChapterManifest = value; },
|
| 341 |
-
get renderDocx() { return renderDocx; }, set renderDocx(value) { renderDocx = value; },
|
| 342 |
get renderFoliate() { return renderFoliate; }, set renderFoliate(value) { renderFoliate = value; },
|
| 343 |
get renderFullSearchResults() { return renderFullSearchResults; },
|
| 344 |
get renderHtml() { return renderHtml; }, set renderHtml(value) { renderHtml = value; },
|
|
@@ -505,8 +499,6 @@ const readerContext = {
|
|
| 505 |
get loadPdfTaskWithTimeout() { return loadPdfTaskWithTimeout; }, set loadPdfTaskWithTimeout(value) { loadPdfTaskWithTimeout = value; },
|
| 506 |
get loadPdfWithTimeout() { return loadPdfWithTimeout; }, set loadPdfWithTimeout(value) { loadPdfWithTimeout = value; },
|
| 507 |
get makePdfSearchPageLoader() { return makePdfSearchPageLoader; }, set makePdfSearchPageLoader(value) { makePdfSearchPageLoader = value; },
|
| 508 |
-
get memoizeDocxAssets() { return memoizeDocxAssets; }, set memoizeDocxAssets(value) { memoizeDocxAssets = value; },
|
| 509 |
-
get memoizeDocxResource() { return memoizeDocxResource; }, set memoizeDocxResource(value) { memoizeDocxResource = value; },
|
| 510 |
get normalizeEpubDocument() { return normalizeEpubDocument; }, set normalizeEpubDocument(value) { normalizeEpubDocument = value; },
|
| 511 |
get notifyReaderUiState() { return notifyReaderUiState; }, set notifyReaderUiState(value) { notifyReaderUiState = value; },
|
| 512 |
get pdfManifestPrefetchConcurrency() { return pdfManifestPrefetchConcurrency; }, set pdfManifestPrefetchConcurrency(value) { pdfManifestPrefetchConcurrency = value; },
|
|
@@ -632,7 +624,7 @@ let {
|
|
| 632 |
let {
|
| 633 |
loadScript, fetchWithReaderTimeout, retryableReaderProxyError, retryReaderProxy,
|
| 634 |
fetchReaderUrl, fetchReaderResponse, prepareReaderDocument, readPreparedBytes,
|
| 635 |
-
loadTextDocument, loadMarkdownDocument, loadHtmlDocument,
|
| 636 |
loadMediaDocument, loadImageDocument, loadChapterManifestDocument
|
| 637 |
} = createReaderDocumentLoader(readerContext);
|
| 638 |
|
|
@@ -670,10 +662,6 @@ let {
|
|
| 670 |
renderChapterManifest, captureChapterPosition, restoreChapterPosition
|
| 671 |
} = createReaderChapterFormat(readerContext);
|
| 672 |
|
| 673 |
-
let {
|
| 674 |
-
renderDocx, memoizeDocxResource, memoizeDocxAssets
|
| 675 |
-
} = createReaderDocxFormat(readerContext);
|
| 676 |
-
|
| 677 |
let {
|
| 678 |
disposeFormatResources, registerReaderFormatAdapters, resolveReaderSource, start,
|
| 679 |
syncCapabilityControls
|
|
@@ -701,8 +689,6 @@ const PDFJS_CMAP_URL = "/static/vendor/cmaps/";
|
|
| 701 |
const PDFJS_STANDARD_FONT_URL = "/static/vendor/standard_fonts/";
|
| 702 |
const MARKED_URL = VoiceOfMLReaderResources.vendorUrl("marked", "/static/");
|
| 703 |
const PURIFY_URL = VoiceOfMLReaderResources.vendorUrl("purify", "/static/");
|
| 704 |
-
const JSZIP_URL = VoiceOfMLReaderResources.vendorUrl("jszip", "/static/");
|
| 705 |
-
const DOCX_PREVIEW_URL = VoiceOfMLReaderResources.vendorUrl("docx", "/static/");
|
| 706 |
const RUFFLE_URL = VoiceOfMLReaderResources.vendors.ruffle.url;
|
| 707 |
const READER_PROXY_TIMEOUT_MS = 120000;
|
| 708 |
const readerRequestManager = VoiceOfMLReaderRequests.createReaderRequestManager();
|
|
@@ -809,8 +795,6 @@ let folderNavigationTarget = null;
|
|
| 809 |
let bookmarkInvoker = null;
|
| 810 |
const bookmarkInertSiblings = new Map();
|
| 811 |
let pdfDocument = null;
|
| 812 |
-
let docxPageNodes = [];
|
| 813 |
-
readerBindings.ownDocxPageNodes();
|
| 814 |
let pdfPageManifest = null;
|
| 815 |
let pdfOcrManifest = null;
|
| 816 |
let pdfOcrManifestPromise = null;
|
|
|
|
| 42 |
createReaderPdfRenderer,
|
| 43 |
createReaderTextFormat,
|
| 44 |
createReaderChapterFormat,
|
|
|
|
| 45 |
createReaderFormatController,
|
| 46 |
createReaderPdfEngine,
|
| 47 |
createReaderPdfSearch
|
|
|
|
| 52 |
get DISCOURSE_HTML_STYLE() { return DISCOURSE_HTML_STYLE; },
|
| 53 |
get DISCOURSE_POST_SELECTOR() { return DISCOURSE_POST_SELECTOR; },
|
| 54 |
get DISCOURSE_TITLE_SELECTOR() { return DISCOURSE_TITLE_SELECTOR; },
|
|
|
|
| 55 |
get EPUB_HTML_TAGS() { return EPUB_HTML_TAGS; },
|
| 56 |
get EPUB_HTML_VOID_TAGS() { return EPUB_HTML_VOID_TAGS; },
|
| 57 |
get FOLIATE_LOADED_SECTION_LIMIT() { return FOLIATE_LOADED_SECTION_LIMIT; },
|
| 58 |
get FOLIATE_PREFETCH_MARGIN() { return FOLIATE_PREFETCH_MARGIN; },
|
| 59 |
get HTML_FRAME_STYLE() { return HTML_FRAME_STYLE; },
|
|
|
|
| 60 |
get MARKED_URL() { return MARKED_URL; },
|
| 61 |
get PDFJS_CMAP_URL() { return PDFJS_CMAP_URL; },
|
| 62 |
get PDFJS_STANDARD_FONT_URL() { return PDFJS_STANDARD_FONT_URL; },
|
|
|
|
| 123 |
get createV3Repository() { return createV3Repository; },
|
| 124 |
get detectTextEncoding() { return detectTextEncoding; }, set detectTextEncoding(value) { detectTextEncoding = value; },
|
| 125 |
get documentState() { return documentState; },
|
|
|
|
| 126 |
get domSearch() { return domSearch; },
|
| 127 |
get downloadButton() { return downloadButton; },
|
| 128 |
get downloadFeedback() { return downloadFeedback; },
|
|
|
|
| 186 |
get isReaderGenerationCurrent() { return isReaderGenerationCurrent; }, set isReaderGenerationCurrent(value) { isReaderGenerationCurrent = value; },
|
| 187 |
get lastSavedProgress() { return lastSavedProgress; }, set lastSavedProgress(value) { lastSavedProgress = value; },
|
| 188 |
get loadChapterManifestDocument() { return loadChapterManifestDocument; }, set loadChapterManifestDocument(value) { loadChapterManifestDocument = value; },
|
|
|
|
| 189 |
get loadHtmlDocument() { return loadHtmlDocument; }, set loadHtmlDocument(value) { loadHtmlDocument = value; },
|
| 190 |
get loadImageDocument() { return loadImageDocument; }, set loadImageDocument(value) { loadImageDocument = value; },
|
| 191 |
get loadMarkdownDocument() { return loadMarkdownDocument; }, set loadMarkdownDocument(value) { loadMarkdownDocument = value; },
|
|
|
|
| 333 |
get releasePdfWorker() { return releasePdfWorker; }, set releasePdfWorker(value) { releasePdfWorker = value; },
|
| 334 |
get renderBookmarks() { return renderBookmarks; }, set renderBookmarks(value) { renderBookmarks = value; },
|
| 335 |
get renderChapterManifest() { return renderChapterManifest; }, set renderChapterManifest(value) { renderChapterManifest = value; },
|
|
|
|
| 336 |
get renderFoliate() { return renderFoliate; }, set renderFoliate(value) { renderFoliate = value; },
|
| 337 |
get renderFullSearchResults() { return renderFullSearchResults; },
|
| 338 |
get renderHtml() { return renderHtml; }, set renderHtml(value) { renderHtml = value; },
|
|
|
|
| 499 |
get loadPdfTaskWithTimeout() { return loadPdfTaskWithTimeout; }, set loadPdfTaskWithTimeout(value) { loadPdfTaskWithTimeout = value; },
|
| 500 |
get loadPdfWithTimeout() { return loadPdfWithTimeout; }, set loadPdfWithTimeout(value) { loadPdfWithTimeout = value; },
|
| 501 |
get makePdfSearchPageLoader() { return makePdfSearchPageLoader; }, set makePdfSearchPageLoader(value) { makePdfSearchPageLoader = value; },
|
|
|
|
|
|
|
| 502 |
get normalizeEpubDocument() { return normalizeEpubDocument; }, set normalizeEpubDocument(value) { normalizeEpubDocument = value; },
|
| 503 |
get notifyReaderUiState() { return notifyReaderUiState; }, set notifyReaderUiState(value) { notifyReaderUiState = value; },
|
| 504 |
get pdfManifestPrefetchConcurrency() { return pdfManifestPrefetchConcurrency; }, set pdfManifestPrefetchConcurrency(value) { pdfManifestPrefetchConcurrency = value; },
|
|
|
|
| 624 |
let {
|
| 625 |
loadScript, fetchWithReaderTimeout, retryableReaderProxyError, retryReaderProxy,
|
| 626 |
fetchReaderUrl, fetchReaderResponse, prepareReaderDocument, readPreparedBytes,
|
| 627 |
+
loadTextDocument, loadMarkdownDocument, loadHtmlDocument,
|
| 628 |
loadMediaDocument, loadImageDocument, loadChapterManifestDocument
|
| 629 |
} = createReaderDocumentLoader(readerContext);
|
| 630 |
|
|
|
|
| 662 |
renderChapterManifest, captureChapterPosition, restoreChapterPosition
|
| 663 |
} = createReaderChapterFormat(readerContext);
|
| 664 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
let {
|
| 666 |
disposeFormatResources, registerReaderFormatAdapters, resolveReaderSource, start,
|
| 667 |
syncCapabilityControls
|
|
|
|
| 689 |
const PDFJS_STANDARD_FONT_URL = "/static/vendor/standard_fonts/";
|
| 690 |
const MARKED_URL = VoiceOfMLReaderResources.vendorUrl("marked", "/static/");
|
| 691 |
const PURIFY_URL = VoiceOfMLReaderResources.vendorUrl("purify", "/static/");
|
|
|
|
|
|
|
| 692 |
const RUFFLE_URL = VoiceOfMLReaderResources.vendors.ruffle.url;
|
| 693 |
const READER_PROXY_TIMEOUT_MS = 120000;
|
| 694 |
const readerRequestManager = VoiceOfMLReaderRequests.createReaderRequestManager();
|
|
|
|
| 795 |
let bookmarkInvoker = null;
|
| 796 |
const bookmarkInertSiblings = new Map();
|
| 797 |
let pdfDocument = null;
|
|
|
|
|
|
|
| 798 |
let pdfPageManifest = null;
|
| 799 |
let pdfOcrManifest = null;
|
| 800 |
let pdfOcrManifestPromise = null;
|
static/reader/core/reader-bindings.mjs
CHANGED
|
@@ -207,10 +207,6 @@ export function createReaderBindings(readerContext) {
|
|
| 207 |
});
|
| 208 |
}
|
| 209 |
|
| 210 |
-
function ownDocxPageNodes() {
|
| 211 |
-
readerContext.trackReaderResource(() => { readerContext.docxPageNodes = []; });
|
| 212 |
-
}
|
| 213 |
-
|
| 214 |
function ownIndependentPdfResources() {
|
| 215 |
readerContext.trackReaderResource(() => {
|
| 216 |
for (const release of [...readerContext.pdfV3BlobReleases]) release();
|
|
@@ -835,7 +831,6 @@ export function createReaderBindings(readerContext) {
|
|
| 835 |
restoreReturnNavigation,
|
| 836 |
validateReturnHistory,
|
| 837 |
ownChapterSearchClient,
|
| 838 |
-
ownDocxPageNodes,
|
| 839 |
ownIndependentPdfResources,
|
| 840 |
ownPdfBookSearchClient,
|
| 841 |
ownPdfPrefetchAndQueues,
|
|
|
|
| 207 |
});
|
| 208 |
}
|
| 209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
function ownIndependentPdfResources() {
|
| 211 |
readerContext.trackReaderResource(() => {
|
| 212 |
for (const release of [...readerContext.pdfV3BlobReleases]) release();
|
|
|
|
| 831 |
restoreReturnNavigation,
|
| 832 |
validateReturnHistory,
|
| 833 |
ownChapterSearchClient,
|
|
|
|
| 834 |
ownIndependentPdfResources,
|
| 835 |
ownPdfBookSearchClient,
|
| 836 |
ownPdfPrefetchAndQueues,
|
static/reader/core/reader-contract.js
CHANGED
|
@@ -128,7 +128,6 @@
|
|
| 128 |
fb2: "foliate",
|
| 129 |
fbz: "foliate",
|
| 130 |
"epub-chapters": "epub-chapters",
|
| 131 |
-
docx: "docx",
|
| 132 |
html: "html",
|
| 133 |
htm: "html",
|
| 134 |
txt: "text",
|
|
@@ -193,7 +192,6 @@
|
|
| 193 |
pagination: false,
|
| 194 |
media: false
|
| 195 |
},
|
| 196 |
-
docx: { toc: true, search: true, zoom: true, bookmarks: true, pagination: true, media: false },
|
| 197 |
html: { toc: true, search: true, zoom: true, bookmarks: true, pagination: false, media: false },
|
| 198 |
text: {
|
| 199 |
toc: false,
|
|
@@ -277,7 +275,7 @@
|
|
| 277 |
const assetVersion = String.raw`(?:[0-9a-f]{16}/)?`;
|
| 278 |
const assetPages = String.raw`(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl))`;
|
| 279 |
const assetOcr = String.raw`(?:ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))`;
|
| 280 |
-
const assetDocument = String.raw`(?:linearized\.pdf|document\.(?:pdf|epub|mobi|azw|azw3|fb2|
|
| 281 |
const assetChapters = String.raw`(?:chapter-manifest\.json|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz))`;
|
| 282 |
const v2ChapterPathPattern = new RegExp(`^chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\\.json|epub-search-index\\.json\\.gz|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*)$`);
|
| 283 |
const ebookBucketPathPattern = new RegExp(`^ebook-chapters/${assetRoot}[a-z0-9-]+/[a-z0-9-]+-epub-chapters-v[0-9]+-bucket/epub-chapters/(?:chapter-manifest\\.json|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*|epub-search-index\\.json\\.gz)$`);
|
|
@@ -289,13 +287,12 @@
|
|
| 289 |
);
|
| 290 |
const bucketPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);
|
| 291 |
const v2ObjectPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);
|
| 292 |
-
const staticBucketPathPattern = new RegExp(`^(?:${assetRoot}(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?(?:document\\.(?:
|
| 293 |
const versionedBucketPathPattern = new RegExp(`^${assetRoot}[0-9a-f]{16}/(?:${assetPages}|${assetOcr})$`);
|
| 294 |
const assetBase = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/";
|
| 295 |
const assetModes = Object.freeze({
|
| 296 |
p: "pdf",
|
| 297 |
e: "epub",
|
| 298 |
-
d: "docx",
|
| 299 |
h: "html",
|
| 300 |
t: "txt",
|
| 301 |
k: "md",
|
|
|
|
| 128 |
fb2: "foliate",
|
| 129 |
fbz: "foliate",
|
| 130 |
"epub-chapters": "epub-chapters",
|
|
|
|
| 131 |
html: "html",
|
| 132 |
htm: "html",
|
| 133 |
txt: "text",
|
|
|
|
| 192 |
pagination: false,
|
| 193 |
media: false
|
| 194 |
},
|
|
|
|
| 195 |
html: { toc: true, search: true, zoom: true, bookmarks: true, pagination: false, media: false },
|
| 196 |
text: {
|
| 197 |
toc: false,
|
|
|
|
| 275 |
const assetVersion = String.raw`(?:[0-9a-f]{16}/)?`;
|
| 276 |
const assetPages = String.raw`(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl))`;
|
| 277 |
const assetOcr = String.raw`(?:ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))`;
|
| 278 |
+
const assetDocument = String.raw`(?:linearized\.pdf|document\.(?:pdf|epub|mobi|azw|azw3|fb2|html|txt|md|webp|swf)|book\.epub|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov))`;
|
| 279 |
const assetChapters = String.raw`(?:chapter-manifest\.json|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz))`;
|
| 280 |
const v2ChapterPathPattern = new RegExp(`^chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\\.json|epub-search-index\\.json\\.gz|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*)$`);
|
| 281 |
const ebookBucketPathPattern = new RegExp(`^ebook-chapters/${assetRoot}[a-z0-9-]+/[a-z0-9-]+-epub-chapters-v[0-9]+-bucket/epub-chapters/(?:chapter-manifest\\.json|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*|epub-search-index\\.json\\.gz)$`);
|
|
|
|
| 287 |
);
|
| 288 |
const bucketPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);
|
| 289 |
const v2ObjectPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);
|
| 290 |
+
const staticBucketPathPattern = new RegExp(`^(?:${assetRoot}(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?(?:document\\.(?:html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|audio\\.(?:mp3|wav|m4a|flac|mpga)|video\\.(?:mp4|mov))|documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/document\\.(?:txt|md|html|pdf|vcf|ini)|media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\\.[a-z0-9]+|video\\.[a-z0-9]+|document\\.swf)|pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/(?:page-manifest\\.json|pages/page-[0-9]{6}\\.webp)|derived/[A-Za-z0-9._-]+/[a-z0-9]{32}/document\\.pdf|chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\\.json|epub-search-index\\.json\\.gz))$`);
|
| 291 |
const versionedBucketPathPattern = new RegExp(`^${assetRoot}[0-9a-f]{16}/(?:${assetPages}|${assetOcr})$`);
|
| 292 |
const assetBase = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/";
|
| 293 |
const assetModes = Object.freeze({
|
| 294 |
p: "pdf",
|
| 295 |
e: "epub",
|
|
|
|
| 296 |
h: "html",
|
| 297 |
t: "txt",
|
| 298 |
k: "md",
|
static/reader/core/reader-document-loader.mjs
CHANGED
|
@@ -111,10 +111,6 @@ export function createReaderDocumentLoader(readerContext) {
|
|
| 111 |
return {response, engine:engines};
|
| 112 |
}
|
| 113 |
|
| 114 |
-
function loadDocxDocument() {
|
| 115 |
-
return readerContext.prepareReaderDocument([readerContext.loadScript(readerContext.JSZIP_URL), readerContext.loadScript(readerContext.DOCX_PREVIEW_URL)]);
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
function loadMediaDocument() {
|
| 119 |
return Promise.resolve(null);
|
| 120 |
}
|
|
@@ -156,7 +152,6 @@ export function createReaderDocumentLoader(readerContext) {
|
|
| 156 |
loadTextDocument,
|
| 157 |
loadMarkdownDocument,
|
| 158 |
loadHtmlDocument,
|
| 159 |
-
loadDocxDocument,
|
| 160 |
loadMediaDocument,
|
| 161 |
loadImageDocument,
|
| 162 |
loadChapterManifestDocument
|
|
|
|
| 111 |
return {response, engine:engines};
|
| 112 |
}
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
function loadMediaDocument() {
|
| 115 |
return Promise.resolve(null);
|
| 116 |
}
|
|
|
|
| 152 |
loadTextDocument,
|
| 153 |
loadMarkdownDocument,
|
| 154 |
loadHtmlDocument,
|
|
|
|
| 155 |
loadMediaDocument,
|
| 156 |
loadImageDocument,
|
| 157 |
loadChapterManifestDocument
|
static/reader/core/reader-source.mjs
CHANGED
|
@@ -165,7 +165,6 @@ export function createReaderSource(readerContext) {
|
|
| 165 |
if (url.protocol !== "https:" || !["huggingface.co", "hf-mirror.com"].includes(url.hostname))
|
| 166 |
return false;
|
| 167 |
const readerAsset = VoiceOfMLReader.isAssetSourcePath(url.pathname);
|
| 168 |
-
if (readerContext.extension === "docx") return readerAsset;
|
| 169 |
return /^\/datasets\/VoiceOfML\/[^/]+\/(resolve|raw)\//.test(url.pathname) || readerAsset;
|
| 170 |
} catch (_) {
|
| 171 |
return false;
|
|
|
|
| 165 |
if (url.protocol !== "https:" || !["huggingface.co", "hf-mirror.com"].includes(url.hostname))
|
| 166 |
return false;
|
| 167 |
const readerAsset = VoiceOfMLReader.isAssetSourcePath(url.pathname);
|
|
|
|
| 168 |
return /^\/datasets\/VoiceOfML\/[^/]+\/(resolve|raw)\//.test(url.pathname) || readerAsset;
|
| 169 |
} catch (_) {
|
| 170 |
return false;
|
static/reader/formats/reader-docx-format.mjs
DELETED
|
@@ -1,129 +0,0 @@
|
|
| 1 |
-
export function createReaderDocxFormat(readerContext) {
|
| 2 |
-
async function renderDocx(prepared) {
|
| 3 |
-
const bytes = await readerContext.readPreparedBytes(prepared.response, prepared.engines);
|
| 4 |
-
readerContext.assertReaderActive();
|
| 5 |
-
VoiceOfMLReaderSecurity.inspectZip(bytes, {
|
| 6 |
-
...VoiceOfMLReaderSecurity.LIMITS,
|
| 7 |
-
archiveCompressedBytes: VoiceOfMLReaderSecurity.LIMITS.documentBytes
|
| 8 |
-
});
|
| 9 |
-
const styles = document.createElement("div");
|
| 10 |
-
styles.className = "docx-styles";
|
| 11 |
-
const body = document.createElement("div");
|
| 12 |
-
body.className = "docx-body";
|
| 13 |
-
readerContext.content.append(styles, body);
|
| 14 |
-
const options = {
|
| 15 |
-
className: "reader-docx",
|
| 16 |
-
inWrapper: true,
|
| 17 |
-
breakPages: true,
|
| 18 |
-
ignoreLastRenderedPageBreak: false,
|
| 19 |
-
useBase64URL: false,
|
| 20 |
-
renderHeaders: true,
|
| 21 |
-
renderFooters: true,
|
| 22 |
-
renderFootnotes: true,
|
| 23 |
-
renderEndnotes: true,
|
| 24 |
-
renderChanges: false,
|
| 25 |
-
renderComments: false,
|
| 26 |
-
renderAltChunks: false,
|
| 27 |
-
debug: false
|
| 28 |
-
};
|
| 29 |
-
const docxDocument = await readerContext.awaitReader(docx.parseAsync(bytes, options));
|
| 30 |
-
readerContext.assertReaderActive();
|
| 31 |
-
const urls = new Set(), urlsByPath = new Map(), contentTypes = docxDocument.contentTypes || [];
|
| 32 |
-
let released = false;
|
| 33 |
-
const release = () => {
|
| 34 |
-
released = true;
|
| 35 |
-
for (const url of urls) URL.revokeObjectURL(url);
|
| 36 |
-
urls.clear();
|
| 37 |
-
urlsByPath.clear();
|
| 38 |
-
};
|
| 39 |
-
const untrack = readerContext.trackReaderResource(release);
|
| 40 |
-
readerContext.memoizeDocxAssets(docxDocument, () => released);
|
| 41 |
-
// Own this parsed document's images, fonts and numbering assets only.
|
| 42 |
-
docxDocument.blobToURL = (blob, path) => {
|
| 43 |
-
if (released || !blob) return null;
|
| 44 |
-
if (path && urlsByPath.has(path)) return urlsByPath.get(path);
|
| 45 |
-
const type = path && contentTypes.find(entry => entry.partName === path ||
|
| 46 |
-
(entry.extension && path.endsWith(`.${entry.extension}`)));
|
| 47 |
-
const url = URL.createObjectURL(type ? new Blob([blob], {type:type.contentType}) : blob);
|
| 48 |
-
if (typeof url === "string" && url.startsWith("blob:")) {
|
| 49 |
-
urls.add(url);
|
| 50 |
-
if (path) urlsByPath.set(path, url);
|
| 51 |
-
}
|
| 52 |
-
return url;
|
| 53 |
-
};
|
| 54 |
-
try {
|
| 55 |
-
const nodes = await readerContext.awaitReader(docx.renderDocument(docxDocument, options));
|
| 56 |
-
readerContext.assertReaderActive();
|
| 57 |
-
for (const node of nodes) (node.nodeName === "STYLE" ? styles : body).appendChild(node);
|
| 58 |
-
} catch (error) {
|
| 59 |
-
release();
|
| 60 |
-
untrack();
|
| 61 |
-
throw error;
|
| 62 |
-
}
|
| 63 |
-
readerContext.assertReaderActive();
|
| 64 |
-
body.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark");
|
| 65 |
-
if (!(body.textContent || "").trim() && !body.querySelector("img, table, svg, canvas")) {
|
| 66 |
-
release();
|
| 67 |
-
untrack();
|
| 68 |
-
throw new Error("DOCX rendered no supported content");
|
| 69 |
-
}
|
| 70 |
-
const pages = [...body.querySelectorAll(":scope > .reader-docx-wrapper > section.reader-docx")];
|
| 71 |
-
readerContext.docxPageNodes = pages;
|
| 72 |
-
if (pages.length) {
|
| 73 |
-
readerContext.updateDocumentState({ pageCount: pages.length });
|
| 74 |
-
readerContext.pageInput.max = String(readerContext.documentState.pageCount);
|
| 75 |
-
document.querySelector("#page-total").textContent = `/ ${readerContext.documentState.pageCount}`;
|
| 76 |
-
document.querySelector(".page-controls").hidden = false;
|
| 77 |
-
pages.forEach((page, index) => {
|
| 78 |
-
page.classList.add("reader-docx-page");
|
| 79 |
-
page.dataset.page = String(index + 1);
|
| 80 |
-
page.style.setProperty("--reader-docx-height", page.style.minHeight || page.style.height || "1123px");
|
| 81 |
-
});
|
| 82 |
-
readerContext.setToc(readerContext.headingTocEntries(body));
|
| 83 |
-
}
|
| 84 |
-
for (const link of body.querySelectorAll("a[href]")) {
|
| 85 |
-
const href = link.getAttribute("href") || "";
|
| 86 |
-
if (!href.startsWith("#") && !/^https?:\/\//i.test(href)) link.removeAttribute("href");
|
| 87 |
-
else if (!href.startsWith("#")) {
|
| 88 |
-
link.target = "_blank";
|
| 89 |
-
link.rel = "noopener noreferrer";
|
| 90 |
-
}
|
| 91 |
-
}
|
| 92 |
-
readerContext.markReaderContentReady();
|
| 93 |
-
readerContext.status.textContent = readerContext.documentState.pageCount ? `${readerContext.documentState.pageCount} 页` : "DOCX";
|
| 94 |
-
}
|
| 95 |
-
|
| 96 |
-
function memoizeDocxResource(load, keyFor, isReleased) {
|
| 97 |
-
const pending = new Map();
|
| 98 |
-
return (...args) => {
|
| 99 |
-
if (isReleased()) return Promise.resolve(null);
|
| 100 |
-
const key = keyFor(...args);
|
| 101 |
-
if (!key) return load(...args);
|
| 102 |
-
if (!pending.has(key)) {
|
| 103 |
-
const task = Promise.resolve().then(() => isReleased() ? null : load(...args));
|
| 104 |
-
pending.set(key, task);
|
| 105 |
-
task.catch(() => { if (pending.get(key) === task) pending.delete(key); });
|
| 106 |
-
}
|
| 107 |
-
return pending.get(key);
|
| 108 |
-
};
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
function memoizeDocxAssets(doc, isReleased) {
|
| 112 |
-
if (typeof doc.getPathById !== "function") return;
|
| 113 |
-
for (const [name, part] of [["loadDocumentImage", "documentPart"],
|
| 114 |
-
["loadNumberingImage", "numberingPart"], ["loadFont", "fontTablePart"]]) {
|
| 115 |
-
if (typeof doc[name] !== "function") continue;
|
| 116 |
-
const original = doc[name].bind(doc);
|
| 117 |
-
doc[name] = readerContext.memoizeDocxResource(original, (id, parameter) => {
|
| 118 |
-
const path = doc.getPathById(name === "loadDocumentImage" ? parameter || doc[part] : doc[part], id);
|
| 119 |
-
return path ? (name === "loadFont" ? `${path}\u0000${parameter}` : path) : null;
|
| 120 |
-
}, isReleased);
|
| 121 |
-
}
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
return {
|
| 125 |
-
renderDocx,
|
| 126 |
-
memoizeDocxResource,
|
| 127 |
-
memoizeDocxAssets
|
| 128 |
-
};
|
| 129 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
static/reader/formats/reader-format-controller.mjs
CHANGED
|
@@ -83,7 +83,6 @@ export function createReaderFormatController(readerContext) {
|
|
| 83 |
markdown: [readerContext.loadMarkdownDocument, readerContext.renderMarkdownDocument],
|
| 84 |
html: [readerContext.loadHtmlDocument, readerContext.renderHtml],
|
| 85 |
"epub-chapters": [readerContext.loadChapterManifestDocument, readerContext.renderChapterManifest],
|
| 86 |
-
docx: [readerContext.loadDocxDocument, readerContext.renderDocx],
|
| 87 |
audio: [readerContext.loadMediaDocument, () => readerContext.renderMedia("audio")],
|
| 88 |
video: [readerContext.loadMediaDocument, () => readerContext.renderMedia("video")],
|
| 89 |
swf: [readerContext.loadSwfDocument, readerContext.renderSwf],
|
|
|
|
| 83 |
markdown: [readerContext.loadMarkdownDocument, readerContext.renderMarkdownDocument],
|
| 84 |
html: [readerContext.loadHtmlDocument, readerContext.renderHtml],
|
| 85 |
"epub-chapters": [readerContext.loadChapterManifestDocument, readerContext.renderChapterManifest],
|
|
|
|
| 86 |
audio: [readerContext.loadMediaDocument, () => readerContext.renderMedia("audio")],
|
| 87 |
video: [readerContext.loadMediaDocument, () => readerContext.renderMedia("video")],
|
| 88 |
swf: [readerContext.loadSwfDocument, readerContext.renderSwf],
|
static/reader/reader-components.mjs
CHANGED
|
@@ -17,7 +17,6 @@ export { createReaderHtmlFormat } from "./formats/reader-html-format.mjs";
|
|
| 17 |
export { createReaderPdfRenderer } from "./pdf/reader-pdf-renderer.mjs";
|
| 18 |
export { createReaderTextFormat } from "./formats/reader-text-format.mjs";
|
| 19 |
export { createReaderChapterFormat } from "./formats/reader-chapter-format.mjs";
|
| 20 |
-
export { createReaderDocxFormat } from "./formats/reader-docx-format.mjs";
|
| 21 |
export { createReaderFormatController } from "./formats/reader-format-controller.mjs";
|
| 22 |
export { createReaderPdfEngine } from "./pdf/reader-pdf-engine.mjs";
|
| 23 |
export { createReaderPdfSearch } from "./pdf/reader-pdf-search.mjs";
|
|
|
|
| 17 |
export { createReaderPdfRenderer } from "./pdf/reader-pdf-renderer.mjs";
|
| 18 |
export { createReaderTextFormat } from "./formats/reader-text-format.mjs";
|
| 19 |
export { createReaderChapterFormat } from "./formats/reader-chapter-format.mjs";
|
|
|
|
| 20 |
export { createReaderFormatController } from "./formats/reader-format-controller.mjs";
|
| 21 |
export { createReaderPdfEngine } from "./pdf/reader-pdf-engine.mjs";
|
| 22 |
export { createReaderPdfSearch } from "./pdf/reader-pdf-search.mjs";
|
static/reader/search/reader-search-backends.mjs
CHANGED
|
@@ -228,7 +228,7 @@ export function createReaderSearchBackends(readerContext) {
|
|
| 228 |
else if (readerContext.capability.mode === "foliate")
|
| 229 |
readerContext.publishSearchResults(generation, await readerContext.fullSearchFoliateMatches(query, generation));
|
| 230 |
else if (readerContext.capability.mode === "epub-chapters") await readerContext.searchChapterBook(query, generation);
|
| 231 |
-
else if (["text", "markdown"
|
| 232 |
readerContext.publishSearchResults(
|
| 233 |
generation,
|
| 234 |
await readerContext.fullSearchDomMatches(readerContext.content, "阅读位置", query, generation, true)
|
|
|
|
| 228 |
else if (readerContext.capability.mode === "foliate")
|
| 229 |
readerContext.publishSearchResults(generation, await readerContext.fullSearchFoliateMatches(query, generation));
|
| 230 |
else if (readerContext.capability.mode === "epub-chapters") await readerContext.searchChapterBook(query, generation);
|
| 231 |
+
else if (["text", "markdown"].includes(readerContext.capability.mode))
|
| 232 |
readerContext.publishSearchResults(
|
| 233 |
generation,
|
| 234 |
await readerContext.fullSearchDomMatches(readerContext.content, "阅读位置", query, generation, true)
|
static/reader/ui/reader-navigation.mjs
CHANGED
|
@@ -71,7 +71,7 @@ export function createReaderNavigation(readerContext) {
|
|
| 71 |
const page = VoiceOfMLReader.clampNumber(value, 1, readerContext.documentState.pageCount, 1);
|
| 72 |
readerContext.pdfShellWindow?.ensure(page);
|
| 73 |
let shell = readerContext.content.querySelector(
|
| 74 |
-
`.reader-page[data-page="${page}"]
|
| 75 |
);
|
| 76 |
if (!shell && ["pdf-pages", "image-pages"].includes(readerContext.capability.mode)) {
|
| 77 |
await readerContext.pdfShellsReady;
|
|
|
|
| 71 |
const page = VoiceOfMLReader.clampNumber(value, 1, readerContext.documentState.pageCount, 1);
|
| 72 |
readerContext.pdfShellWindow?.ensure(page);
|
| 73 |
let shell = readerContext.content.querySelector(
|
| 74 |
+
`.reader-page[data-page="${page}"]`
|
| 75 |
);
|
| 76 |
if (!shell && ["pdf-pages", "image-pages"].includes(readerContext.capability.mode)) {
|
| 77 |
await readerContext.pdfShellsReady;
|
static/reader/ui/reader-progress.mjs
CHANGED
|
@@ -27,7 +27,7 @@ export function createReaderProgress(readerContext) {
|
|
| 27 |
readerContext.syncCurrentPageFromMarker();
|
| 28 |
const shell = readerContext.documentState.pageCount
|
| 29 |
? readerContext.content.querySelector(
|
| 30 |
-
`.reader-page[data-page="${readerContext.documentState.page}"]
|
| 31 |
)
|
| 32 |
: null;
|
| 33 |
const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0;
|
|
@@ -175,7 +175,7 @@ export function createReaderProgress(readerContext) {
|
|
| 175 |
|
| 176 |
function pageAtMarker() {
|
| 177 |
const y = readerContext.bookmarkRibbon.getBoundingClientRect().bottom,
|
| 178 |
-
pages =
|
| 179 |
if (!pages.length) return null;
|
| 180 |
const end = readerContext.viewport.scrollHeight - readerContext.viewport.clientHeight;
|
| 181 |
if (["pdf", "pdf-pages"].includes(readerContext.capability.mode) && end > 2 && readerContext.viewport.scrollTop > 0 &&
|
|
@@ -233,7 +233,7 @@ export function createReaderProgress(readerContext) {
|
|
| 233 |
)
|
| 234 |
return false;
|
| 235 |
const shell = readerContext.content.querySelector(
|
| 236 |
-
`.reader-page[data-page="${readerContext.documentState.page}"]
|
| 237 |
);
|
| 238 |
if (shell && Number.isFinite(entry.pageOffset))
|
| 239 |
readerContext.viewport.scrollTop = readerContext.readerPageScrollTop(shell) + entry.pageOffset;
|
|
|
|
| 27 |
readerContext.syncCurrentPageFromMarker();
|
| 28 |
const shell = readerContext.documentState.pageCount
|
| 29 |
? readerContext.content.querySelector(
|
| 30 |
+
`.reader-page[data-page="${readerContext.documentState.page}"]`
|
| 31 |
)
|
| 32 |
: null;
|
| 33 |
const pageOffset = shell ? Math.max(0, readerContext.viewport.scrollTop - readerContext.readerPageScrollTop(shell)) : 0;
|
|
|
|
| 175 |
|
| 176 |
function pageAtMarker() {
|
| 177 |
const y = readerContext.bookmarkRibbon.getBoundingClientRect().bottom,
|
| 178 |
+
pages = [...readerContext.content.querySelectorAll(".reader-page")];
|
| 179 |
if (!pages.length) return null;
|
| 180 |
const end = readerContext.viewport.scrollHeight - readerContext.viewport.clientHeight;
|
| 181 |
if (["pdf", "pdf-pages"].includes(readerContext.capability.mode) && end > 2 && readerContext.viewport.scrollTop > 0 &&
|
|
|
|
| 233 |
)
|
| 234 |
return false;
|
| 235 |
const shell = readerContext.content.querySelector(
|
| 236 |
+
`.reader-page[data-page="${readerContext.documentState.page}"]`
|
| 237 |
);
|
| 238 |
if (shell && Number.isFinite(entry.pageOffset))
|
| 239 |
readerContext.viewport.scrollTop = readerContext.readerPageScrollTop(shell) + entry.pageOffset;
|
static/reader/ui/reader-ui.mjs
CHANGED
|
@@ -47,8 +47,6 @@ export function createReaderUi(readerContext) {
|
|
| 47 |
readerContext.readerThemeToggle.title = readerContext.readerTheme === "dark" ? "切换到白天模式" : "切换到夜间模式";
|
| 48 |
readerContext.readerThemeToggle.setAttribute("aria-label", readerContext.readerThemeToggle.title);
|
| 49 |
readerContext.readerThemeToggle.setAttribute("aria-pressed", String(readerContext.readerTheme === "light"));
|
| 50 |
-
const docxBody = readerContext.content.querySelector(".docx-body");
|
| 51 |
-
if (docxBody) docxBody.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark");
|
| 52 |
for (const article of readerContext.content.querySelectorAll(".foliate-continuous > article"))
|
| 53 |
article.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark");
|
| 54 |
if (persist) localStorage.setItem("theme", readerContext.readerTheme);
|
|
|
|
| 47 |
readerContext.readerThemeToggle.title = readerContext.readerTheme === "dark" ? "切换到白天模式" : "切换到夜间模式";
|
| 48 |
readerContext.readerThemeToggle.setAttribute("aria-label", readerContext.readerThemeToggle.title);
|
| 49 |
readerContext.readerThemeToggle.setAttribute("aria-pressed", String(readerContext.readerTheme === "light"));
|
|
|
|
|
|
|
| 50 |
for (const article of readerContext.content.querySelectorAll(".foliate-continuous > article"))
|
| 51 |
article.classList.toggle("reader-document-dark", readerContext.readerTheme === "dark");
|
| 52 |
if (persist) localStorage.setItem("theme", readerContext.readerTheme);
|
tests/test_reader_architecture.js
CHANGED
|
@@ -124,7 +124,7 @@ assert.doesNotMatch(reader, /Promise\.all\(\[loadReaderRestoration\(\)/)
|
|
| 124 |
assert.strictEqual((reader.match(/function loadPdfDocument\(/g) || []).length, 1)
|
| 125 |
for (const renderer of ['renderImageDocument', 'renderMedia']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\s*\\(`,'g')) || []).length, 1)
|
| 126 |
for (const renderer of ['renderTextDocument', 'renderMarkdownDocument']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\(`,'g')) || []).length, 1)
|
| 127 |
-
for (const loader of ['loadTextDocument', 'loadMarkdownDocument', 'loadHtmlDocument'
|
| 128 |
for (const loader of ['loadMediaDocument', 'loadImageDocument', 'loadChapterManifestDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
| 129 |
assert.doesNotMatch(reader, /loadFoliateDocument/)
|
| 130 |
assert.match(reader, /reader-chapter-repository\.js/)
|
|
@@ -203,7 +203,7 @@ const expected = {
|
|
| 203 |
pdf: ['loadPdfDocument', 'renderPdf'], image: ['loadImageDocument', 'renderImageDocument'],
|
| 204 |
text: ['loadTextDocument', 'renderTextDocument'], markdown: ['loadMarkdownDocument', 'renderMarkdownDocument'],
|
| 205 |
html: ['loadHtmlDocument', 'renderHtml'], 'epub-chapters': ['loadChapterManifestDocument', 'renderChapterManifest'],
|
| 206 |
-
|
| 207 |
swf: ['loadSwfDocument', 'renderSwf'],
|
| 208 |
}
|
| 209 |
const registered = new Map(), calls = []
|
|
|
|
| 124 |
assert.strictEqual((reader.match(/function loadPdfDocument\(/g) || []).length, 1)
|
| 125 |
for (const renderer of ['renderImageDocument', 'renderMedia']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\s*\\(`,'g')) || []).length, 1)
|
| 126 |
for (const renderer of ['renderTextDocument', 'renderMarkdownDocument']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\(`,'g')) || []).length, 1)
|
| 127 |
+
for (const loader of ['loadTextDocument', 'loadMarkdownDocument', 'loadHtmlDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
| 128 |
for (const loader of ['loadMediaDocument', 'loadImageDocument', 'loadChapterManifestDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
| 129 |
assert.doesNotMatch(reader, /loadFoliateDocument/)
|
| 130 |
assert.match(reader, /reader-chapter-repository\.js/)
|
|
|
|
| 203 |
pdf: ['loadPdfDocument', 'renderPdf'], image: ['loadImageDocument', 'renderImageDocument'],
|
| 204 |
text: ['loadTextDocument', 'renderTextDocument'], markdown: ['loadMarkdownDocument', 'renderMarkdownDocument'],
|
| 205 |
html: ['loadHtmlDocument', 'renderHtml'], 'epub-chapters': ['loadChapterManifestDocument', 'renderChapterManifest'],
|
| 206 |
+
foliate: ['loadMediaDocument', 'renderFoliate'],
|
| 207 |
swf: ['loadSwfDocument', 'renderSwf'],
|
| 208 |
}
|
| 209 |
const registered = new Map(), calls = []
|
tests/test_reader_format_pipeline.py
CHANGED
|
@@ -3,7 +3,7 @@ import unittest
|
|
| 3 |
from urllib.parse import urlencode
|
| 4 |
|
| 5 |
from tests import test_reader_pdf_followup as support
|
| 6 |
-
from tests.test_reader_performance import
|
| 7 |
|
| 8 |
|
| 9 |
class ReaderFormatPipelineTests(unittest.TestCase):
|
|
@@ -25,11 +25,9 @@ class ReaderFormatPipelineTests(unittest.TestCase):
|
|
| 25 |
engines={
|
| 26 |
'marked':'window.marked={parse:t=>"<h1>Heading</h1><p>"+t+"</p>"};',
|
| 27 |
'purify':'window.DOMPurify={sanitize:t=>t};',
|
| 28 |
-
'jszip':'window.JSZip=function(){};',
|
| 29 |
-
'docx-preview':'window.docx={parseAsync:async()=>({blobToURL:()=>null}),renderDocument:async()=>{const n=document.createElement("p");n.textContent="Document body";return [n];}};'
|
| 30 |
}
|
| 31 |
documents=[('md',b'Markdown body','text/plain'),('html',b'<h1>Heading</h1><p>HTML body</p>','text/html'),
|
| 32 |
-
('
|
| 33 |
for ext,body,mime in documents:
|
| 34 |
with self.subTest(format=ext):
|
| 35 |
held=[]
|
|
@@ -38,8 +36,7 @@ class ReaderFormatPipelineTests(unittest.TestCase):
|
|
| 38 |
self.page.route(pattern,engine)
|
| 39 |
self.page.route('**/api/reader-content**',lambda route,_request,body=body,mime=mime:route.fulfill(
|
| 40 |
content_type=mime,body=body,headers={'Access-Control-Allow-Origin':'*'}))
|
| 41 |
-
url=
|
| 42 |
-
if ext=='docx' else f'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/pipeline.{ext}')
|
| 43 |
self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url=url,ext=ext)),wait_until='domcontentloaded')
|
| 44 |
self.page.wait_for_function('()=>window.__bodyReads>1',timeout=1500)
|
| 45 |
self.assertTrue(held)
|
|
|
|
| 3 |
from urllib.parse import urlencode
|
| 4 |
|
| 5 |
from tests import test_reader_pdf_followup as support
|
| 6 |
+
from tests.test_reader_performance import epub_with_navigation
|
| 7 |
|
| 8 |
|
| 9 |
class ReaderFormatPipelineTests(unittest.TestCase):
|
|
|
|
| 25 |
engines={
|
| 26 |
'marked':'window.marked={parse:t=>"<h1>Heading</h1><p>"+t+"</p>"};',
|
| 27 |
'purify':'window.DOMPurify={sanitize:t=>t};',
|
|
|
|
|
|
|
| 28 |
}
|
| 29 |
documents=[('md',b'Markdown body','text/plain'),('html',b'<h1>Heading</h1><p>HTML body</p>','text/html'),
|
| 30 |
+
('epub',epub_with_navigation(),'application/epub+zip')]
|
| 31 |
for ext,body,mime in documents:
|
| 32 |
with self.subTest(format=ext):
|
| 33 |
held=[]
|
|
|
|
| 36 |
self.page.route(pattern,engine)
|
| 37 |
self.page.route('**/api/reader-content**',lambda route,_request,body=body,mime=mime:route.fulfill(
|
| 38 |
content_type=mime,body=body,headers={'Access-Control-Allow-Origin':'*'}))
|
| 39 |
+
url=f'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/pipeline.{ext}'
|
|
|
|
| 40 |
self.page.goto(self.origin+support.PREFIX+'/static/reader.html?'+urlencode(dict(url=url,ext=ext)),wait_until='domcontentloaded')
|
| 41 |
self.page.wait_for_function('()=>window.__bodyReads>1',timeout=1500)
|
| 42 |
self.assertTrue(held)
|
tests/test_reader_live_formats.py
CHANGED
|
@@ -28,7 +28,6 @@ SAMPLES = ()
|
|
| 28 |
("video", f"{ASSET_ROOT}/objects/9b/9bd4e16a28936dbf9f0bf9dbcdb09b0dc9889743c5f314c0720019175181ca91/ffmpeg-video-mp4-h264-aac-v1/video.mp4", "mp4", "video", False),
|
| 29 |
("fb2", f"{ASSET_ROOT}/objects/79/794a61d8a31327c495e56313bdf19895b94885e9fcd2e2b8bd5f9fc5057b8608/foliate-original-v1/document.fb2", "fb2", "foliate", True),
|
| 30 |
("fb2-cn", f"{ASSET_ROOT}/objects/ab/ab658eeefdcfedf881cc93cff87d10a06d902af497328315460875038c769381/foliate-original-v1/document.fb2", "fb2", "foliate", True),
|
| 31 |
-
("docx", f"{ASSET_ROOT}/objects/37/3795cbd583cbb49d3cef6e4518e7cde21b2de9295f8387327f10e44de3fa8a24/docx-native-v2/document.docx", "docx", "docx", False),
|
| 32 |
("html", f"{ASSET_ROOT}/objects/23/23e3eb7e0d93e496ce57e6c0a44d977a42b91991409b516b087e6a79b10bb4a7/sanitized-html-v5-e2f98d3c6dd02d16/document.html", "html", "html", True),
|
| 33 |
)
|
| 34 |
"""
|
|
@@ -54,8 +53,6 @@ def _reader_extension_for_sample(name, item):
|
|
| 54 |
return "pdf"
|
| 55 |
if name in {"epub", "mobi", "azw3", "fb2"} and source_extension == name and reader_mode == "foliate":
|
| 56 |
return name
|
| 57 |
-
if name == "docx" and source_extension in {"doc", "docx"} and reader_mode == "docx":
|
| 58 |
-
return "docx"
|
| 59 |
if name == "html" and source_extension in {"html", "htm"} and reader_mode == "html":
|
| 60 |
return "html"
|
| 61 |
if name in {"audio", "video"} and reader_mode == name:
|
|
@@ -74,8 +71,6 @@ class ReaderSampleMappingTests(unittest.TestCase):
|
|
| 74 |
("mobi", {"source_extension": "mobi", "reader_mode": "foliate"}, "mobi"),
|
| 75 |
("azw3", {"source_extension": "AZW3", "reader_mode": "foliate"}, "azw3"),
|
| 76 |
("fb2", {"source_extension": "fb2", "reader_mode": "foliate"}, "fb2"),
|
| 77 |
-
("docx", {"source_extension": "DOC", "reader_mode": "docx"}, "docx"),
|
| 78 |
-
("docx", {"source_extension": "docx", "reader_mode": "docx"}, "docx"),
|
| 79 |
("html", {"source_extension": "HTM", "reader_mode": "html"}, "html"),
|
| 80 |
("audio", {"source_extension": "amr", "reader_mode": "audio"}, "audio"),
|
| 81 |
("video", {"source_extension": "flv", "reader_mode": "video"}, "video"),
|
|
@@ -143,7 +138,7 @@ def _select_samples():
|
|
| 143 |
print("Reader-Assets revision:", revision)
|
| 144 |
root = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main"
|
| 145 |
ready = [v for v in manifest.get("files", {}).values() if v.get("status") == "ready" and v.get("path") and v.get("sha256")]
|
| 146 |
-
wanted = {"pdf": ("pdf",), "epub": ("epub",), "mobi": ("mobi",), "azw3": ("azw3",), "fb2": ("fb2",), "
|
| 147 |
selected = {}
|
| 148 |
for name, extensions in wanted.items():
|
| 149 |
candidates = [v for v in ready if v.get("source_extension", "").lower() in extensions]
|
|
@@ -178,7 +173,7 @@ def _select_samples():
|
|
| 178 |
raw_skips[name] = f"raw API selector failed: {error}"
|
| 179 |
for name, reason in raw_skips.items():
|
| 180 |
print(f"Raw {name} sample skipped: {reason}")
|
| 181 |
-
order = ("pdf", "pdf-pages", "epub", "mobi", "azw3", "audio", "video", "fb2", "
|
| 182 |
return tuple(selected[name] for name in order if name in selected), revision, raw_skips
|
| 183 |
|
| 184 |
|
|
@@ -237,8 +232,6 @@ class ReaderLiveFormatTests(unittest.TestCase):
|
|
| 237 |
self.assertGreater(article.evaluate("node => (node.shadowRoot || node).textContent.trim().length"), 0, name)
|
| 238 |
elif mode == "html":
|
| 239 |
self.assertGreater(len(page.frame_locator(".html-frame").locator("body").inner_text(timeout=120000).strip()), 0, name)
|
| 240 |
-
elif mode == "docx":
|
| 241 |
-
self.assertGreater(len(page.locator("#content").inner_text().strip()), 0, name)
|
| 242 |
elif mode in {"text", "markdown"}:
|
| 243 |
selector = ".reader-text" if mode == "text" else ".reader-markdown"
|
| 244 |
content = page.locator(selector)
|
|
|
|
| 28 |
("video", f"{ASSET_ROOT}/objects/9b/9bd4e16a28936dbf9f0bf9dbcdb09b0dc9889743c5f314c0720019175181ca91/ffmpeg-video-mp4-h264-aac-v1/video.mp4", "mp4", "video", False),
|
| 29 |
("fb2", f"{ASSET_ROOT}/objects/79/794a61d8a31327c495e56313bdf19895b94885e9fcd2e2b8bd5f9fc5057b8608/foliate-original-v1/document.fb2", "fb2", "foliate", True),
|
| 30 |
("fb2-cn", f"{ASSET_ROOT}/objects/ab/ab658eeefdcfedf881cc93cff87d10a06d902af497328315460875038c769381/foliate-original-v1/document.fb2", "fb2", "foliate", True),
|
|
|
|
| 31 |
("html", f"{ASSET_ROOT}/objects/23/23e3eb7e0d93e496ce57e6c0a44d977a42b91991409b516b087e6a79b10bb4a7/sanitized-html-v5-e2f98d3c6dd02d16/document.html", "html", "html", True),
|
| 32 |
)
|
| 33 |
"""
|
|
|
|
| 53 |
return "pdf"
|
| 54 |
if name in {"epub", "mobi", "azw3", "fb2"} and source_extension == name and reader_mode == "foliate":
|
| 55 |
return name
|
|
|
|
|
|
|
| 56 |
if name == "html" and source_extension in {"html", "htm"} and reader_mode == "html":
|
| 57 |
return "html"
|
| 58 |
if name in {"audio", "video"} and reader_mode == name:
|
|
|
|
| 71 |
("mobi", {"source_extension": "mobi", "reader_mode": "foliate"}, "mobi"),
|
| 72 |
("azw3", {"source_extension": "AZW3", "reader_mode": "foliate"}, "azw3"),
|
| 73 |
("fb2", {"source_extension": "fb2", "reader_mode": "foliate"}, "fb2"),
|
|
|
|
|
|
|
| 74 |
("html", {"source_extension": "HTM", "reader_mode": "html"}, "html"),
|
| 75 |
("audio", {"source_extension": "amr", "reader_mode": "audio"}, "audio"),
|
| 76 |
("video", {"source_extension": "flv", "reader_mode": "video"}, "video"),
|
|
|
|
| 138 |
print("Reader-Assets revision:", revision)
|
| 139 |
root = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main"
|
| 140 |
ready = [v for v in manifest.get("files", {}).values() if v.get("status") == "ready" and v.get("path") and v.get("sha256")]
|
| 141 |
+
wanted = {"pdf": ("pdf",), "epub": ("epub",), "mobi": ("mobi",), "azw3": ("azw3",), "fb2": ("fb2",), "html": ("html", "htm")}
|
| 142 |
selected = {}
|
| 143 |
for name, extensions in wanted.items():
|
| 144 |
candidates = [v for v in ready if v.get("source_extension", "").lower() in extensions]
|
|
|
|
| 173 |
raw_skips[name] = f"raw API selector failed: {error}"
|
| 174 |
for name, reason in raw_skips.items():
|
| 175 |
print(f"Raw {name} sample skipped: {reason}")
|
| 176 |
+
order = ("pdf", "pdf-pages", "epub", "mobi", "azw3", "audio", "video", "fb2", "html", "txt", "md")
|
| 177 |
return tuple(selected[name] for name in order if name in selected), revision, raw_skips
|
| 178 |
|
| 179 |
|
|
|
|
| 232 |
self.assertGreater(article.evaluate("node => (node.shadowRoot || node).textContent.trim().length"), 0, name)
|
| 233 |
elif mode == "html":
|
| 234 |
self.assertGreater(len(page.frame_locator(".html-frame").locator("body").inner_text(timeout=120000).strip()), 0, name)
|
|
|
|
|
|
|
| 235 |
elif mode in {"text", "markdown"}:
|
| 236 |
selector = ".reader-text" if mode == "text" else ".reader-markdown"
|
| 237 |
content = page.locator(selector)
|
tests/test_reader_optimizations.py
CHANGED
|
@@ -2,11 +2,9 @@
|
|
| 2 |
|
| 3 |
import gzip
|
| 4 |
import hashlib
|
| 5 |
-
import io
|
| 6 |
import json
|
| 7 |
import unittest
|
| 8 |
import urllib.parse
|
| 9 |
-
import zipfile
|
| 10 |
|
| 11 |
from tests import test_reader_refactor as fixtures
|
| 12 |
|
|
@@ -204,37 +202,6 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 204 |
self.assertEqual(self.page.evaluate('__pdfProbeTotal()'), 123)
|
| 205 |
self.assertEqual(self.page.evaluate('__extraction.calls'), [1, 2])
|
| 206 |
|
| 207 |
-
def test_large_docx_skips_offscreen_paint_but_searches_all_pages(self):
|
| 208 |
-
self.expose()
|
| 209 |
-
with zipfile.ZipFile(io.BytesIO(fixtures.support.minimal_docx())) as archive:
|
| 210 |
-
files = {name: archive.read(name) for name in archive.namelist()}
|
| 211 |
-
paragraphs = ''.join(f'<w:p><w:r><w:t>needle page {page}</w:t></w:r></w:p>' +
|
| 212 |
-
('<w:p><w:r><w:br w:type="page"/></w:r></w:p>' if page < 20 else '')
|
| 213 |
-
for page in range(1, 21))
|
| 214 |
-
files['word/document.xml'] = ('<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>' + paragraphs + '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/></w:sectPr></w:body></w:document>')
|
| 215 |
-
self.serve(fixtures.support.zip_bytes(files), 'application/octet-stream')
|
| 216 |
-
self.open(self.docx_url())
|
| 217 |
-
pages = self.page.locator('.reader-docx-page')
|
| 218 |
-
self.assertEqual(pages.count(), 20)
|
| 219 |
-
marker = self.page.evaluate('''()=>{let reads=0;const pages=[...document.querySelectorAll('.reader-docx-page')];
|
| 220 |
-
for(const page of pages){const native=page.getBoundingClientRect.bind(page);page.getBoundingClientRect=()=>{reads++;return native();};}
|
| 221 |
-
const actual=__markerPage();return {actual,reads};}''')
|
| 222 |
-
self.assertEqual(marker['actual'],'1')
|
| 223 |
-
self.assertLessEqual(marker['reads'],6)
|
| 224 |
-
self.assertEqual(pages.last.evaluate('e => getComputedStyle(e).contentVisibility'), 'auto')
|
| 225 |
-
self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')
|
| 226 |
-
self.assertFalse(pages.last.evaluate('e => e.firstElementChild.checkVisibility({contentVisibilityAuto:true})'))
|
| 227 |
-
self.assertEqual(self.page.evaluate('__query("needle")'), 20)
|
| 228 |
-
self.search('needle')
|
| 229 |
-
self.page.locator('.full-search-result').last.click()
|
| 230 |
-
self.page.wait_for_function('() => document.querySelector(".reader-docx-page:last-child mark")')
|
| 231 |
-
self.assertEqual(pages.last.locator('mark').text_content(), 'needle')
|
| 232 |
-
self.page.locator('#history').click()
|
| 233 |
-
self.page.locator('#page-number').fill('1')
|
| 234 |
-
self.page.locator('#page-number').press('Enter')
|
| 235 |
-
self.page.wait_for_function('() => document.querySelector("#page-number").value === "1"')
|
| 236 |
-
self.assertEqual(self.page.evaluate('__query("needle")'), 20)
|
| 237 |
-
|
| 238 |
def test_mobile_pdf_search_keeps_one_demand_slot_and_drops_queued_cancelled_work(self):
|
| 239 |
self.expose()
|
| 240 |
self.serve('mobile scheduling fixture')
|
|
@@ -352,91 +319,17 @@ class ReaderOptimizationTests(unittest.TestCase):
|
|
| 352 |
self.assertEqual(self.page.locator('mark.full-search-highlight').text_content(), 'needle')
|
| 353 |
self.assertGreater(sum(url.endswith('chapter-1.xhtml') for url in requested), 1)
|
| 354 |
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
def image_docx(self, image=None, repeats=3, font=None):
|
| 359 |
-
support = fixtures.support
|
| 360 |
-
with zipfile.ZipFile(io.BytesIO(support.minimal_docx())) as archive:
|
| 361 |
-
files = {name: archive.read(name) for name in archive.namelist()}
|
| 362 |
-
files['[Content_Types].xml'] = files['[Content_Types].xml'].decode().replace('</Types>', '<Default Extension="png" ContentType="image/png"/></Types>')
|
| 363 |
-
files['word/_rels/document.xml.rels'] = '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image.png"/></Relationships>'
|
| 364 |
-
files['word/media/image.png'] = image if image is not None else support.PNG_BYTES
|
| 365 |
-
drawing = '''<w:p><w:r><w:drawing><wp:inline xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"><wp:extent cx="1524000" cy="762000"/><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:blipFill><a:blip xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:embed="image"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1524000" cy="762000"/></a:xfrm><a:prstGeom prst="rect"/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>'''
|
| 366 |
-
files['word/document.xml'] = files['word/document.xml'].decode().replace('<w:sectPr/>', drawing * repeats + '<w:sectPr/>')
|
| 367 |
-
if font is not None:
|
| 368 |
-
files['[Content_Types].xml'] = files['[Content_Types].xml'].replace('</Types>', '<Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/></Types>')
|
| 369 |
-
files['word/_rels/document.xml.rels'] = files['word/_rels/document.xml.rels'].replace('</Relationships>', '<Relationship Id="fontTable" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/></Relationships>')
|
| 370 |
-
files['word/fontTable.xml'] = '<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:font w:name="FixtureFont"><w:embedRegular r:id="font" w:fontKey="{00000000-0000-0000-0000-000000000000}"/></w:font></w:fonts>'
|
| 371 |
-
files['word/_rels/fontTable.xml.rels'] = '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="font" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/font" Target="fonts/font.odttf"/></Relationships>'
|
| 372 |
-
files['word/fonts/font.odttf'] = font
|
| 373 |
-
files['word/document.xml'] = files['word/document.xml'].replace('<w:r><w:t>', '<w:r><w:rPr><w:rFonts w:ascii="FixtureFont" w:hAnsi="FixtureFont"/></w:rPr><w:t>')
|
| 374 |
-
return support.zip_bytes(files)
|
| 375 |
-
|
| 376 |
-
def test_real_docx_images_use_owned_blob_urls_and_release_on_close(self):
|
| 377 |
-
self.page.add_init_script('window.__imageReads=0;')
|
| 378 |
-
def zip_engine(route):
|
| 379 |
-
response = route.fetch()
|
| 380 |
-
route.fulfill(response=response, body=response.text() + '''
|
| 381 |
-
const original=JSZip.loadAsync;
|
| 382 |
-
JSZip.loadAsync=async(...args)=>{const zip=await original(...args);
|
| 383 |
-
const file=zip.file('word/media/image.png'),read=file.async.bind(file);
|
| 384 |
-
file.async=(...args)=>{__imageReads++;return read(...args);};return zip;};''')
|
| 385 |
-
self.page.route('**/static/vendor/jszip.min.*.js', zip_engine)
|
| 386 |
-
self.page.add_init_script('''window.__created = []; window.__revoked = [];
|
| 387 |
-
const create = URL.createObjectURL.bind(URL), revoke = URL.revokeObjectURL.bind(URL);
|
| 388 |
-
URL.createObjectURL = blob => { const url=create(blob); __created.push(url); return url; };
|
| 389 |
-
URL.revokeObjectURL = url => { __revoked.push(url); return revoke(url); };''')
|
| 390 |
-
font = (fixtures.support.ROOT / 'static/vendor/standard_fonts/LiberationSans-Regular.ttf').read_bytes()
|
| 391 |
-
self.serve(self.image_docx(font=font), 'application/octet-stream')
|
| 392 |
-
self.open(self.docx_url())
|
| 393 |
-
self.page.wait_for_function('() => document.querySelectorAll(".docx-body img").length === 3 && [...document.querySelectorAll(".docx-body img")].every(image => image.naturalWidth > 0)')
|
| 394 |
-
self.assertTrue(all(url.startswith('blob:') for url in self.page.locator('.docx-body img').evaluate_all('images => images.map(image => image.src)')))
|
| 395 |
-
self.assertEqual(self.page.evaluate('__revoked.length'), 0)
|
| 396 |
-
self.assertEqual(self.page.evaluate('async () => (await document.fonts.load("16px FixtureFont")).length'), 1)
|
| 397 |
-
self.assertTrue(self.page.evaluate('[...document.fonts].some(font => font.family === "FixtureFont" && font.status === "loaded")'))
|
| 398 |
-
self.assertEqual(self.page.evaluate('__created.length'), 2)
|
| 399 |
-
self.assertEqual(self.page.evaluate('__imageReads'), 1)
|
| 400 |
-
self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose"))')
|
| 401 |
-
self.assertEqual(self.page.evaluate('__created.slice().sort()'), self.page.evaluate('__revoked.slice().sort()'))
|
| 402 |
-
|
| 403 |
-
def test_docx_failure_and_late_render_cannot_leak_blob_assets(self):
|
| 404 |
-
script = '''window.docx = {
|
| 405 |
-
parseAsync: async () => ({blobToURL: blob => URL.createObjectURL(blob)}),
|
| 406 |
-
renderDocument: async doc => {
|
| 407 |
-
window.__ownedUrl = doc.blobToURL(new Blob(['font']), 'font.ttf');
|
| 408 |
-
window.__lateBlob = () => doc.blobToURL(new Blob(['late']), 'image.png');
|
| 409 |
-
if (location.search.includes('hold=1')) await new Promise(resolve => {window.__releaseDocx = resolve;});
|
| 410 |
-
throw new Error('render fixture failure');
|
| 411 |
-
}
|
| 412 |
-
};'''
|
| 413 |
-
self.page.route('**/static/vendor/docx-preview.min.*.js', lambda route: route.fulfill(content_type='text/javascript', body=script))
|
| 414 |
-
self.page.add_init_script('''window.__revoked = []; const revoke=URL.revokeObjectURL.bind(URL);
|
| 415 |
-
URL.revokeObjectURL = url => {__revoked.push(url); revoke(url);};''')
|
| 416 |
-
self.serve(fixtures.support.minimal_docx(), 'application/octet-stream')
|
| 417 |
-
for hold in (False, True):
|
| 418 |
-
with self.subTest(hold=hold):
|
| 419 |
-
self.page.goto(self.docx_url() + ('&hold=1' if hold else ''))
|
| 420 |
-
self.page.wait_for_function('() => !!window.__ownedUrl')
|
| 421 |
-
if hold:
|
| 422 |
-
self.page.evaluate('window.dispatchEvent(new Event("voice-reader-dispose")); __releaseDocx()')
|
| 423 |
-
else:
|
| 424 |
-
self.page.wait_for_function('() => document.documentElement.dataset.readerPhase === "failed"')
|
| 425 |
-
self.assertEqual(self.page.evaluate('__revoked'), [self.page.evaluate('__ownedUrl')])
|
| 426 |
-
self.assertIsNone(self.page.evaluate('__lateBlob()'))
|
| 427 |
|
| 428 |
def test_dom_snapshot_reuses_text_after_highlights_and_invalidates_external_edits(self):
|
| 429 |
self.expose()
|
| 430 |
body = '<p><span>nee</span><b>dle</b> otherword</p>' + '<p>ordinary</p>' * 4000 + '<p>tail needle</p>'
|
| 431 |
-
for extension in ('html', 'md', 'txt'
|
| 432 |
with self.subTest(extension=extension):
|
| 433 |
-
if extension == '
|
| 434 |
-
|
| 435 |
-
self.serve(fixtures.support.minimal_docx(), 'application/octet-stream')
|
| 436 |
-
self.open(self.docx_url())
|
| 437 |
-
else:
|
| 438 |
-
self.serve('needle otherword\n' + 'ordinary\n' * 4000 + 'tail needle' if extension == 'txt' else body)
|
| 439 |
-
self.open(self.reader_url(extension))
|
| 440 |
self.assertEqual(self.page.evaluate('__query("needle")'), 2)
|
| 441 |
self.page.evaluate('window.__originalSnapshot = __snapshot(); __walkProbe()')
|
| 442 |
self.assertEqual(self.page.evaluate('__query("otherword")'), 1)
|
|
|
|
| 2 |
|
| 3 |
import gzip
|
| 4 |
import hashlib
|
|
|
|
| 5 |
import json
|
| 6 |
import unittest
|
| 7 |
import urllib.parse
|
|
|
|
| 8 |
|
| 9 |
from tests import test_reader_refactor as fixtures
|
| 10 |
|
|
|
|
| 202 |
self.assertEqual(self.page.evaluate('__pdfProbeTotal()'), 123)
|
| 203 |
self.assertEqual(self.page.evaluate('__extraction.calls'), [1, 2])
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
def test_mobile_pdf_search_keeps_one_demand_slot_and_drops_queued_cancelled_work(self):
|
| 206 |
self.expose()
|
| 207 |
self.serve('mobile scheduling fixture')
|
|
|
|
| 319 |
self.assertEqual(self.page.locator('mark.full-search-highlight').text_content(), 'needle')
|
| 320 |
self.assertGreater(sum(url.endswith('chapter-1.xhtml') for url in requested), 1)
|
| 321 |
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
def test_dom_snapshot_reuses_text_after_highlights_and_invalidates_external_edits(self):
|
| 327 |
self.expose()
|
| 328 |
body = '<p><span>nee</span><b>dle</b> otherword</p>' + '<p>ordinary</p>' * 4000 + '<p>tail needle</p>'
|
| 329 |
+
for extension in ('html', 'md', 'txt'):
|
| 330 |
with self.subTest(extension=extension):
|
| 331 |
+
self.serve('needle otherword\n' + 'ordinary\n' * 4000 + 'tail needle' if extension == 'txt' else body)
|
| 332 |
+
self.open(self.reader_url(extension))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
self.assertEqual(self.page.evaluate('__query("needle")'), 2)
|
| 334 |
self.page.evaluate('window.__originalSnapshot = __snapshot(); __walkProbe()')
|
| 335 |
self.assertEqual(self.page.evaluate('__query("otherword")'), 1)
|
tests/test_reader_performance.py
CHANGED
|
@@ -39,16 +39,12 @@ VENDOR_FILES = {
|
|
| 39 |
"pdf_worker": vendor_name("pdfWorker", "pdf.worker.min.*.mjs"),
|
| 40 |
"marked": vendor_name("marked", "marked.min.*.js"),
|
| 41 |
"purify": vendor_name("purify", "purify.min.*.js"),
|
| 42 |
-
"jszip": vendor_name("jszip", "jszip.min.*.js"),
|
| 43 |
-
"docx": vendor_name("docx", "docx-preview.min.*.js"),
|
| 44 |
}
|
| 45 |
VENDOR_STEMS = {
|
| 46 |
"pdf": "pdf.min.*.mjs",
|
| 47 |
"pdf_worker": "pdf.worker.min.*.mjs",
|
| 48 |
"marked": "marked.min.*.js",
|
| 49 |
"purify": "purify.min.*.js",
|
| 50 |
-
"jszip": "jszip.min.*.js",
|
| 51 |
-
"docx": "docx-preview.min.*.js",
|
| 52 |
}
|
| 53 |
|
| 54 |
|
|
@@ -126,7 +122,6 @@ window.VoiceOfMLReaderStore = Object.freeze({
|
|
| 126 |
"""
|
| 127 |
MARKED_SCRIPT = "window.marked = { parse: (text) => '<p>' + text + '</p>' };"
|
| 128 |
PURIFY_SCRIPT = "window.DOMPurify = { sanitize: (html) => html };"
|
| 129 |
-
JSZIP_SCRIPT = "window.JSZip = function() {};"
|
| 130 |
EPUB_SCRIPT = """
|
| 131 |
window.ePub = () => ({ renderTo: (frame) => ({
|
| 132 |
themes: { register() {}, select() {}, fontSize() {} },
|
|
@@ -136,12 +131,6 @@ window.ePub = () => ({ renderTo: (frame) => ({
|
|
| 136 |
}, 20)),
|
| 137 |
}) });
|
| 138 |
"""
|
| 139 |
-
DOCX_SCRIPT = """
|
| 140 |
-
window.docx = { parseAsync: async () => ({blobToURL: blob => URL.createObjectURL(blob)}),
|
| 141 |
-
renderDocument: () => new Promise(resolve => setTimeout(() => {
|
| 142 |
-
resolve([document.createTextNode('DOCX readable')]);
|
| 143 |
-
}, 20)) };
|
| 144 |
-
"""
|
| 145 |
PNG_BYTES = bytes.fromhex(
|
| 146 |
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
|
| 147 |
"0000000d49444154789c6360f8cfc000000301010018dd8db10000000049454e44ae426082"
|
|
@@ -232,14 +221,6 @@ def epub_with_many_chapters(count=14):
|
|
| 232 |
return zip_bytes(files, ("mimetype", "application/epub+zip"))
|
| 233 |
|
| 234 |
|
| 235 |
-
def minimal_docx():
|
| 236 |
-
return zip_bytes({
|
| 237 |
-
"[Content_Types].xml": '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>',
|
| 238 |
-
"_rels/.rels": '<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
|
| 239 |
-
"word/document.xml": '<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>DOCX readable</w:t></w:r></w:p><w:sectPr/></w:body></w:document>',
|
| 240 |
-
})
|
| 241 |
-
|
| 242 |
-
|
| 243 |
def minimal_wav():
|
| 244 |
output = io.BytesIO()
|
| 245 |
with wave.open(output, "wb") as audio:
|
|
@@ -704,14 +685,13 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 704 |
self.assertEqual(self.page.locator("#download").get_attribute("target"), "_blank")
|
| 705 |
self.assertIn("noopener", self.page.locator("#download").get_attribute("rel"))
|
| 706 |
|
| 707 |
-
def
|
| 708 |
cases = [
|
| 709 |
("pdf", "pdf", "30 页", ".reader-page", "application/pdf", b"pdf", False, False),
|
| 710 |
("txt", "text", "已加载", ".reader-text", "text/plain", b"Text readable", True, False),
|
| 711 |
("md", "markdown", "已加载", ".reader-markdown", "text/markdown", b"# Markdown readable", True, False),
|
| 712 |
("html", "html", "HTML", "iframe.html-frame", "text/html", b"<p>HTML readable</p>", True, False),
|
| 713 |
("png", "image", "图片", ".reader-image", "image/png", PNG_BYTES, True, False),
|
| 714 |
-
("docx", "docx", "DOCX", ".docx-body", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", minimal_docx(), False, False),
|
| 715 |
("wav", "audio", "音频", ".reader-audio", "audio/wav", minimal_wav(), True, True),
|
| 716 |
]
|
| 717 |
for extension, mode, status, content_selector, content_type, body, page_hidden, zoom_hidden in cases:
|
|
@@ -723,13 +703,8 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 723 |
if extension == "md":
|
| 724 |
page.route("**/static/vendor/marked.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=MARKED_SCRIPT))
|
| 725 |
page.route("**/static/vendor/purify.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=PURIFY_SCRIPT))
|
| 726 |
-
if extension == "docx":
|
| 727 |
-
page.route("**/static/vendor/jszip.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=JSZIP_SCRIPT))
|
| 728 |
-
page.route("**/static/vendor/docx-preview.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=DOCX_SCRIPT))
|
| 729 |
page.route("**/api/reader-content**", lambda route, _request, content_type=content_type, body=body: route.fulfill(status=200, content_type=content_type, body=body))
|
| 730 |
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/matrix.{extension}"
|
| 731 |
-
if extension == "docx":
|
| 732 |
-
source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "a" * 64 + "/docx-native-v1/document.docx"
|
| 733 |
page.route("**/api/reader-resolve?id=capability-matrix", lambda route: route.fulfill(
|
| 734 |
status=200, content_type="application/json",
|
| 735 |
body=json.dumps({"url": source, "extension": extension, "title": "Matrix"}),
|
|
@@ -1307,29 +1282,25 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 1307 |
page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub-chapters&title=Limits", wait_until="domcontentloaded")
|
| 1308 |
page.locator(".reader-error").wait_for(timeout=10000); self.assertIn(page.locator("#content").get_attribute("data-error-code"), ("READER_PARSE", "READER_CORRUPT")); expected_limit = limit if name == "manifest" else 8 * 1024 * 1024; self.assertEqual(page.evaluate("limit => { try { VoiceOfMLReaderSecurity.assertResponseSize({headers:{get:()=>String(limit + 1)}}, limit); return null; } catch (error) { return error.message; } }", expected_limit), "READER_RESOURCE_LIMIT"); context.close()
|
| 1309 |
|
| 1310 |
-
def
|
| 1311 |
payload = zip_bomb_metadata()
|
| 1312 |
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
| 1313 |
self.assertIsNone(archive.testzip())
|
| 1314 |
entry = archive.getinfo("bomb.txt")
|
| 1315 |
self.assertGreater(entry.file_size / entry.compress_size, 200)
|
| 1316 |
-
|
| 1317 |
-
|
| 1318 |
-
|
| 1319 |
-
|
| 1320 |
-
|
| 1321 |
-
|
| 1322 |
-
|
| 1323 |
-
|
| 1324 |
-
|
| 1325 |
-
|
| 1326 |
-
|
| 1327 |
-
|
| 1328 |
-
|
| 1329 |
-
self.assertIn("READER_ARCHIVE_LIMIT", page.locator(".reader-error").text_content())
|
| 1330 |
-
self.assertEqual(page.locator("#content").get_attribute("data-error-code"), "READER_CORRUPT" if extension == "epub" else "READER_PARSE")
|
| 1331 |
-
self.assertFalse(page.evaluate("window.__archiveParserStarted === true"))
|
| 1332 |
-
context.close()
|
| 1333 |
|
| 1334 |
def test_actual_store_broadcasts_progress_and_bookmark_updates_between_readers(self):
|
| 1335 |
self.page.unroute("**/static/reader/core/reader-store.js"); self.page.unroute("**/api/reader-content**")
|
|
@@ -2388,7 +2359,6 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 2388 |
def test_supported_formats_start_loading_while_history_restores(self):
|
| 2389 |
cases = [
|
| 2390 |
("md", "已加载", ".reader-markdown", ["content", "marked", "purify"]),
|
| 2391 |
-
("docx", "DOCX", ".docx-body", ["content", "jszip", "docx"]),
|
| 2392 |
("png", "图片", ".reader-image", ["content"]),
|
| 2393 |
]
|
| 2394 |
elapsed_by_format = {}
|
|
@@ -2412,17 +2382,11 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 2412 |
page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=pending_store))
|
| 2413 |
page.route("**/static/vendor/marked.min.*.js", timed("marked", "text/javascript", MARKED_SCRIPT))
|
| 2414 |
page.route("**/static/vendor/purify.min.*.js", timed("purify", "text/javascript", PURIFY_SCRIPT))
|
| 2415 |
-
page.route("**/static/vendor/jszip.min.*.js", timed("jszip", "text/javascript", JSZIP_SCRIPT))
|
| 2416 |
page.route("**/static/vendor/epub.min.06eae1574510.js", timed("epub", "text/javascript", EPUB_SCRIPT))
|
| 2417 |
-
page.route("**/static/vendor/docx-preview.min.*.js", timed("docx", "text/javascript", DOCX_SCRIPT))
|
| 2418 |
content_type = "image/png" if extension == "png" else "application/octet-stream"
|
| 2419 |
-
body = PNG_BYTES if extension == "png" else
|
| 2420 |
page.route("**/api/reader-content**", timed("content", content_type, body))
|
| 2421 |
-
|
| 2422 |
-
digest = "a" * 64
|
| 2423 |
-
source = f"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/{digest}/docx-native-v1/document.docx"
|
| 2424 |
-
else:
|
| 2425 |
-
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/performance.{extension}"
|
| 2426 |
if extension == "png":
|
| 2427 |
page.route(source, timed("content", content_type, body))
|
| 2428 |
started = time.perf_counter()
|
|
@@ -2452,7 +2416,6 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 2452 |
("txt", b"Cold TXT readable", "text/plain", "已加载", ".reader-text", []),
|
| 2453 |
("md", b"# Cold Markdown", "text/markdown", "已加载", ".reader-markdown", [VENDOR_FILES["marked"], VENDOR_FILES["purify"]]),
|
| 2454 |
("pdf", minimal_pdf(), "application/pdf", "1 页", ".reader-page canvas.ready", [VENDOR_FILES["pdf"], VENDOR_FILES["pdf_worker"]]),
|
| 2455 |
-
("docx", minimal_docx(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "1 页", ".docx-body", [VENDOR_FILES["jszip"], VENDOR_FILES["docx"]]),
|
| 2456 |
("png", PNG_BYTES, "image/png", "图片", ".reader-image", []),
|
| 2457 |
]
|
| 2458 |
results = []
|
|
@@ -2469,19 +2432,12 @@ class ReaderPerformanceTest(unittest.TestCase):
|
|
| 2469 |
route.fulfill(status=200, content_type=content_type, body=document)
|
| 2470 |
|
| 2471 |
page.route("**/api/reader-content**", serve_document)
|
| 2472 |
-
|
| 2473 |
-
digest = "a" * 64
|
| 2474 |
-
source = f"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/{digest}/docx-native-v1/document.docx"
|
| 2475 |
-
else:
|
| 2476 |
-
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/cold.{extension}"
|
| 2477 |
if extension == "png": page.route(source, serve_document)
|
| 2478 |
started = time.perf_counter()
|
| 2479 |
page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext={extension}&title=Cold", wait_until="domcontentloaded")
|
| 2480 |
page.wait_for_function("expected => document.querySelector('#status').textContent === expected", arg=ready_status, timeout=30000)
|
| 2481 |
page.locator(selector).wait_for(state="attached", timeout=30000)
|
| 2482 |
-
if extension == "docx":
|
| 2483 |
-
self.assertTrue(page.locator(".page-controls").is_visible())
|
| 2484 |
-
self.assertEqual(page.locator(".reader-docx-page").count(), 1)
|
| 2485 |
elapsed = (time.perf_counter() - started) * 1000
|
| 2486 |
urls = [urllib.parse.urlsplit(response.url).path.rsplit("/", 1)[-1] for response in responses]
|
| 2487 |
for engine in engines: self.assertIn(engine, urls)
|
|
|
|
| 39 |
"pdf_worker": vendor_name("pdfWorker", "pdf.worker.min.*.mjs"),
|
| 40 |
"marked": vendor_name("marked", "marked.min.*.js"),
|
| 41 |
"purify": vendor_name("purify", "purify.min.*.js"),
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
VENDOR_STEMS = {
|
| 44 |
"pdf": "pdf.min.*.mjs",
|
| 45 |
"pdf_worker": "pdf.worker.min.*.mjs",
|
| 46 |
"marked": "marked.min.*.js",
|
| 47 |
"purify": "purify.min.*.js",
|
|
|
|
|
|
|
| 48 |
}
|
| 49 |
|
| 50 |
|
|
|
|
| 122 |
"""
|
| 123 |
MARKED_SCRIPT = "window.marked = { parse: (text) => '<p>' + text + '</p>' };"
|
| 124 |
PURIFY_SCRIPT = "window.DOMPurify = { sanitize: (html) => html };"
|
|
|
|
| 125 |
EPUB_SCRIPT = """
|
| 126 |
window.ePub = () => ({ renderTo: (frame) => ({
|
| 127 |
themes: { register() {}, select() {}, fontSize() {} },
|
|
|
|
| 131 |
}, 20)),
|
| 132 |
}) });
|
| 133 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
PNG_BYTES = bytes.fromhex(
|
| 135 |
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
|
| 136 |
"0000000d49444154789c6360f8cfc000000301010018dd8db10000000049454e44ae426082"
|
|
|
|
| 221 |
return zip_bytes(files, ("mimetype", "application/epub+zip"))
|
| 222 |
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
def minimal_wav():
|
| 225 |
output = io.BytesIO()
|
| 226 |
with wave.open(output, "wb") as audio:
|
|
|
|
| 685 |
self.assertEqual(self.page.locator("#download").get_attribute("target"), "_blank")
|
| 686 |
self.assertIn("noopener", self.page.locator("#download").get_attribute("rel"))
|
| 687 |
|
| 688 |
+
def test_supported_format_modes_expose_matching_controls_and_bookmark_ui(self):
|
| 689 |
cases = [
|
| 690 |
("pdf", "pdf", "30 页", ".reader-page", "application/pdf", b"pdf", False, False),
|
| 691 |
("txt", "text", "已加载", ".reader-text", "text/plain", b"Text readable", True, False),
|
| 692 |
("md", "markdown", "已加载", ".reader-markdown", "text/markdown", b"# Markdown readable", True, False),
|
| 693 |
("html", "html", "HTML", "iframe.html-frame", "text/html", b"<p>HTML readable</p>", True, False),
|
| 694 |
("png", "image", "图片", ".reader-image", "image/png", PNG_BYTES, True, False),
|
|
|
|
| 695 |
("wav", "audio", "音频", ".reader-audio", "audio/wav", minimal_wav(), True, True),
|
| 696 |
]
|
| 697 |
for extension, mode, status, content_selector, content_type, body, page_hidden, zoom_hidden in cases:
|
|
|
|
| 703 |
if extension == "md":
|
| 704 |
page.route("**/static/vendor/marked.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=MARKED_SCRIPT))
|
| 705 |
page.route("**/static/vendor/purify.min.*.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=PURIFY_SCRIPT))
|
|
|
|
|
|
|
|
|
|
| 706 |
page.route("**/api/reader-content**", lambda route, _request, content_type=content_type, body=body: route.fulfill(status=200, content_type=content_type, body=body))
|
| 707 |
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/matrix.{extension}"
|
|
|
|
|
|
|
| 708 |
page.route("**/api/reader-resolve?id=capability-matrix", lambda route: route.fulfill(
|
| 709 |
status=200, content_type="application/json",
|
| 710 |
body=json.dumps({"url": source, "extension": extension, "title": "Matrix"}),
|
|
|
|
| 1282 |
page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub-chapters&title=Limits", wait_until="domcontentloaded")
|
| 1283 |
page.locator(".reader-error").wait_for(timeout=10000); self.assertIn(page.locator("#content").get_attribute("data-error-code"), ("READER_PARSE", "READER_CORRUPT")); expected_limit = limit if name == "manifest" else 8 * 1024 * 1024; self.assertEqual(page.evaluate("limit => { try { VoiceOfMLReaderSecurity.assertResponseSize({headers:{get:()=>String(limit + 1)}}, limit); return null; } catch (error) { return error.message; } }", expected_limit), "READER_RESOURCE_LIMIT"); context.close()
|
| 1284 |
|
| 1285 |
+
def test_zip_bomb_metadata_is_rejected_before_foliate_parser(self):
|
| 1286 |
payload = zip_bomb_metadata()
|
| 1287 |
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
| 1288 |
self.assertIsNone(archive.testzip())
|
| 1289 |
entry = archive.getinfo("bomb.txt")
|
| 1290 |
self.assertGreater(entry.file_size / entry.compress_size, 200)
|
| 1291 |
+
context = self.browser.new_context(viewport={"width": 390, "height": 844})
|
| 1292 |
+
self.addCleanup(context.close)
|
| 1293 |
+
page = context.new_page()
|
| 1294 |
+
page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
|
| 1295 |
+
page.route("**/static/foliate-reader/view.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body="customElements.define('foliate-view', class extends HTMLElement { open() { window.__archiveParserStarted=true; throw new Error('parser must not start'); } });"))
|
| 1296 |
+
page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="application/octet-stream", body=payload))
|
| 1297 |
+
source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/bomb.epub"
|
| 1298 |
+
page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext=epub&title=Bomb", wait_until="domcontentloaded")
|
| 1299 |
+
page.locator(".reader-error").wait_for(timeout=10000)
|
| 1300 |
+
self.assertIn("READER_ARCHIVE_LIMIT", page.locator(".reader-error").text_content())
|
| 1301 |
+
self.assertEqual(page.locator("#content").get_attribute("data-error-code"), "READER_CORRUPT")
|
| 1302 |
+
self.assertFalse(page.evaluate("window.__archiveParserStarted === true"))
|
| 1303 |
+
context.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1304 |
|
| 1305 |
def test_actual_store_broadcasts_progress_and_bookmark_updates_between_readers(self):
|
| 1306 |
self.page.unroute("**/static/reader/core/reader-store.js"); self.page.unroute("**/api/reader-content**")
|
|
|
|
| 2359 |
def test_supported_formats_start_loading_while_history_restores(self):
|
| 2360 |
cases = [
|
| 2361 |
("md", "已加载", ".reader-markdown", ["content", "marked", "purify"]),
|
|
|
|
| 2362 |
("png", "图片", ".reader-image", ["content"]),
|
| 2363 |
]
|
| 2364 |
elapsed_by_format = {}
|
|
|
|
| 2382 |
page.route("**/static/reader/core/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=pending_store))
|
| 2383 |
page.route("**/static/vendor/marked.min.*.js", timed("marked", "text/javascript", MARKED_SCRIPT))
|
| 2384 |
page.route("**/static/vendor/purify.min.*.js", timed("purify", "text/javascript", PURIFY_SCRIPT))
|
|
|
|
| 2385 |
page.route("**/static/vendor/epub.min.06eae1574510.js", timed("epub", "text/javascript", EPUB_SCRIPT))
|
|
|
|
| 2386 |
content_type = "image/png" if extension == "png" else "application/octet-stream"
|
| 2387 |
+
body = PNG_BYTES if extension == "png" else b"Reader benchmark content"
|
| 2388 |
page.route("**/api/reader-content**", timed("content", content_type, body))
|
| 2389 |
+
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/performance.{extension}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2390 |
if extension == "png":
|
| 2391 |
page.route(source, timed("content", content_type, body))
|
| 2392 |
started = time.perf_counter()
|
|
|
|
| 2416 |
("txt", b"Cold TXT readable", "text/plain", "已加载", ".reader-text", []),
|
| 2417 |
("md", b"# Cold Markdown", "text/markdown", "已加载", ".reader-markdown", [VENDOR_FILES["marked"], VENDOR_FILES["purify"]]),
|
| 2418 |
("pdf", minimal_pdf(), "application/pdf", "1 页", ".reader-page canvas.ready", [VENDOR_FILES["pdf"], VENDOR_FILES["pdf_worker"]]),
|
|
|
|
| 2419 |
("png", PNG_BYTES, "image/png", "图片", ".reader-image", []),
|
| 2420 |
]
|
| 2421 |
results = []
|
|
|
|
| 2432 |
route.fulfill(status=200, content_type=content_type, body=document)
|
| 2433 |
|
| 2434 |
page.route("**/api/reader-content**", serve_document)
|
| 2435 |
+
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/cold.{extension}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2436 |
if extension == "png": page.route(source, serve_document)
|
| 2437 |
started = time.perf_counter()
|
| 2438 |
page.goto(f"{self.origin}/static/reader.html?url={urllib.parse.quote(source, safe='')}&ext={extension}&title=Cold", wait_until="domcontentloaded")
|
| 2439 |
page.wait_for_function("expected => document.querySelector('#status').textContent === expected", arg=ready_status, timeout=30000)
|
| 2440 |
page.locator(selector).wait_for(state="attached", timeout=30000)
|
|
|
|
|
|
|
|
|
|
| 2441 |
elapsed = (time.perf_counter() - started) * 1000
|
| 2442 |
urls = [urllib.parse.urlsplit(response.url).path.rsplit("/", 1)[-1] for response in responses]
|
| 2443 |
for engine in engines: self.assertIn(engine, urls)
|
tests/test_reader_refactor.py
CHANGED
|
@@ -143,21 +143,17 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 143 |
self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))
|
| 144 |
self.assertTrue(self.page.locator("#full-search-toggle").evaluate("node => node.hidden"))
|
| 145 |
|
| 146 |
-
def
|
| 147 |
-
|
| 148 |
-
self.page.
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
self.
|
| 154 |
-
self.
|
| 155 |
-
self.
|
| 156 |
-
self.
|
| 157 |
-
held[0].continue_()
|
| 158 |
-
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 159 |
-
self.assertEqual(self.page.locator('.reader-docx-page').count(), 1)
|
| 160 |
-
self.assertIn('DOCX readable', self.page.locator('.docx-body').text_content())
|
| 161 |
|
| 162 |
def test_missing_image_manifest_or_page_recovers_original_without_changing_book_identity(self):
|
| 163 |
prefix = 'pages/image/bmp/' + 'a' * 64 + '/'
|
|
@@ -2464,16 +2460,11 @@ class ReaderRefactorTest(unittest.TestCase):
|
|
| 2464 |
};
|
| 2465 |
""")
|
| 2466 |
self.page.route("**/static/reader.js*", instrument)
|
| 2467 |
-
for extension in ('html', 'md', '
|
| 2468 |
with self.subTest(extension=extension):
|
| 2469 |
-
if extension == '
|
| 2470 |
-
|
| 2471 |
-
|
| 2472 |
-
self.serve(support.minimal_docx(), 'application/octet-stream')
|
| 2473 |
-
else:
|
| 2474 |
-
self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,
|
| 2475 |
-
'text/html' if extension == 'html' else 'text/plain')
|
| 2476 |
-
source = self.reader_url(extension, url='https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a' * 64 + '/document.docx') if extension == 'docx' else self.reader_url(extension)
|
| 2477 |
self.open(source)
|
| 2478 |
self.search('needle')
|
| 2479 |
self.assertEqual(self.page.locator('#full-search-status').text_content(), '2 个结果')
|
|
|
|
| 143 |
self.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))
|
| 144 |
self.assertTrue(self.page.locator("#full-search-toggle").evaluate("node => node.hidden"))
|
| 145 |
|
| 146 |
+
def test_unconverted_docx_is_download_only_without_loading_native_engines(self):
|
| 147 |
+
requests = []
|
| 148 |
+
self.page.on("request", lambda request: requests.append(request.url))
|
| 149 |
+
source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/unconverted.docx'
|
| 150 |
+
self.page.goto(self.reader_url('docx', url=source), wait_until='domcontentloaded')
|
| 151 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'failed'")
|
| 152 |
+
self.assertIn("此文件暂不支持在线阅读", self.page.locator('.reader-error').text_content())
|
| 153 |
+
download = self.page.locator('#download').get_attribute('href')
|
| 154 |
+
self.assertTrue(download.startswith('/api/download?'))
|
| 155 |
+
self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(download).query).get('link'), [source])
|
| 156 |
+
self.assertFalse(any('docx-preview' in url or 'jszip' in url.lower() for url in requests))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
def test_missing_image_manifest_or_page_recovers_original_without_changing_book_identity(self):
|
| 159 |
prefix = 'pages/image/bmp/' + 'a' * 64 + '/'
|
|
|
|
| 2460 |
};
|
| 2461 |
""")
|
| 2462 |
self.page.route("**/static/reader.js*", instrument)
|
| 2463 |
+
for extension in ('html', 'md', 'txt'):
|
| 2464 |
with self.subTest(extension=extension):
|
| 2465 |
+
self.serve('before needle after\n' + 'ordinary\n' * 8000 + 'last needle' if extension == 'txt' else html,
|
| 2466 |
+
'text/html' if extension == 'html' else 'text/plain')
|
| 2467 |
+
source = self.reader_url(extension)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2468 |
self.open(source)
|
| 2469 |
self.search('needle')
|
| 2470 |
self.assertEqual(self.page.locator('#full-search-status').text_content(), '2 个结果')
|
tests/test_reader_regression.js
CHANGED
|
@@ -114,7 +114,7 @@ for (const path of [assetRoot + '../linearized.pdf', assetRoot + 'private.json',
|
|
| 114 |
assert.strictEqual(assets.isAssetSourcePath(sourcePrefix + path), false)
|
| 115 |
}
|
| 116 |
|
| 117 |
-
for (const extension of ['pdf', 'pdf-pages', 'txt', 'md', 'markdown', 'html', 'htm', '
|
| 118 |
assert.ok(sandbox.self.VoiceOfMLReader.capability(extension).mode, extension)
|
| 119 |
}
|
| 120 |
for (const extension of ['epub', 'mobi', 'azw3', 'fb2', 'fbz']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'foliate')
|
|
@@ -125,6 +125,8 @@ assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').feat
|
|
| 125 |
for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')
|
| 126 |
for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')
|
| 127 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
|
|
|
|
|
|
|
| 128 |
const convertedUrl = sandbox.self.VoiceOfMLReader.readerUrl({
|
| 129 |
Link: 'https://download.example.test/books/book.mobi',
|
| 130 |
File: '原始书名', Extension: 'mobi', ReaderExtension: 'epub',
|
|
@@ -168,7 +170,8 @@ assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').readerMode, sa
|
|
| 168 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').article, true)
|
| 169 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.UNSUPPORTED)
|
| 170 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').article, false)
|
| 171 |
-
for (const extension of ['pdf', 'pdf-pages', 'epub', 'mobi', 'azw3', 'fb2', 'fbz', '
|
|
|
|
| 172 |
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.articleExtensions), true)
|
| 173 |
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.capability('pdf')), true)
|
| 174 |
const immutableRecord = { Link: 'https://download.example.test/book.txt', File: 'book', Extension: 'txt' }
|
|
|
|
| 114 |
assert.strictEqual(assets.isAssetSourcePath(sourcePrefix + path), false)
|
| 115 |
}
|
| 116 |
|
| 117 |
+
for (const extension of ['pdf', 'pdf-pages', 'txt', 'md', 'markdown', 'html', 'htm', 'epub', 'mobi', 'azw3', 'fb2', 'fbz', 'jpg', 'png', 'mp3', 'm4a', 'flac', 'mpga', 'audio', 'mp4', 'mov', 'video']) {
|
| 118 |
assert.ok(sandbox.self.VoiceOfMLReader.capability(extension).mode, extension)
|
| 119 |
}
|
| 120 |
for (const extension of ['epub', 'mobi', 'azw3', 'fb2', 'fbz']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'foliate')
|
|
|
|
| 125 |
for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')
|
| 126 |
for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')
|
| 127 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
|
| 128 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('docx').mode, null)
|
| 129 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').mode, 'epub-chapters')
|
| 130 |
const convertedUrl = sandbox.self.VoiceOfMLReader.readerUrl({
|
| 131 |
Link: 'https://download.example.test/books/book.mobi',
|
| 132 |
File: '原始书名', Extension: 'mobi', ReaderExtension: 'epub',
|
|
|
|
| 170 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').article, true)
|
| 171 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.UNSUPPORTED)
|
| 172 |
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').article, false)
|
| 173 |
+
for (const extension of ['pdf', 'pdf-pages', 'epub', 'epub-chapters', 'mobi', 'azw3', 'fb2', 'fbz', 'txt', 'md', 'html', 'jpg', 'png', 'webp', 'mp3', 'm4a', 'flac', 'mp4', 'mov']) assert.ok(sandbox.self.VoiceOfMLReader.articleExtensions.includes(extension), extension)
|
| 174 |
+
assert.ok(!sandbox.self.VoiceOfMLReader.articleExtensions.includes('docx'))
|
| 175 |
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.articleExtensions), true)
|
| 176 |
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.capability('pdf')), true)
|
| 177 |
const immutableRecord = { Link: 'https://download.example.test/book.txt', File: 'book', Extension: 'txt' }
|
tests/test_reader_style.py
CHANGED
|
@@ -11,7 +11,6 @@ from tests.test_reader_performance import (
|
|
| 11 |
STORE_SCRIPT,
|
| 12 |
PlaywrightError,
|
| 13 |
epub_with_navigation,
|
| 14 |
-
minimal_docx,
|
| 15 |
static_server,
|
| 16 |
sync_playwright,
|
| 17 |
zip_bytes,
|
|
@@ -308,13 +307,10 @@ class ReaderStyleTests(unittest.TestCase):
|
|
| 308 |
self.assertEqual(button.get_attribute('aria-pressed'), 'false')
|
| 309 |
self.assertEqual(self.page.locator('canvas.ready').first.evaluate('e => getComputedStyle(e).filter'), 'none')
|
| 310 |
|
| 311 |
-
def open_theme_fixture(self,
|
| 312 |
self.page.route("**/api/reader-content**", lambda route: route.fulfill(body=data))
|
| 313 |
-
source = urllib.parse.quote(
|
| 314 |
-
|
| 315 |
-
if extension == "docx" else "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/theme.epub", safe=""
|
| 316 |
-
)
|
| 317 |
-
self.page.goto(f"{self.origin}/static/reader.html?url={source}&ext={extension}&title=Theme")
|
| 318 |
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 319 |
|
| 320 |
def check_document_theme_round_trip(self, selector):
|
|
@@ -331,18 +327,6 @@ class ReaderStyleTests(unittest.TestCase):
|
|
| 331 |
else ["rgb(0, 0, 0)", "rgb(255, 255, 255)"])
|
| 332 |
self.assertEqual(target.bounding_box(), initial)
|
| 333 |
|
| 334 |
-
def test_docx_shaded_runs_and_paragraphs_follow_theme(self):
|
| 335 |
-
with zipfile.ZipFile(io.BytesIO(minimal_docx())) as archive:
|
| 336 |
-
files = {name: archive.read(name) for name in archive.namelist()}
|
| 337 |
-
files["word/document.xml"] = files["word/document.xml"].decode().replace(
|
| 338 |
-
"<w:p><w:r>", '<w:p><w:pPr><w:shd w:fill="FFFFFF"/></w:pPr><w:r>'
|
| 339 |
-
'<w:rPr><w:color w:val="000000"/><w:shd w:fill="FFFFFF"/></w:rPr>'
|
| 340 |
-
)
|
| 341 |
-
self.open_theme_fixture("docx", zip_bytes(files))
|
| 342 |
-
self.check_document_theme_round_trip(".reader-docx p span")
|
| 343 |
-
self.assertEqual(self.page.locator(".reader-docx p").first.evaluate(
|
| 344 |
-
"e=>getComputedStyle(e).backgroundColor"), "rgba(0, 0, 0, 0)")
|
| 345 |
-
|
| 346 |
def test_epub_legacy_font_colors_and_shading_follow_shadow_theme(self):
|
| 347 |
with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive:
|
| 348 |
files = {name: archive.read(name) for name in archive.namelist()}
|
|
@@ -352,7 +336,7 @@ class ReaderStyleTests(unittest.TestCase):
|
|
| 352 |
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">'
|
| 353 |
'<rect id="night-art" width="16" height="16" fill="red"/></svg></body>'
|
| 354 |
)
|
| 355 |
-
self.open_theme_fixture(
|
| 356 |
self.check_document_theme_round_trip("#night-text")
|
| 357 |
self.assertEqual(self.page.locator("#night-art").evaluate("e=>getComputedStyle(e).fill"), "rgb(255, 0, 0)")
|
| 358 |
self.assertEqual(self.page.locator("#night-art").evaluate("e=>getComputedStyle(e.ownerSVGElement).filter"), "none")
|
|
|
|
| 11 |
STORE_SCRIPT,
|
| 12 |
PlaywrightError,
|
| 13 |
epub_with_navigation,
|
|
|
|
| 14 |
static_server,
|
| 15 |
sync_playwright,
|
| 16 |
zip_bytes,
|
|
|
|
| 307 |
self.assertEqual(button.get_attribute('aria-pressed'), 'false')
|
| 308 |
self.assertEqual(self.page.locator('canvas.ready').first.evaluate('e => getComputedStyle(e).filter'), 'none')
|
| 309 |
|
| 310 |
+
def open_theme_fixture(self, data):
|
| 311 |
self.page.route("**/api/reader-content**", lambda route: route.fulfill(body=data))
|
| 312 |
+
source = urllib.parse.quote("https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/theme.epub", safe="")
|
| 313 |
+
self.page.goto(f"{self.origin}/static/reader.html?url={source}&ext=epub&title=Theme")
|
|
|
|
|
|
|
|
|
|
| 314 |
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 315 |
|
| 316 |
def check_document_theme_round_trip(self, selector):
|
|
|
|
| 327 |
else ["rgb(0, 0, 0)", "rgb(255, 255, 255)"])
|
| 328 |
self.assertEqual(target.bounding_box(), initial)
|
| 329 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
def test_epub_legacy_font_colors_and_shading_follow_shadow_theme(self):
|
| 331 |
with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive:
|
| 332 |
files = {name: archive.read(name) for name in archive.namelist()}
|
|
|
|
| 336 |
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">'
|
| 337 |
'<rect id="night-art" width="16" height="16" fill="red"/></svg></body>'
|
| 338 |
)
|
| 339 |
+
self.open_theme_fixture(zip_bytes(files))
|
| 340 |
self.check_document_theme_round_trip("#night-text")
|
| 341 |
self.assertEqual(self.page.locator("#night-art").evaluate("e=>getComputedStyle(e).fill"), "rgb(255, 0, 0)")
|
| 342 |
self.assertEqual(self.page.locator("#night-art").evaluate("e=>getComputedStyle(e.ownerSVGElement).filter"), "none")
|
tests/test_static_contract.py
CHANGED
|
@@ -92,8 +92,6 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 92 |
self.assertIn("reader-pdf-text-fallback", text)
|
| 93 |
self.assertIn("writing_mode", text)
|
| 94 |
self.assertIn(".reader-pdf-text-fallback", css)
|
| 95 |
-
self.assertIn(".docx-body .reader-docx-wrapper", css)
|
| 96 |
-
self.assertIn("width: 100% !important", css)
|
| 97 |
self.assertIn("pageState.hidden = true", reader)
|
| 98 |
self.assertIn("loadPdfOcrManifest().then((manifest)", reader)
|
| 99 |
self.assertIn("manifest?.pages?.[page - 1]", reader)
|
|
@@ -131,7 +129,7 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 131 |
modes = {'pdf': 'pdf', 'pdf-pages': 'pdf-pages', 'epub': 'foliate', 'mobi': 'foliate',
|
| 132 |
'fb2': 'foliate', 'txt': 'text', 'md': 'markdown', 'jpg': 'image',
|
| 133 |
'mp3': 'audio', 'wav': 'audio', 'flac': 'audio', 'mp4': 'video', 'mov': 'video',
|
| 134 |
-
'docx': '
|
| 135 |
evaluated = subprocess.run(
|
| 136 |
['node', '-e', 'const vm = require("vm"), fs = require("fs"); const context = { self: {} }; '
|
| 137 |
'vm.runInNewContext(fs.readFileSync("static/reader/core/reader-contract.js", "utf8"), context); '
|
|
@@ -193,7 +191,7 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 193 |
assert_source_contains(self, 'if (Array.isArray(manifest.toc) && manifest.toc.length) setToc(manifest.toc.map', reader)
|
| 194 |
assert_source_contains(self, 'tab.hidden = !navigationState.tocEntries.length', reader)
|
| 195 |
assert_source_contains(self, 'appendDecoded(decoder.decode(bytes), decoder.encoding)', reader)
|
| 196 |
-
assert_source_contains(self, '
|
| 197 |
assert_source_contains(self, 'capability.mode === "html"', reader)
|
| 198 |
assert_source_contains(self, 'function sanitizeOfflineHtml(text)', reader)
|
| 199 |
assert_source_contains(self, 'detectHtmlEncoding(bytes, documentState.title)', reader)
|
|
@@ -206,13 +204,11 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 206 |
assert_source_contains(self, 'template.content.querySelectorAll("style")', reader)
|
| 207 |
assert_source_contains(self, 'template.content.querySelectorAll("[style]")', reader)
|
| 208 |
self.assertIn('VoiceOfMLReader.isAssetSourcePath(url.pathname)', reader)
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
self.assertIn('VoiceOfMLReaderResources.vendorUrl("jszip", "/static/")', reader)
|
| 213 |
-
self.assertIn('VoiceOfMLReaderResources.vendorUrl("docx", "/static/")', reader)
|
| 214 |
self.assertIn('&& !rec.ReaderLink) return false', self.js)
|
| 215 |
-
|
| 216 |
self.assertIn('warmReaderIntent', self.js)
|
| 217 |
self.assertIn('validatePdfPageManifest', reader)
|
| 218 |
self.assertIn('chapterManifestObserver', reader)
|
|
@@ -302,13 +298,12 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 302 |
self.assertNotIn('epubRendition.themes', reader)
|
| 303 |
self.assertIn('function applyReaderTheme', reader)
|
| 304 |
self.assertIn('readerThemeToggle.innerHTML', reader)
|
| 305 |
-
|
| 306 |
-
self.assertIn('.docx-body.reader-document-dark .reader-docx', reader_css)
|
| 307 |
for value in ('id="bookmark-ribbon"', 'id="toc-tab"', 'id="history-clear"', 'id="theme-toggle"'):
|
| 308 |
self.assertIn(value, reader_html)
|
| 309 |
self.assertIn('.reader-panel-tabs', reader_css)
|
| 310 |
self.assertIn('function syncCurrentPageFromMarker', reader)
|
| 311 |
-
self.
|
| 312 |
self.assertIn('message.type === "voice-reader-open"', self.js)
|
| 313 |
self.assertNotIn('loadFoliateDocument', reader)
|
| 314 |
self.assertIn('async function renderFoliate', reader)
|
|
|
|
| 92 |
self.assertIn("reader-pdf-text-fallback", text)
|
| 93 |
self.assertIn("writing_mode", text)
|
| 94 |
self.assertIn(".reader-pdf-text-fallback", css)
|
|
|
|
|
|
|
| 95 |
self.assertIn("pageState.hidden = true", reader)
|
| 96 |
self.assertIn("loadPdfOcrManifest().then((manifest)", reader)
|
| 97 |
self.assertIn("manifest?.pages?.[page - 1]", reader)
|
|
|
|
| 129 |
modes = {'pdf': 'pdf', 'pdf-pages': 'pdf-pages', 'epub': 'foliate', 'mobi': 'foliate',
|
| 130 |
'fb2': 'foliate', 'txt': 'text', 'md': 'markdown', 'jpg': 'image',
|
| 131 |
'mp3': 'audio', 'wav': 'audio', 'flac': 'audio', 'mp4': 'video', 'mov': 'video',
|
| 132 |
+
'docx': None, 'epub-chapters': 'epub-chapters', 'html': 'html', 'htm': 'html'}
|
| 133 |
evaluated = subprocess.run(
|
| 134 |
['node', '-e', 'const vm = require("vm"), fs = require("fs"); const context = { self: {} }; '
|
| 135 |
'vm.runInNewContext(fs.readFileSync("static/reader/core/reader-contract.js", "utf8"), context); '
|
|
|
|
| 191 |
assert_source_contains(self, 'if (Array.isArray(manifest.toc) && manifest.toc.length) setToc(manifest.toc.map', reader)
|
| 192 |
assert_source_contains(self, 'tab.hidden = !navigationState.tocEntries.length', reader)
|
| 193 |
assert_source_contains(self, 'appendDecoded(decoder.decode(bytes), decoder.encoding)', reader)
|
| 194 |
+
assert_source_contains(self, '"epub-chapters": [loadChapterManifestDocument, renderChapterManifest]', reader)
|
| 195 |
assert_source_contains(self, 'capability.mode === "html"', reader)
|
| 196 |
assert_source_contains(self, 'function sanitizeOfflineHtml(text)', reader)
|
| 197 |
assert_source_contains(self, 'detectHtmlEncoding(bytes, documentState.title)', reader)
|
|
|
|
| 204 |
assert_source_contains(self, 'template.content.querySelectorAll("style")', reader)
|
| 205 |
assert_source_contains(self, 'template.content.querySelectorAll("[style]")', reader)
|
| 206 |
self.assertIn('VoiceOfMLReader.isAssetSourcePath(url.pathname)', reader)
|
| 207 |
+
self.assertNotIn('docx-preview', reader)
|
| 208 |
+
self.assertNotIn('JSZip', reader)
|
| 209 |
+
self.assertNotIn('renderDocx', reader)
|
|
|
|
|
|
|
| 210 |
self.assertIn('&& !rec.ReaderLink) return false', self.js)
|
| 211 |
+
self.assertNotIn('extension === "docx"', reader)
|
| 212 |
self.assertIn('warmReaderIntent', self.js)
|
| 213 |
self.assertIn('validatePdfPageManifest', reader)
|
| 214 |
self.assertIn('chapterManifestObserver', reader)
|
|
|
|
| 298 |
self.assertNotIn('epubRendition.themes', reader)
|
| 299 |
self.assertIn('function applyReaderTheme', reader)
|
| 300 |
self.assertIn('readerThemeToggle.innerHTML', reader)
|
| 301 |
+
self.assertNotIn('docx-body', reader_css)
|
|
|
|
| 302 |
for value in ('id="bookmark-ribbon"', 'id="toc-tab"', 'id="history-clear"', 'id="theme-toggle"'):
|
| 303 |
self.assertIn(value, reader_html)
|
| 304 |
self.assertIn('.reader-panel-tabs', reader_css)
|
| 305 |
self.assertIn('function syncCurrentPageFromMarker', reader)
|
| 306 |
+
self.assertNotIn('reader-docx-page', reader)
|
| 307 |
self.assertIn('message.type === "voice-reader-open"', self.js)
|
| 308 |
self.assertNotIn('loadFoliateDocument', reader)
|
| 309 |
self.assertIn('async function renderFoliate', reader)
|