dlxj commited on
Commit ·
2d8be8f
1
Parent(s): 4e1096a
add sub mods
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +6 -0
- apps/readest-app/src/__tests__/utils/paragraph.test.ts +46 -0
- apps/readest-app/src/utils/paragraph.ts +12 -9
- apps/readest-app/src/utils/style.ts +6 -0
- packages/foliate-js/.gitattributes +1 -0
- packages/foliate-js/.github/FUNDING.yml +1 -0
- packages/foliate-js/.github/workflows/eslint.yml +50 -0
- packages/foliate-js/.gitignore +1 -0
- packages/foliate-js/LICENSE +21 -0
- packages/foliate-js/README.md +374 -0
- packages/foliate-js/comic-book.js +64 -0
- packages/foliate-js/dict.js +241 -0
- packages/foliate-js/epub.js +1374 -0
- packages/foliate-js/epubcfi.js +345 -0
- packages/foliate-js/eslint.config.js +22 -0
- packages/foliate-js/fb2.js +348 -0
- packages/foliate-js/fixed-layout.js +618 -0
- packages/foliate-js/footnotes.js +145 -0
- packages/foliate-js/mobi.js +1236 -0
- packages/foliate-js/opds.js +294 -0
- packages/foliate-js/overlayer.js +409 -0
- packages/foliate-js/package-lock.json +1584 -0
- packages/foliate-js/package.json +50 -0
- packages/foliate-js/paginator.js +1417 -0
- packages/foliate-js/pdf.js +315 -0
- packages/foliate-js/progress.js +113 -0
- packages/foliate-js/quote-image.js +86 -0
- packages/foliate-js/reader.html +304 -0
- packages/foliate-js/reader.js +239 -0
- packages/foliate-js/rollup.config.js +32 -0
- packages/foliate-js/rollup/fflate.js +1 -0
- packages/foliate-js/rollup/zip.js +1 -0
- packages/foliate-js/search.js +130 -0
- packages/foliate-js/tests/epubcfi-tests.js +236 -0
- packages/foliate-js/tests/tests.html +5 -0
- packages/foliate-js/tests/tests.js +1 -0
- packages/foliate-js/text-walker.js +43 -0
- packages/foliate-js/tts.js +377 -0
- packages/foliate-js/ui/menu.js +42 -0
- packages/foliate-js/ui/tree.js +169 -0
- packages/foliate-js/uri-template.js +52 -0
- packages/foliate-js/vendor/fflate.js +1 -0
- packages/foliate-js/vendor/pdfjs/annotation_layer_builder.css +407 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-H.bcmap +3 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-V.bcmap +3 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78-H.bcmap +3 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-H.bcmap +3 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-V.bcmap +3 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78-V.bcmap +3 -0
- packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-H.bcmap +3 -0
.gitattributes
CHANGED
|
@@ -1,4 +1,10 @@
|
|
| 1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
*.woff2 filter=lfs diff=lfs merge=lfs -text
|
| 3 |
*.icns filter=lfs diff=lfs merge=lfs -text
|
| 4 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.pdf filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.exe filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.pfb filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bcmap filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.bcmap filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ttf filter=lfs diff=lfs merge=lfs -text
|
| 8 |
*.woff2 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
*.icns filter=lfs diff=lfs merge=lfs -text
|
| 10 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
apps/readest-app/src/__tests__/utils/paragraph.test.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, it, expect } from 'vitest';
|
| 2 |
+
import { ParagraphIterator } from '@/utils/paragraph';
|
| 3 |
+
|
| 4 |
+
const createDoc = (body: string): Document =>
|
| 5 |
+
new DOMParser().parseFromString(`<html><body>${body}</body></html>`, 'text/html');
|
| 6 |
+
|
| 7 |
+
describe('ParagraphIterator', () => {
|
| 8 |
+
it('skips whitespace-only paragraphs', async () => {
|
| 9 |
+
const doc = createDoc(`
|
| 10 |
+
<p>First</p>
|
| 11 |
+
<p> </p>
|
| 12 |
+
<p> </p>
|
| 13 |
+
<p>\u200b</p>
|
| 14 |
+
<p><span>\u00a0</span></p>
|
| 15 |
+
<p><br /></p>
|
| 16 |
+
<p>Second</p>
|
| 17 |
+
`);
|
| 18 |
+
|
| 19 |
+
const iterator = await ParagraphIterator.createAsync(doc, 1000);
|
| 20 |
+
|
| 21 |
+
expect(iterator.length).toBe(2);
|
| 22 |
+
expect(iterator.first()?.toString()).toContain('First');
|
| 23 |
+
expect(iterator.next()?.toString()).toContain('Second');
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
it('keeps paragraphs with non-text content', async () => {
|
| 27 |
+
const doc = createDoc(`
|
| 28 |
+
<p>Intro</p>
|
| 29 |
+
<p><img src="cover.png" alt="" /></p>
|
| 30 |
+
<p>Outro</p>
|
| 31 |
+
`);
|
| 32 |
+
|
| 33 |
+
const iterator = await ParagraphIterator.createAsync(doc, 1000);
|
| 34 |
+
|
| 35 |
+
expect(iterator.length).toBe(3);
|
| 36 |
+
|
| 37 |
+
iterator.first();
|
| 38 |
+
expect(iterator.current()?.toString()).toContain('Intro');
|
| 39 |
+
|
| 40 |
+
const imageRange = iterator.next();
|
| 41 |
+
const fragment = imageRange?.cloneContents();
|
| 42 |
+
expect(fragment?.querySelector('img')).not.toBeNull();
|
| 43 |
+
|
| 44 |
+
expect(iterator.next()?.toString()).toContain('Outro');
|
| 45 |
+
});
|
| 46 |
+
});
|
apps/readest-app/src/utils/paragraph.ts
CHANGED
|
@@ -31,16 +31,19 @@ const blockTags = new Set([
|
|
| 31 |
|
| 32 |
const MAX_BLOCKS = 5000;
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
const rangeHasContent = (range: Range): boolean => {
|
| 35 |
try {
|
| 36 |
-
const
|
| 37 |
-
if (
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
if (container.nodeType === Node.ELEMENT_NODE) {
|
| 41 |
-
return (container as Element).textContent?.trim().length !== 0;
|
| 42 |
-
}
|
| 43 |
-
return true;
|
| 44 |
} catch {
|
| 45 |
return false;
|
| 46 |
}
|
|
@@ -48,7 +51,7 @@ const rangeHasContent = (range: Range): boolean => {
|
|
| 48 |
|
| 49 |
const hasDirectText = (node: Element): boolean =>
|
| 50 |
Array.from(node.childNodes).some(
|
| 51 |
-
(child) => child.nodeType === Node.TEXT_NODE && child.textContent
|
| 52 |
);
|
| 53 |
|
| 54 |
const hasBlockChild = (node: Element): boolean =>
|
|
|
|
| 31 |
|
| 32 |
const MAX_BLOCKS = 5000;
|
| 33 |
|
| 34 |
+
const INVISIBLE_TEXT_PATTERN =
|
| 35 |
+
/[\s\u00a0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\u200b-\u200d\u2060\ufeff]/g;
|
| 36 |
+
const MEDIA_SELECTOR = 'img, svg, video, audio, canvas, math, iframe, object, embed, hr';
|
| 37 |
+
|
| 38 |
+
const hasMeaningfulText = (text?: string | null): boolean =>
|
| 39 |
+
(text ?? '').replace(INVISIBLE_TEXT_PATTERN, '').length > 0;
|
| 40 |
+
|
| 41 |
const rangeHasContent = (range: Range): boolean => {
|
| 42 |
try {
|
| 43 |
+
const text = range.toString();
|
| 44 |
+
if (hasMeaningfulText(text)) return true;
|
| 45 |
+
const fragment = range.cloneContents();
|
| 46 |
+
return !!fragment.querySelector?.(MEDIA_SELECTOR);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
} catch {
|
| 48 |
return false;
|
| 49 |
}
|
|
|
|
| 51 |
|
| 52 |
const hasDirectText = (node: Element): boolean =>
|
| 53 |
Array.from(node.childNodes).some(
|
| 54 |
+
(child) => child.nodeType === Node.TEXT_NODE && hasMeaningfulText(child.textContent),
|
| 55 |
);
|
| 56 |
|
| 57 |
const hasBlockChild = (node: Element): boolean =>
|
apps/readest-app/src/utils/style.ts
CHANGED
|
@@ -867,10 +867,16 @@ export const applyTableStyle = (document: Document) => {
|
|
| 867 |
table.style.width = `calc(min(${computedWidth}, var(--available-width)))`;
|
| 868 |
}
|
| 869 |
}
|
|
|
|
|
|
|
| 870 |
if (totalTableWidth > 0) {
|
| 871 |
const scale = `calc(min(1, var(--available-width) / ${totalTableWidth}))`;
|
| 872 |
table.style.transformOrigin = 'left top';
|
| 873 |
table.style.transform = `scale(${scale})`;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
}
|
| 875 |
});
|
| 876 |
};
|
|
|
|
| 867 |
table.style.width = `calc(min(${computedWidth}, var(--available-width)))`;
|
| 868 |
}
|
| 869 |
}
|
| 870 |
+
const parentWidth = window.getComputedStyle(parent as Element).width;
|
| 871 |
+
const parentContainerWidth = parseFloat(parentWidth) || 0;
|
| 872 |
if (totalTableWidth > 0) {
|
| 873 |
const scale = `calc(min(1, var(--available-width) / ${totalTableWidth}))`;
|
| 874 |
table.style.transformOrigin = 'left top';
|
| 875 |
table.style.transform = `scale(${scale})`;
|
| 876 |
+
} else if (parentContainerWidth > 0) {
|
| 877 |
+
const scale = `calc(min(1, var(--available-width) / ${parentContainerWidth}))`;
|
| 878 |
+
table.style.transformOrigin = 'center top';
|
| 879 |
+
table.style.transform = `scale(${scale})`;
|
| 880 |
}
|
| 881 |
});
|
| 882 |
};
|
packages/foliate-js/.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
vendor/** linguist-vendored=true
|
packages/foliate-js/.github/FUNDING.yml
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
buy_me_a_coffee: johnfactotum
|
packages/foliate-js/.github/workflows/eslint.yml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This workflow uses actions that are not certified by GitHub.
|
| 2 |
+
# They are provided by a third-party and are governed by
|
| 3 |
+
# separate terms of service, privacy policy, and support
|
| 4 |
+
# documentation.
|
| 5 |
+
# ESLint is a tool for identifying and reporting on patterns
|
| 6 |
+
# found in ECMAScript/JavaScript code.
|
| 7 |
+
# More details at https://github.com/eslint/eslint
|
| 8 |
+
# and https://eslint.org
|
| 9 |
+
|
| 10 |
+
name: ESLint
|
| 11 |
+
|
| 12 |
+
on:
|
| 13 |
+
push:
|
| 14 |
+
branches: [ "main" ]
|
| 15 |
+
pull_request:
|
| 16 |
+
# The branches below must be a subset of the branches above
|
| 17 |
+
branches: [ "main" ]
|
| 18 |
+
schedule:
|
| 19 |
+
- cron: '27 12 * * 1'
|
| 20 |
+
|
| 21 |
+
jobs:
|
| 22 |
+
eslint:
|
| 23 |
+
name: Run eslint scanning
|
| 24 |
+
runs-on: ubuntu-latest
|
| 25 |
+
permissions:
|
| 26 |
+
contents: read
|
| 27 |
+
security-events: write
|
| 28 |
+
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
|
| 29 |
+
steps:
|
| 30 |
+
- name: Checkout code
|
| 31 |
+
uses: actions/checkout@v4
|
| 32 |
+
|
| 33 |
+
- name: Install ESLint
|
| 34 |
+
run: |
|
| 35 |
+
npm install eslint@9.28.0
|
| 36 |
+
npm install @microsoft/eslint-formatter-sarif@3.1.0
|
| 37 |
+
|
| 38 |
+
- name: Run ESLint
|
| 39 |
+
env:
|
| 40 |
+
SARIF_ESLINT_IGNORE_SUPPRESSED: "true"
|
| 41 |
+
run: npx eslint .
|
| 42 |
+
--format @microsoft/eslint-formatter-sarif
|
| 43 |
+
--output-file eslint-results.sarif
|
| 44 |
+
continue-on-error: true
|
| 45 |
+
|
| 46 |
+
- name: Upload analysis results to GitHub
|
| 47 |
+
uses: github/codeql-action/upload-sarif@v3
|
| 48 |
+
with:
|
| 49 |
+
sarif_file: eslint-results.sarif
|
| 50 |
+
wait-for-processing: true
|
packages/foliate-js/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
node_modules/
|
packages/foliate-js/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2022 John Factotum
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
packages/foliate-js/README.md
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# foliate-js
|
| 2 |
+
|
| 3 |
+
Library for rendering e-books in the browser.
|
| 4 |
+
|
| 5 |
+
Features:
|
| 6 |
+
- Supports EPUB, MOBI, KF8 (AZW3), FB2, CBZ, PDF (experimental; requires PDF.js)
|
| 7 |
+
- Add support for other formats yourself by implementing the book interface
|
| 8 |
+
- Pure JavaScript
|
| 9 |
+
- Small and modular
|
| 10 |
+
- No hard dependencies
|
| 11 |
+
- Does not require loading whole file into memory
|
| 12 |
+
- Does not care about older browsers
|
| 13 |
+
|
| 14 |
+
## Demo
|
| 15 |
+
|
| 16 |
+
The repo includes a demo viewer that can be used to open local files. To use it, serve the files with a server, and navigate to `reader.html`. Or visit the [online demo](https://johnfactotum.github.io/foliate-js/reader.html) hosted on GitHub. Note that it is very incomplete at the moment, and lacks many basic features such as keyboard shortcuts.
|
| 17 |
+
|
| 18 |
+
Also note that deobfuscating fonts with the IDPF algorithm requires a SHA-1 function. By default it uses Web Crypto, which is only available in secure contexts. Without HTTPS, you will need to modify `reader.js` and pass your own SHA-1 implementation.
|
| 19 |
+
|
| 20 |
+
## Current Status
|
| 21 |
+
|
| 22 |
+
It works reasonably well, and has been used in several stable releases of [Foliate](https://github.com/johnfactotum/foliate). This library itself is, however, *not* stable. Expect it to break and the API to change at any time. Use it at your own risk.
|
| 23 |
+
|
| 24 |
+
If you do decide to use it, since there's no release yet, it is recommended that you include the library as a git submodule in your project so that you can easily update it.
|
| 25 |
+
|
| 26 |
+
## Documentation
|
| 27 |
+
|
| 28 |
+
### Overview
|
| 29 |
+
|
| 30 |
+
This project uses native ES modules. There's no build step, and you can import them directly.
|
| 31 |
+
|
| 32 |
+
There are mainly three kinds of modules:
|
| 33 |
+
|
| 34 |
+
- Modules that parse and load books, implementing the "book" interface
|
| 35 |
+
- `comic-book.js`, for comic book archives (CBZ)
|
| 36 |
+
- `epub.js` and `epubcfi.js`, for EPUB
|
| 37 |
+
- `fb2.js`, for FictionBook 2
|
| 38 |
+
- `mobi.js`, for both Mobipocket files and KF8 (commonly known as AZW3) files
|
| 39 |
+
- Modules that handle pagination, implementing the "renderer" interface
|
| 40 |
+
- `fixed-layout.js`, for fixed layout books
|
| 41 |
+
- `paginator.js`, for reflowable books
|
| 42 |
+
- Auxiliary modules used to add additional functionalities
|
| 43 |
+
- `overlayer.js`, for rendering annotations
|
| 44 |
+
- `progress.js`, for getting reading progress
|
| 45 |
+
- `search.js`, for searching
|
| 46 |
+
|
| 47 |
+
The modules are designed to be modular. In general, they don't directly depend on each other. Instead they depend on certain interfaces, detailed below. The exception is `view.js`. It is the higher level renderer that strings most of the things together, and you can think of it as the main entry point of the library. See "Basic Usage" below.
|
| 48 |
+
|
| 49 |
+
The repo also includes a still higher level reader, though strictly speaking, `reader.html` (along with `reader.js` and its associated files in `ui/`) is not considered part of the library itself. It's akin to [Epub.js Reader](https://github.com/futurepress/epubjs-reader). You are expected to modify it or replace it with your own code.
|
| 50 |
+
|
| 51 |
+
### Basic Usage
|
| 52 |
+
|
| 53 |
+
To get started, clone the repo and import `view.js`:
|
| 54 |
+
|
| 55 |
+
```js
|
| 56 |
+
import './foliate-js/view.js'
|
| 57 |
+
|
| 58 |
+
const view = document.createElement('foliate-view')
|
| 59 |
+
document.body.append(view)
|
| 60 |
+
|
| 61 |
+
view.addEventListener('relocate', e => {
|
| 62 |
+
console.log('location changed')
|
| 63 |
+
console.log(e.detail)
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
// can open a File/Blob object or a URL
|
| 67 |
+
// or any object that implements the "book" interface
|
| 68 |
+
await view.open('example.epub')
|
| 69 |
+
await view.goTo(/* path, section index, or CFI */)
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
See the [online demo](https://johnfactotum.github.io/foliate-js/reader.html) for a more advanced example.
|
| 73 |
+
|
| 74 |
+
### Security
|
| 75 |
+
|
| 76 |
+
EPUB books can contain [scripted content](https://www.w3.org/TR/epub/#sec-scripted-content) (i.e. JavaScript in the e-book), which is potentially dangerous, and is not supported by this library because
|
| 77 |
+
|
| 78 |
+
- It is currently impossible to do so securely due to the content being served from the same origin (using `blob:` URLs).
|
| 79 |
+
- Due to [WebKit Bug 218086](https://bugs.webkit.org/show_bug.cgi?id=218086), the `allow-scripts` attribute is required on iframes, which renders iframe sandbox useless.
|
| 80 |
+
|
| 81 |
+
It is therefore imperative that you use [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to block all scripts except `'self'`. An EPUB file for testing can be found at https://github.com/johnfactotum/epub-test.
|
| 82 |
+
|
| 83 |
+
> [!CAUTION]
|
| 84 |
+
> Do NOT use this library (or any other e-book library, for that matter) without CSP unless you completely trust the content you're rendering or can block scripts by other means.
|
| 85 |
+
|
| 86 |
+
### The Main Interface for Books
|
| 87 |
+
|
| 88 |
+
Processors for each book format return an object that implements the following interface:
|
| 89 |
+
- `.sections`: an array of sections in the book. Each item has the following properties:
|
| 90 |
+
- `.load()`: returns a string containing the URL that will be rendered. May be async.
|
| 91 |
+
- `.unload()`: returns nothing. If present, can be used to free the section.
|
| 92 |
+
- `.createDocument()`: returns a `Document` object of the section. Used for searching. May be async.
|
| 93 |
+
- `.size`: a number, the byte size of the section. Used for showing reading progress.
|
| 94 |
+
- `.linear`: a string. If it is `"no"`, the section is not part of the linear reading sequence (see the [`linear`](https://www.w3.org/publishing/epub32/epub-packages.html#attrdef-itemref-linear) attribute in EPUB).
|
| 95 |
+
- `.cfi`: base CFI string of the section. The part that goes before the `!` in CFIs.
|
| 96 |
+
- `.id`: an identifier for the section, used for getting TOC item (see below). Can be anything, as long as they can be used as keys in a `Map`.
|
| 97 |
+
- `.dir`: a string representing the page progression direction of the book (`"rtl"` or `"ltr"`).
|
| 98 |
+
- `.toc`: an array representing the table of contents of the book. Each item has
|
| 99 |
+
- `.label`: a string label for the item
|
| 100 |
+
- `.href`: a string representing the destination of the item. Does not have to be a valid URL.
|
| 101 |
+
- `.subitems`: a array that contains TOC items
|
| 102 |
+
- `.pageList`: same as the TOC, but for the [page list](https://www.w3.org/publishing/epub32/epub-packages.html#sec-nav-pagelist).
|
| 103 |
+
- `.metadata`: an object representing the metadata of the book. Currently, it follows more or less the metadata schema of [Readium's webpub manifest](https://github.com/readium/webpub-manifest). Note that titles and names can be a string or an object like `{ ja: "草枕", en: 'Kusamakura' }`, and authors, etc. can be a string, an object, or an array of strings or objects.
|
| 104 |
+
- `.rendition`: an object that contains properties that correspond to the [rendition properties](https://www.w3.org/publishing/epub32/epub-packages.html#sec-package-metadata-rendering) in EPUB. If `.layout` is `"pre-paginated"`, the book is rendered with the fixed layout renderer.
|
| 105 |
+
- `.resolveHref(href)`: given an href string, returns an object representing the destination referenced by the href, which has the following properties:
|
| 106 |
+
- `.index`: the index of the referenced section in the `.section` array
|
| 107 |
+
- `.anchor(doc)`: given a `Document` object, returns the document fragment referred to by the href (can either be an `Element` or a `Range`), or `null`
|
| 108 |
+
- `.resolveCFI(cfi)`: same as above, but with a CFI string instead of href
|
| 109 |
+
- `.isExternal(href)`: returns a boolean. If `true`, the link should be opened externally.
|
| 110 |
+
|
| 111 |
+
The following methods are consumed by `progress.js`, for getting the correct TOC and page list item when navigating:
|
| 112 |
+
- `.splitTOCHref(href)`: given an href string (from the TOC), returns an array, the first element of which is the `id` of the section (see above), and the second element is the fragment identifier (can be any type; see below). May be async.
|
| 113 |
+
- `.getTOCFragment(doc, id)`: given a `Document` object and a fragment identifier (the one provided by `.splitTOCHref()`; see above), returns a `Node` representing the target linked by the TOC item
|
| 114 |
+
|
| 115 |
+
In addition, the `.transformTarget`, if present, can be used to transform the contents of the book as it loads. It is an `EventTarget` with a custom event `"data"`, whose `.detail` is `{ data, type, name }`, where `.data` is either a string or `Blob`, or a `Promise` thereof, `.type` the content type string, and `.name` the identifier of the resource. Event handlers should mutate `.data` to transform the data.
|
| 116 |
+
|
| 117 |
+
Almost all of the properties and methods are optional. At minimum it needs `.sections` and the `.load()` method for the sections, as otherwise there won't be anything to render.
|
| 118 |
+
|
| 119 |
+
### Archived Files
|
| 120 |
+
|
| 121 |
+
Reading Zip-based formats requires adapting an external library. Both `epub.js` and `comic-book.js` expect a `loader` object that implements the following interface:
|
| 122 |
+
|
| 123 |
+
- `.entries`: (only used by `comic-book.js`) an array, each element of which has a `filename` property, which is a string containing the filename (the full path).
|
| 124 |
+
- `.loadText(filename)`: given the path, returns the contents of the file as string. May be async.
|
| 125 |
+
- `.loadBlob(filename)`: given the path, returns the file as a `Blob` object. May be async.
|
| 126 |
+
- `.getSize(filename)`: returns the file size in bytes. Used to set the `.size` property for `.sections` (see above).
|
| 127 |
+
|
| 128 |
+
In `view.js`, this is implemented using [zip.js](https://github.com/gildas-lormeau/zip.js), which is highly recommended because it seems to be the only library that supports random access for `File` objects (as well as HTTP range requests).
|
| 129 |
+
|
| 130 |
+
One advantage of having such an interface is that one can easily use it for reading unarchived files as well. For example, `view.js` has a loader that allows you to open unpacked EPUBs as directories.
|
| 131 |
+
|
| 132 |
+
### Mobipocket and Kindle Files
|
| 133 |
+
|
| 134 |
+
It can read both MOBI and KF8 (.azw3, and combo .mobi files) from a `File` (or `Blob`) object. For MOBI files, it decompresses all text at once and splits the raw markup into sections at every `<mbp:pagebreak>`, instead of outputting one long page for the whole book, which drastically improves rendering performance. For KF8 files, it tries to decompress as little text as possible when loading a section, but it can still be quite slow due to the slowness of the current HUFF/CDIC decompressor implementation. In all cases, images and other resources are not loaded until they are needed.
|
| 135 |
+
|
| 136 |
+
Note that KF8 files can contain fonts that are zlib-compressed. They need to be decompressed with an external library. `view.js` uses [fflate](https://github.com/101arrowz/fflate) to decompress them.
|
| 137 |
+
|
| 138 |
+
### PDF and Other Fixed-Layout Formats
|
| 139 |
+
|
| 140 |
+
There is a proof-of-concept, highly experimental adapter for [PDF.js](https://mozilla.github.io/pdf.js/), with which you can show PDFs using the same fixed-layout renderer for EPUBs.
|
| 141 |
+
|
| 142 |
+
CBZs are similarly handled like fixed-layout EPUBs.
|
| 143 |
+
|
| 144 |
+
### The Renderers
|
| 145 |
+
|
| 146 |
+
To simplify things, it has two separate renderers, one for reflowable books, and one for fixed layout books (as such there's no support for mixed layout books). These renderers are custom elements (web components).
|
| 147 |
+
|
| 148 |
+
A renderer's interface is currently mainly:
|
| 149 |
+
- `.open(book)`: open a book object.
|
| 150 |
+
- `.goTo({ index, anchor })`: navigate to a destination. The argument has the same type as the one returned by `.resolveHref()` in the book object.
|
| 151 |
+
- `.prev()`: go to previous page.
|
| 152 |
+
- `.next()`: go to next page.
|
| 153 |
+
|
| 154 |
+
It has the following custom events:
|
| 155 |
+
- `load`, when a section is loaded. Its `event.detail` has two properties, `doc`, the `Document` object, and `index`, the index of the section.
|
| 156 |
+
- `relocate`, when the location changes. Its `event.detail` has the properties `range`, `index`, and `fraction`, where `range` is a `Range` object containing the current visible area, and `fraction` is a number between 0 and 1, representing the reading progress within the section.
|
| 157 |
+
- `create-overlayer`, which allows adding an overlay to the page. The `event.detail` has the properties `doc`, `index`, and a function `attach(overlay)`, which should be called with an overlayer object (see the description for `overlayer.js` below).
|
| 158 |
+
|
| 159 |
+
Both renderers have the [`part`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/part) named `filter`, which you can apply CSS filters to, to e.g. invert colors or adjust brightness:
|
| 160 |
+
|
| 161 |
+
```css
|
| 162 |
+
foliate-view::part(filter) {
|
| 163 |
+
filter: invert(1) hue-rotate(180deg);
|
| 164 |
+
}
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
The filter only applies to the book itself, leaving overlaid elements such as highlights unaffected.
|
| 168 |
+
|
| 169 |
+
### The Paginator
|
| 170 |
+
|
| 171 |
+
The paginator uses the same pagination strategy as [Epub.js](https://github.com/futurepress/epub.js): it uses CSS multi-column. As such it shares much of the same limitations (it's slow, some CSS styles do not work as expected, and other bugs). There are a few differences:
|
| 172 |
+
- It is a totally standalone module. You can use it to paginate any content.
|
| 173 |
+
- It is much simpler, but currently there's no support for continuous scrolling.
|
| 174 |
+
- It has no concept of CFIs and operates on `Range` objects directly.
|
| 175 |
+
- It uses bisecting to find the current visible range, which is more accurate than what Epub.js does.
|
| 176 |
+
- It has an internal `#anchor` property, which can be a `Range`, `Element`, or a fraction that represents the current location. The view is *anchored* to it no matter how you resize the window.
|
| 177 |
+
- It supports more than two columns.
|
| 178 |
+
- It supports switching between scrolled and paginated mode without reloading (I can't figure out how to do this in Epub.js).
|
| 179 |
+
|
| 180 |
+
The layout can be configured by setting the following attributes:
|
| 181 |
+
- `animated`: a [boolean attribute](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML). If present, adds a sliding transition effect.
|
| 182 |
+
- `flow`: either `paginated` or `scrolled`.
|
| 183 |
+
- `margin`: a CSS `<length>`. The unit must be `px`. The height of the header and footer.
|
| 184 |
+
- `gap`: a CSS `<percentage>`. The size of the space between columns, relative to page size.
|
| 185 |
+
- `max-inline-size`: a CSS `<length>`. The unit must be `px`. The maximum inline size of the text (column width in paginated mode).
|
| 186 |
+
- `max-block-size`: same as above, but for the size in the block direction.
|
| 187 |
+
- `max-column-count`: integer. The maximum number of columns. Has no effect in scrolled mode, or when the orientation of the renderer element is `portrait` (or, for vertical writing, `landscape`).
|
| 188 |
+
|
| 189 |
+
(Note: there's no JS property API. You must use `.setAttribute()`.)
|
| 190 |
+
|
| 191 |
+
It has built-in header and footer regions accessible via the `.heads` and `.feet` properties of the paginator instance. These can be used to display running heads and reading progress. They are only available in paginated mode, and there will be one element for each column. They are styleable with `::part(head)` and `::part(foot)`. E.g., to add a border under the running heads,
|
| 192 |
+
|
| 193 |
+
```css
|
| 194 |
+
foliate-view::part(head) {
|
| 195 |
+
padding-bottom: 4px;
|
| 196 |
+
border-bottom: 1px solid graytext;
|
| 197 |
+
}
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
### EPUB CFI
|
| 201 |
+
|
| 202 |
+
Parsed CFIs are represented as a plain array or object. The basic type is called a "part", which is an object with the following structure: `{ index, id, offset, temporal, spatial, text, side }`, corresponding to a step + offset in the CFI.
|
| 203 |
+
|
| 204 |
+
A collapsed, non-range CFI is represented as an array whose elements are arrays of parts, each corresponding to a full path. That is, `/6/4!/4` is turned into
|
| 205 |
+
|
| 206 |
+
```json
|
| 207 |
+
[
|
| 208 |
+
[
|
| 209 |
+
{ "index": 6 },
|
| 210 |
+
{ "index": 4 }
|
| 211 |
+
],
|
| 212 |
+
[
|
| 213 |
+
{ "index": 4 }
|
| 214 |
+
]
|
| 215 |
+
]
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
A range CFI is an object `{ parent, start, end }`, each property being the same type as a collapsed CFI. For example, `/6/4!/2,/2,/4` is represented as
|
| 219 |
+
|
| 220 |
+
```json
|
| 221 |
+
{
|
| 222 |
+
"parent": [
|
| 223 |
+
[
|
| 224 |
+
{ "index": 6 },
|
| 225 |
+
{ "index": 4 }
|
| 226 |
+
],
|
| 227 |
+
[
|
| 228 |
+
{ "index": 2 }
|
| 229 |
+
]
|
| 230 |
+
],
|
| 231 |
+
"start": [
|
| 232 |
+
[
|
| 233 |
+
{ "index": 2 }
|
| 234 |
+
]
|
| 235 |
+
],
|
| 236 |
+
"end": [
|
| 237 |
+
[
|
| 238 |
+
{ "index": 4 }
|
| 239 |
+
]
|
| 240 |
+
]
|
| 241 |
+
}
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
The parser uses a state machine rather than regex, and should handle assertions that contain escaped characters correctly (see tests for examples of this).
|
| 245 |
+
|
| 246 |
+
It has the ability ignore nodes, which is needed if you want to inject your own nodes into the document without affecting CFIs. To do this, you need to pass the optional filter function that works similarly to the filter function of [`TreeWalker`s](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker):
|
| 247 |
+
|
| 248 |
+
```js
|
| 249 |
+
const filter = node => node.nodeType !== 1 ? NodeFilter.FILTER_ACCEPT
|
| 250 |
+
: node.matches('.reject') ? NodeFilter.FILTER_REJECT
|
| 251 |
+
: node.matches('.skip') ? NodeFilter.FILTER_SKIP
|
| 252 |
+
: NodeFilter.FILTER_ACCEPT
|
| 253 |
+
|
| 254 |
+
CFI.toRange(doc, 'epubcfi(...)', filter)
|
| 255 |
+
CFI.fromRange(range, filter)
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
It can parse and stringify spatial and temporal offsets, as well as text location assertions and side bias, but there's no support for employing them when rendering yet.
|
| 259 |
+
|
| 260 |
+
### Highlighting Text
|
| 261 |
+
|
| 262 |
+
There is a generic module for overlaying arbitrary SVG elements, `overlayer.js`. It can be used to implement highlighting text for annotations. It's the same technique used by [marks-pane](https://github.com/fchasen/marks), used by Epub.js, but it's designed to be easily extensible. You can return any SVG element in the `draw` function, making it possible to add custom styles such as squiggly lines or even free hand drawings.
|
| 263 |
+
|
| 264 |
+
The overlay has no event listeners by default. It only provides a `.hitTest(event)` method, that can be used to do hit tests. Currently it does this with the client rects of `Range`s, not the element returned by `draw()`.
|
| 265 |
+
|
| 266 |
+
An overlayer object implements the following interface for the consumption of renderers:
|
| 267 |
+
- `.element`: the DOM element of the overlayer. This element will be inserted, resized, and positioned automatically by the renderer on top of the page.
|
| 268 |
+
- `.redraw()`: called by the renderer when the overlay needs to be redrawn.
|
| 269 |
+
|
| 270 |
+
### The Text Walker
|
| 271 |
+
|
| 272 |
+
Not a particularly descriptive name, but essentially, `text-walker.js` is a small DOM utility that allows you to
|
| 273 |
+
|
| 274 |
+
1. Gather all text nodes in a `Range`, `Document` or `DocumentFragment` into an array of strings.
|
| 275 |
+
2. Perform splitting or matching on the strings.
|
| 276 |
+
3. Get back the results of these string operations as `Range`s.
|
| 277 |
+
|
| 278 |
+
E.g. you can join all the text nodes together, use `Intl.Segmenter` to segment the string into words, and get the results in DOM Ranges, so you can mark up those words in the original document.
|
| 279 |
+
|
| 280 |
+
In foliate-js, this is used for searching and TTS.
|
| 281 |
+
|
| 282 |
+
### Searching
|
| 283 |
+
|
| 284 |
+
It provides a search module, which can in fact be used as a standalone module for searching across any array of strings. There's no limit on the number of strings a match is allowed to span. It's based on `Intl.Collator` and `Intl.Segmenter`, to support ignoring diacritics and matching whole words only. It's extrenely slow, and you'd probably want to load results incrementally.
|
| 285 |
+
|
| 286 |
+
### Text-to-Speech (TTS)
|
| 287 |
+
|
| 288 |
+
The TTS module doesn't directly handle speech output. Rather, its methods return SSML documents (as strings), which you can then feed to your speech synthesizer.
|
| 289 |
+
|
| 290 |
+
The SSML attributes `ssml:ph` and `ssml:alphabet` are supported. There's no support for PLS and CSS Speech.
|
| 291 |
+
|
| 292 |
+
### Offline Dictionaries
|
| 293 |
+
|
| 294 |
+
The `dict.js` module can be used to load dictd and StarDict dictionaries. Usage:
|
| 295 |
+
|
| 296 |
+
```js
|
| 297 |
+
import { StarDict } from './dict.js'
|
| 298 |
+
import { inflate } from 'your inflate implementation'
|
| 299 |
+
|
| 300 |
+
const { ifo, dz, idx, syn } = { /* `File` (or `Blob`) objects */ }
|
| 301 |
+
const dict = new StarDict()
|
| 302 |
+
await dict.loadIfo(ifo)
|
| 303 |
+
await dict.loadDict(dz, inflate)
|
| 304 |
+
await dict.loadIdx(idx)
|
| 305 |
+
await dict.loadSyn(syn)
|
| 306 |
+
|
| 307 |
+
// look up words
|
| 308 |
+
const query = '...'
|
| 309 |
+
await dictionary.lookup(query)
|
| 310 |
+
await dictionary.synonyms(query)
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
Note that you must supply your own `inflate` function. Here is an example using [fflate](https://github.com/101arrowz/fflate):
|
| 314 |
+
```js
|
| 315 |
+
const inflate = data => new Promise(resolve => {
|
| 316 |
+
const inflate = new fflate.Inflate()
|
| 317 |
+
inflate.ondata = data => resolve(data)
|
| 318 |
+
inflate.push(data)
|
| 319 |
+
})
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
### OPDS
|
| 323 |
+
|
| 324 |
+
The `opds.js` module can be used to implement OPDS clients. It can convert OPDS 1.x documents to OPDS 2.0:
|
| 325 |
+
|
| 326 |
+
- `getFeed(doc)`: converts an OPDS 1.x feed to OPDS 2.0. The argument must be a DOM Document object. You need to use a `DOMParser` to obtain a Document first if you have a string.
|
| 327 |
+
- `getPublication(entry)`: converts a OPDS 1.x entry in acquisition feeds to an OPDS 2.0 publication. The argument must be a DOM Element object.
|
| 328 |
+
|
| 329 |
+
It exports the following symbols for properties unsupported by OPDS 2.0:
|
| 330 |
+
- `SYMBOL.SUMMARY`: used on navigation links to represent the summary/content (see https://github.com/opds-community/drafts/issues/51)
|
| 331 |
+
- `SYMBOL.CONTENT`: used on publications to represent the content/description and its type. This is mainly for preserving the type info for XHTML. The value of this property is an object whose properties are:
|
| 332 |
+
- `.type`: either "text", "html", or "xhtml"
|
| 333 |
+
- `.value`: the value of the content
|
| 334 |
+
|
| 335 |
+
There are also two functions that can be used to implement search forms:
|
| 336 |
+
|
| 337 |
+
- `getOpenSearch(doc)`: for OpenSearch. The argument is a DOM Document object of an OpenSearch search document.
|
| 338 |
+
- `getSearch(link)` for templated search in OPDS 2.0. The argument must be an OPDS 2.0 Link object. Note that this function will import `uri-template.js`.
|
| 339 |
+
|
| 340 |
+
These two functions return an object that implements the following interface:
|
| 341 |
+
- `.metadata`: an object with the string properties `title` and `description`
|
| 342 |
+
- `.params`: an array, representing the search parameters, whose elements are objects whose properties are
|
| 343 |
+
- `ns`: a string; the namespace of the parameter
|
| 344 |
+
- `name`: a string; the name of the parameter
|
| 345 |
+
- `required`: a boolean, whether the parameter is required
|
| 346 |
+
- `value`: a string; the default value of the parameter
|
| 347 |
+
- `.search(map)`: a function, whose argument is a `Map` whose values are `Map`s (i.e. a two-dimensional map). The first key is the namespace of the search parameter. For non-namespaced parameters, the first key must be `null`. The second key is the parameter's name. Returns a string representing the URL of the search results.
|
| 348 |
+
|
| 349 |
+
### Generating Images for Quotes
|
| 350 |
+
|
| 351 |
+
With `quote-image.js`, one can generate shareable images for quotes:
|
| 352 |
+
|
| 353 |
+
```js
|
| 354 |
+
document.querySelector('foliate-quoteimage').getBlob({
|
| 355 |
+
title: 'The Time Machine',
|
| 356 |
+
author: 'H. G. Wells',
|
| 357 |
+
text: 'Can an instantaneous cube exist?',
|
| 358 |
+
})
|
| 359 |
+
```
|
| 360 |
+
|
| 361 |
+
### Supported Browsers
|
| 362 |
+
|
| 363 |
+
It aims to support the latest version of WebKitGTK, Firefox, and Chromium. Older browsers like Firefox ESR are not supported.
|
| 364 |
+
|
| 365 |
+
Although it's mainly indeded for rendering e-books in the browser, some features can be used in non-browser environments as well. In particular, `epubcfi.js` can be used as is in any environment if you only need to parse or sort CFIs. Most other features depend on having the global objects `Blob`, `TextDecoder`, `TextEncoder`, `DOMParser`, `XMLSerializer`, and `URL`, and should work if you polyfill them.
|
| 366 |
+
|
| 367 |
+
## License
|
| 368 |
+
|
| 369 |
+
MIT.
|
| 370 |
+
|
| 371 |
+
Vendored libraries:
|
| 372 |
+
- [zip.js](https://github.com/gildas-lormeau/zip.js) is licensed under the BSD-3-Clause license.
|
| 373 |
+
- [fflate](https://github.com/101arrowz/fflate) is MIT licensed.
|
| 374 |
+
- [PDF.js](https://mozilla.github.io/pdf.js/) is licensed under Apache.
|
packages/foliate-js/comic-book.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export const makeComicBook = async ({ entries, loadBlob, getSize, getComment }, file) => {
|
| 2 |
+
const cache = new Map()
|
| 3 |
+
const urls = new Map()
|
| 4 |
+
const load = async name => {
|
| 5 |
+
if (cache.has(name)) return cache.get(name)
|
| 6 |
+
const src = URL.createObjectURL(await loadBlob(name))
|
| 7 |
+
const page = URL.createObjectURL(
|
| 8 |
+
new Blob([`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin: 0"><img src="${src}"></body></html>`], { type: 'text/html' }))
|
| 9 |
+
urls.set(name, [src, page])
|
| 10 |
+
cache.set(name, page)
|
| 11 |
+
return page
|
| 12 |
+
}
|
| 13 |
+
const unload = name => {
|
| 14 |
+
urls.get(name)?.forEach?.(url => URL.revokeObjectURL(url))
|
| 15 |
+
urls.delete(name)
|
| 16 |
+
cache.delete(name)
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.jxl', '.avif']
|
| 20 |
+
const files = entries
|
| 21 |
+
.map(entry => entry.filename)
|
| 22 |
+
.filter(name => exts.some(ext => name.endsWith(ext)))
|
| 23 |
+
.sort()
|
| 24 |
+
if (!files.length) throw new Error('No supported image files in archive')
|
| 25 |
+
|
| 26 |
+
const book = {}
|
| 27 |
+
try {
|
| 28 |
+
const jsonComment = JSON.parse(await getComment() || '')
|
| 29 |
+
const info = jsonComment['ComicBookInfo/1.0']
|
| 30 |
+
if (info) {
|
| 31 |
+
const year = info.publicationYear
|
| 32 |
+
const month = info.publicationMonth
|
| 33 |
+
const mm = month && month >= 1 && month <= 12 ? String(month).padStart(2, '0') : null
|
| 34 |
+
book.metadata = {
|
| 35 |
+
title: info.title || file.name,
|
| 36 |
+
publisher: info.publisher,
|
| 37 |
+
language: info.language || info.lang,
|
| 38 |
+
author: info.credits ? info.credits.map(c => `${c.person} (${c.role})`).join(', ') : '',
|
| 39 |
+
published: year && month ? `${year}-${mm}` : undefined,
|
| 40 |
+
}
|
| 41 |
+
} else {
|
| 42 |
+
book.metadata = { title: file.name }
|
| 43 |
+
}
|
| 44 |
+
} catch {
|
| 45 |
+
book.metadata = { title: file.name }
|
| 46 |
+
}
|
| 47 |
+
book.getCover = () => loadBlob(files[0])
|
| 48 |
+
book.sections = files.map(name => ({
|
| 49 |
+
id: name,
|
| 50 |
+
load: () => load(name),
|
| 51 |
+
unload: () => unload(name),
|
| 52 |
+
size: getSize(name),
|
| 53 |
+
}))
|
| 54 |
+
book.toc = files.map(name => ({ label: name, href: name }))
|
| 55 |
+
book.rendition = { layout: 'pre-paginated' }
|
| 56 |
+
book.resolveHref = href => ({ index: book.sections.findIndex(s => s.id === href) })
|
| 57 |
+
book.splitTOCHref = href => [href, null]
|
| 58 |
+
book.getTOCFragment = doc => doc.documentElement
|
| 59 |
+
book.destroy = () => {
|
| 60 |
+
for (const arr of urls.values())
|
| 61 |
+
for (const url of arr) URL.revokeObjectURL(url)
|
| 62 |
+
}
|
| 63 |
+
return book
|
| 64 |
+
}
|
packages/foliate-js/dict.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const decoder = new TextDecoder()
|
| 2 |
+
const decode = decoder.decode.bind(decoder)
|
| 3 |
+
|
| 4 |
+
const concatTypedArray = (a, b) => {
|
| 5 |
+
const result = new a.constructor(a.length + b.length)
|
| 6 |
+
result.set(a)
|
| 7 |
+
result.set(b, a.length)
|
| 8 |
+
return result
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
const strcmp = (a, b) => {
|
| 12 |
+
a = a.toLowerCase(), b = b.toLowerCase()
|
| 13 |
+
return a < b ? -1 : a > b ? 1 : 0
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
class DictZip {
|
| 17 |
+
#chlen
|
| 18 |
+
#chunks
|
| 19 |
+
#compressed
|
| 20 |
+
inflate
|
| 21 |
+
async load(file) {
|
| 22 |
+
const header = new DataView(await file.slice(0, 12).arrayBuffer())
|
| 23 |
+
if (header.getUint8(0) !== 31 || header.getUint8(1) !== 139
|
| 24 |
+
|| header.getUint8(2) !== 8) throw new Error('Not a DictZip file')
|
| 25 |
+
const flg = header.getUint8(3)
|
| 26 |
+
if (!flg & 0b100) throw new Error('Missing FEXTRA flag')
|
| 27 |
+
|
| 28 |
+
const xlen = header.getUint16(10, true)
|
| 29 |
+
const extra = new DataView(await file.slice(12, 12 + xlen).arrayBuffer())
|
| 30 |
+
if (extra.getUint8(0) !== 82 || extra.getUint8(1) !== 65)
|
| 31 |
+
throw new Error('Subfield ID should be RA')
|
| 32 |
+
if (extra.getUint16(4, true) !== 1) throw new Error('Unsupported version')
|
| 33 |
+
|
| 34 |
+
this.#chlen = extra.getUint16(6, true)
|
| 35 |
+
const chcnt = extra.getUint16(8, true)
|
| 36 |
+
this.#chunks = []
|
| 37 |
+
for (let i = 0, chunkOffset = 0; i < chcnt; i++) {
|
| 38 |
+
const chunkSize = extra.getUint16(10 + 2 * i, true)
|
| 39 |
+
this.#chunks.push([chunkOffset, chunkSize])
|
| 40 |
+
chunkOffset = chunkOffset + chunkSize
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// skip to compressed data
|
| 44 |
+
let offset = 12 + xlen
|
| 45 |
+
const max = Math.min(offset + 512, file.size)
|
| 46 |
+
const strArr = new Uint8Array(await file.slice(0, max).arrayBuffer())
|
| 47 |
+
if (flg & 0b1000) { // fname
|
| 48 |
+
const i = strArr.indexOf(0, offset)
|
| 49 |
+
if (i < 0) throw new Error('Header too long')
|
| 50 |
+
offset = i + 1
|
| 51 |
+
}
|
| 52 |
+
if (flg & 0b10000) { // fcomment
|
| 53 |
+
const i = strArr.indexOf(0, offset)
|
| 54 |
+
if (i < 0) throw new Error('Header too long')
|
| 55 |
+
offset = i + 1
|
| 56 |
+
}
|
| 57 |
+
if (flg & 0b10) offset += 2 // fhcrc
|
| 58 |
+
this.#compressed = file.slice(offset)
|
| 59 |
+
}
|
| 60 |
+
async read(offset, size) {
|
| 61 |
+
const chunks = this.#chunks
|
| 62 |
+
const startIndex = Math.trunc(offset / this.#chlen)
|
| 63 |
+
const endIndex = Math.trunc((offset + size) / this.#chlen)
|
| 64 |
+
const buf = await this.#compressed.slice(chunks[startIndex][0],
|
| 65 |
+
chunks[endIndex][0] + chunks[endIndex][1]).arrayBuffer()
|
| 66 |
+
let arr = new Uint8Array()
|
| 67 |
+
for (let pos = 0, i = startIndex; i <= endIndex; i++) {
|
| 68 |
+
const data = new Uint8Array(buf, pos, chunks[i][1])
|
| 69 |
+
arr = concatTypedArray(arr, await this.inflate(data))
|
| 70 |
+
pos += chunks[i][1]
|
| 71 |
+
}
|
| 72 |
+
const startOffset = offset - startIndex * this.#chlen
|
| 73 |
+
return arr.subarray(startOffset, startOffset + size)
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
class Index {
|
| 78 |
+
strcmp = strcmp
|
| 79 |
+
// binary search
|
| 80 |
+
bisect(query, start = 0, end = this.words.length - 1) {
|
| 81 |
+
if (end - start === 1) {
|
| 82 |
+
if (!this.strcmp(query, this.getWord(start))) return start
|
| 83 |
+
if (!this.strcmp(query, this.getWord(end))) return end
|
| 84 |
+
return null
|
| 85 |
+
}
|
| 86 |
+
const mid = Math.floor(start + (end - start) / 2)
|
| 87 |
+
const cmp = this.strcmp(query, this.getWord(mid))
|
| 88 |
+
if (cmp < 0) return this.bisect(query, start, mid)
|
| 89 |
+
if (cmp > 0) return this.bisect(query, mid, end)
|
| 90 |
+
return mid
|
| 91 |
+
}
|
| 92 |
+
// check for multiple definitions
|
| 93 |
+
checkAdjacent(query, i) {
|
| 94 |
+
if (i == null) return []
|
| 95 |
+
let j = i
|
| 96 |
+
const equals = i => {
|
| 97 |
+
const word = this.getWord(i)
|
| 98 |
+
return word ? this.strcmp(query, word) === 0 : false
|
| 99 |
+
}
|
| 100 |
+
while (equals(j - 1)) j--
|
| 101 |
+
let k = i
|
| 102 |
+
while (equals(k + 1)) k++
|
| 103 |
+
return j === k ? [i] : Array.from({ length: k + 1 - j }, (_, i) => j + i)
|
| 104 |
+
}
|
| 105 |
+
lookup(query) {
|
| 106 |
+
return this.checkAdjacent(query, this.bisect(query))
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
const decodeBase64Number = str => {
|
| 111 |
+
const { length } = str
|
| 112 |
+
let n = 0
|
| 113 |
+
for (let i = 0; i < length; i++) {
|
| 114 |
+
const c = str.charCodeAt(i)
|
| 115 |
+
n += (c === 43 ? 62 // "+"
|
| 116 |
+
: c === 47 ? 63 // "/"
|
| 117 |
+
: c < 58 ? c + 4 // 0-9 -> 52-61
|
| 118 |
+
: c < 91 ? c - 65 // A-Z -> 0-25
|
| 119 |
+
: c - 71 // a-z -> 26-51
|
| 120 |
+
) * 64 ** (length - 1 - i)
|
| 121 |
+
}
|
| 122 |
+
return n
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
class DictdIndex extends Index {
|
| 126 |
+
getWord(i) {
|
| 127 |
+
return this.words[i]
|
| 128 |
+
}
|
| 129 |
+
async load(file) {
|
| 130 |
+
const words = []
|
| 131 |
+
const offsets = []
|
| 132 |
+
const sizes = []
|
| 133 |
+
for (const line of decode(await file.arrayBuffer()).split('\n')) {
|
| 134 |
+
const a = line.split('\t')
|
| 135 |
+
words.push(a[0])
|
| 136 |
+
offsets.push(decodeBase64Number(a[1]))
|
| 137 |
+
sizes.push(decodeBase64Number(a[2]))
|
| 138 |
+
}
|
| 139 |
+
this.words = words
|
| 140 |
+
this.offsets = offsets
|
| 141 |
+
this.sizes = sizes
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
export class DictdDict {
|
| 146 |
+
#dict = new DictZip()
|
| 147 |
+
#idx = new DictdIndex()
|
| 148 |
+
loadDict(file, inflate) {
|
| 149 |
+
this.#dict.inflate = inflate
|
| 150 |
+
return this.#dict.load(file)
|
| 151 |
+
}
|
| 152 |
+
async #readWord(i) {
|
| 153 |
+
const word = this.#idx.getWord(i)
|
| 154 |
+
const offset = this.#idx.offsets[i]
|
| 155 |
+
const size = this.#idx.sizes[i]
|
| 156 |
+
return { word, data: ['m', this.#dict.read(offset, size)] }
|
| 157 |
+
}
|
| 158 |
+
#readWords(arr) {
|
| 159 |
+
return Promise.all(arr.map(this.#readWord.bind(this)))
|
| 160 |
+
}
|
| 161 |
+
lookup(query) {
|
| 162 |
+
return this.#readWords(this.#idx.lookup(query))
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
class StarDictIndex extends Index {
|
| 167 |
+
isSyn
|
| 168 |
+
#arr
|
| 169 |
+
getWord(i) {
|
| 170 |
+
const word = this.words[i]
|
| 171 |
+
if (!word) return
|
| 172 |
+
return decode(this.#arr.subarray(word[0], word[1]))
|
| 173 |
+
}
|
| 174 |
+
async load(file) {
|
| 175 |
+
const { isSyn } = this
|
| 176 |
+
const buf = await file.arrayBuffer()
|
| 177 |
+
const arr = new Uint8Array(buf)
|
| 178 |
+
this.#arr = arr
|
| 179 |
+
const view = new DataView(buf)
|
| 180 |
+
const words = []
|
| 181 |
+
const offsets = []
|
| 182 |
+
const sizes = []
|
| 183 |
+
for (let i = 0; i < arr.length;) {
|
| 184 |
+
const newI = arr.subarray(0, i + 256).indexOf(0, i)
|
| 185 |
+
if (newI < 0) throw new Error('Word too big')
|
| 186 |
+
words.push([i, newI])
|
| 187 |
+
offsets.push(view.getUint32(newI + 1))
|
| 188 |
+
if (isSyn) i = newI + 5
|
| 189 |
+
else {
|
| 190 |
+
sizes.push(view.getUint32(newI + 5))
|
| 191 |
+
i = newI + 9
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
this.words = words
|
| 195 |
+
this.offsets = offsets
|
| 196 |
+
this.sizes = sizes
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
export class StarDict {
|
| 201 |
+
#dict = new DictZip()
|
| 202 |
+
#idx = new StarDictIndex()
|
| 203 |
+
#syn = Object.assign(new StarDictIndex(), { isSyn: true })
|
| 204 |
+
async loadIfo(file) {
|
| 205 |
+
const str = decode(await file.arrayBuffer())
|
| 206 |
+
this.ifo = Object.fromEntries(str.split('\n').map(line => {
|
| 207 |
+
const sep = line.indexOf('=')
|
| 208 |
+
if (sep < 0) return
|
| 209 |
+
return [line.slice(0, sep), line.slice(sep + 1)]
|
| 210 |
+
}).filter(x => x))
|
| 211 |
+
}
|
| 212 |
+
loadDict(file, inflate) {
|
| 213 |
+
this.#dict.inflate = inflate
|
| 214 |
+
return this.#dict.load(file)
|
| 215 |
+
}
|
| 216 |
+
loadIdx(file) {
|
| 217 |
+
return this.#idx.load(file)
|
| 218 |
+
}
|
| 219 |
+
loadSyn(file) {
|
| 220 |
+
if (file) return this.#syn.load(file)
|
| 221 |
+
}
|
| 222 |
+
async #readWord(i) {
|
| 223 |
+
const word = this.#idx.getWord(i)
|
| 224 |
+
const offset = this.#idx.offsets[i]
|
| 225 |
+
const size = this.#idx.sizes[i]
|
| 226 |
+
const data = await this.#dict.read(offset, size)
|
| 227 |
+
const seq = this.ifo.sametypesequence
|
| 228 |
+
if (!seq) throw new Error('TODO')
|
| 229 |
+
if (seq.length === 1) return { word, data: [[seq[0], data]] }
|
| 230 |
+
throw new Error('TODO')
|
| 231 |
+
}
|
| 232 |
+
#readWords(arr) {
|
| 233 |
+
return Promise.all(arr.map(this.#readWord.bind(this)))
|
| 234 |
+
}
|
| 235 |
+
lookup(query) {
|
| 236 |
+
return this.#readWords(this.#idx.lookup(query))
|
| 237 |
+
}
|
| 238 |
+
synonyms(query) {
|
| 239 |
+
return this.#readWords(this.#syn.lookup(query).map(i => this.#syn.offsets[i]))
|
| 240 |
+
}
|
| 241 |
+
}
|
packages/foliate-js/epub.js
ADDED
|
@@ -0,0 +1,1374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as CFI from './epubcfi.js'
|
| 2 |
+
|
| 3 |
+
const NS = {
|
| 4 |
+
CONTAINER: 'urn:oasis:names:tc:opendocument:xmlns:container',
|
| 5 |
+
XHTML: 'http://www.w3.org/1999/xhtml',
|
| 6 |
+
OPF: 'http://www.idpf.org/2007/opf',
|
| 7 |
+
EPUB: 'http://www.idpf.org/2007/ops',
|
| 8 |
+
DC: 'http://purl.org/dc/elements/1.1/',
|
| 9 |
+
DCTERMS: 'http://purl.org/dc/terms/',
|
| 10 |
+
ENC: 'http://www.w3.org/2001/04/xmlenc#',
|
| 11 |
+
NCX: 'http://www.daisy.org/z3986/2005/ncx/',
|
| 12 |
+
XLINK: 'http://www.w3.org/1999/xlink',
|
| 13 |
+
SMIL: 'http://www.w3.org/ns/SMIL',
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
const MIME = {
|
| 17 |
+
XML: 'application/xml',
|
| 18 |
+
NCX: 'application/x-dtbncx+xml',
|
| 19 |
+
XHTML: 'application/xhtml+xml',
|
| 20 |
+
HTML: 'text/html',
|
| 21 |
+
CSS: 'text/css',
|
| 22 |
+
SVG: 'image/svg+xml',
|
| 23 |
+
JS: /\/(x-)?(javascript|ecmascript)/,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// https://www.w3.org/TR/epub-33/#sec-reserved-prefixes
|
| 27 |
+
const PREFIX = {
|
| 28 |
+
a11y: 'http://www.idpf.org/epub/vocab/package/a11y/#',
|
| 29 |
+
dcterms: 'http://purl.org/dc/terms/',
|
| 30 |
+
marc: 'http://id.loc.gov/vocabulary/',
|
| 31 |
+
media: 'http://www.idpf.org/epub/vocab/overlays/#',
|
| 32 |
+
onix: 'http://www.editeur.org/ONIX/book/codelists/current.html#',
|
| 33 |
+
rendition: 'http://www.idpf.org/vocab/rendition/#',
|
| 34 |
+
schema: 'http://schema.org/',
|
| 35 |
+
xsd: 'http://www.w3.org/2001/XMLSchema#',
|
| 36 |
+
msv: 'http://www.idpf.org/epub/vocab/structure/magazine/#',
|
| 37 |
+
prism: 'http://www.prismstandard.org/specifications/3.0/PRISM_CV_Spec_3.0.htm#',
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
const RELATORS = {
|
| 41 |
+
art: 'artist',
|
| 42 |
+
aut: 'author',
|
| 43 |
+
clr: 'colorist',
|
| 44 |
+
edt: 'editor',
|
| 45 |
+
ill: 'illustrator',
|
| 46 |
+
nrt: 'narrator',
|
| 47 |
+
trl: 'translator',
|
| 48 |
+
pbl: 'publisher',
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
const ONIX5 = {
|
| 52 |
+
'02': 'isbn',
|
| 53 |
+
'06': 'doi',
|
| 54 |
+
'15': 'isbn',
|
| 55 |
+
'26': 'doi',
|
| 56 |
+
'34': 'issn',
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// convert to camel case
|
| 60 |
+
const camel = x => x.toLowerCase().replace(/[-:](.)/g, (_, g) => g.toUpperCase())
|
| 61 |
+
|
| 62 |
+
// strip and collapse ASCII whitespace
|
| 63 |
+
// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
|
| 64 |
+
const normalizeWhitespace = str => str ? str
|
| 65 |
+
.replace(/[\t\n\f\r ]+/g, ' ')
|
| 66 |
+
.replace(/^[\t\n\f\r ]+/, '')
|
| 67 |
+
.replace(/[\t\n\f\r ]+$/, '') : ''
|
| 68 |
+
|
| 69 |
+
const filterAttribute = (attr, value, isList) => isList
|
| 70 |
+
? el => el.getAttribute(attr)?.split(/\s/)?.includes(value)
|
| 71 |
+
: typeof value === 'function'
|
| 72 |
+
? el => value(el.getAttribute(attr))
|
| 73 |
+
: el => el.getAttribute(attr) === value
|
| 74 |
+
|
| 75 |
+
const getAttributes = (...xs) => el =>
|
| 76 |
+
el ? Object.fromEntries(xs.map(x => [camel(x), el.getAttribute(x)])) : null
|
| 77 |
+
|
| 78 |
+
const getElementText = el => normalizeWhitespace(el?.textContent)
|
| 79 |
+
|
| 80 |
+
const childGetter = (doc, ns) => {
|
| 81 |
+
// ignore the namespace if it doesn't appear in document at all
|
| 82 |
+
const useNS = doc.lookupNamespaceURI(null) === ns || doc.lookupPrefix(ns)
|
| 83 |
+
const f = useNS
|
| 84 |
+
? (el, name) => el => el.namespaceURI === ns && el.localName === name
|
| 85 |
+
: (el, name) => el => el.localName === name
|
| 86 |
+
return {
|
| 87 |
+
$: (el, name) => [...el.children].find(f(el, name)),
|
| 88 |
+
$$: (el, name) => [...el.children].filter(f(el, name)),
|
| 89 |
+
$$$: useNS
|
| 90 |
+
? (el, name) => [...el.getElementsByTagNameNS(ns, name)]
|
| 91 |
+
: (el, name) => [...el.getElementsByTagName(name)],
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
const resolveURL = (url, relativeTo) => {
|
| 96 |
+
try {
|
| 97 |
+
// replace %2c in the url with a comma, this might be introduced by calibre
|
| 98 |
+
url = url.replace(/%2c/gi, ',').replace(/%3a/gi, ':')
|
| 99 |
+
if (relativeTo.includes(':') && !relativeTo.startsWith('OEBPS')) return new URL(url, relativeTo)
|
| 100 |
+
// the base needs to be a valid URL, so set a base URL and then remove it
|
| 101 |
+
const root = 'https://invalid.invalid/'
|
| 102 |
+
const obj = new URL(url, root + relativeTo)
|
| 103 |
+
obj.search = ''
|
| 104 |
+
return decodeURI(obj.href.replace(root, ''))
|
| 105 |
+
} catch(e) {
|
| 106 |
+
console.warn(e)
|
| 107 |
+
return url
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const isExternal = uri => /^(?!blob)\w+:/i.test(uri)
|
| 112 |
+
|
| 113 |
+
// like `path.relative()` in Node.js
|
| 114 |
+
const pathRelative = (from, to) => {
|
| 115 |
+
if (!from) return to
|
| 116 |
+
const as = from.replace(/\/$/, '').split('/')
|
| 117 |
+
const bs = to.replace(/\/$/, '').split('/')
|
| 118 |
+
const i = (as.length > bs.length ? as : bs).findIndex((_, i) => as[i] !== bs[i])
|
| 119 |
+
return i < 0 ? '' : Array(as.length - i).fill('..').concat(bs.slice(i)).join('/')
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
const pathDirname = str => str.slice(0, str.lastIndexOf('/') + 1)
|
| 123 |
+
|
| 124 |
+
// replace asynchronously and sequentially
|
| 125 |
+
// same technique as https://stackoverflow.com/a/48032528
|
| 126 |
+
const replaceSeries = async (str, regex, f) => {
|
| 127 |
+
const matches = []
|
| 128 |
+
str.replace(regex, (...args) => (matches.push(args), null))
|
| 129 |
+
const results = []
|
| 130 |
+
for (const args of matches) results.push(await f(...args))
|
| 131 |
+
return str.replace(regex, () => results.shift())
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
const regexEscape = str => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
|
| 135 |
+
|
| 136 |
+
const tidy = obj => {
|
| 137 |
+
for (const [key, val] of Object.entries(obj))
|
| 138 |
+
if (val == null) delete obj[key]
|
| 139 |
+
else if (Array.isArray(val)) {
|
| 140 |
+
obj[key] = val.filter(x => x).map(x =>
|
| 141 |
+
typeof x === 'object' && !Array.isArray(x) ? tidy(x) : x)
|
| 142 |
+
if (!obj[key].length) delete obj[key]
|
| 143 |
+
else if (obj[key].length === 1) obj[key] = obj[key][0]
|
| 144 |
+
}
|
| 145 |
+
else if (typeof val === 'object') {
|
| 146 |
+
obj[key] = tidy(val)
|
| 147 |
+
if (!Object.keys(val).length) delete obj[key]
|
| 148 |
+
}
|
| 149 |
+
const keys = Object.keys(obj)
|
| 150 |
+
if (keys.length === 1 && keys[0] === 'name') return obj[keys[0]]
|
| 151 |
+
return obj
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// https://www.w3.org/TR/epub/#sec-prefix-attr
|
| 155 |
+
const getPrefixes = doc => {
|
| 156 |
+
const map = new Map(Object.entries(PREFIX))
|
| 157 |
+
const value = doc.documentElement.getAttributeNS(NS.EPUB, 'prefix')
|
| 158 |
+
|| doc.documentElement.getAttribute('prefix')
|
| 159 |
+
if (value) for (const [, prefix, url] of value
|
| 160 |
+
.matchAll(/(.+): +(.+)[ \t\r\n]*/g)) map.set(prefix, url)
|
| 161 |
+
return map
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
// https://www.w3.org/TR/epub-rs/#sec-property-values
|
| 165 |
+
// but ignoring the case where the prefix is omitted
|
| 166 |
+
const getPropertyURL = (value, prefixes) => {
|
| 167 |
+
if (!value) return null
|
| 168 |
+
const [a, b] = value.split(':')
|
| 169 |
+
const prefix = b ? a : null
|
| 170 |
+
const reference = b ? b : a
|
| 171 |
+
const baseURL = prefixes.get(prefix)
|
| 172 |
+
return baseURL ? baseURL + reference : null
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
const getMetadata = opf => {
|
| 176 |
+
const { $ } = childGetter(opf, NS.OPF)
|
| 177 |
+
const $metadata = $(opf.documentElement, 'metadata')
|
| 178 |
+
|
| 179 |
+
// first pass: convert to JS objects
|
| 180 |
+
const els = Object.groupBy($metadata.children, el =>
|
| 181 |
+
el.namespaceURI === NS.DC ? 'dc'
|
| 182 |
+
: el.namespaceURI === NS.OPF && el.localName === 'meta' ?
|
| 183 |
+
(el.hasAttribute('name') ? 'legacyMeta' : 'meta') : '')
|
| 184 |
+
const baseLang = $metadata.getAttribute('xml:lang')
|
| 185 |
+
?? opf.documentElement.getAttribute('xml:lang') ?? 'und'
|
| 186 |
+
const prefixes = getPrefixes(opf)
|
| 187 |
+
const parse = el => {
|
| 188 |
+
const property = el.getAttribute('property')
|
| 189 |
+
const scheme = el.getAttribute('scheme')
|
| 190 |
+
return {
|
| 191 |
+
property: getPropertyURL(property, prefixes) ?? property,
|
| 192 |
+
scheme: getPropertyURL(scheme, prefixes) ?? scheme,
|
| 193 |
+
lang: el.getAttribute('xml:lang'),
|
| 194 |
+
value: getElementText(el),
|
| 195 |
+
props: getProperties(el),
|
| 196 |
+
// `opf:` attributes from EPUB 2 & EPUB 3.1 (removed in EPUB 3.2)
|
| 197 |
+
attrs: Object.fromEntries(Array.from(el.attributes)
|
| 198 |
+
.filter(attr => attr.namespaceURI === NS.OPF)
|
| 199 |
+
.map(attr => [attr.localName, attr.value])),
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
const refines = Map.groupBy(els.meta ?? [], el => el.getAttribute('refines'))
|
| 203 |
+
const getProperties = el => {
|
| 204 |
+
const els = refines.get(el ? '#' + el.getAttribute('id') : null)
|
| 205 |
+
if (!els) return null
|
| 206 |
+
return Object.groupBy(els.map(parse), x => x.property)
|
| 207 |
+
}
|
| 208 |
+
const dc = Object.fromEntries(Object.entries(Object.groupBy(els.dc || [], el => el.localName))
|
| 209 |
+
.map(([name, els]) => [name, els.map(parse)]))
|
| 210 |
+
const properties = getProperties() ?? {}
|
| 211 |
+
const legacyMeta = Object.fromEntries(els.legacyMeta?.map(el =>
|
| 212 |
+
[el.getAttribute('name'), el.getAttribute('content')]) ?? [])
|
| 213 |
+
|
| 214 |
+
// second pass: map to webpub
|
| 215 |
+
const one = x => x?.[0]?.value
|
| 216 |
+
const prop = (x, p) => one(x?.props?.[p])
|
| 217 |
+
const makeLanguageMap = x => {
|
| 218 |
+
if (!x) return null
|
| 219 |
+
const alts = x.props?.['alternate-script'] ?? []
|
| 220 |
+
const altRep = x.attrs['alt-rep']
|
| 221 |
+
if (!alts.length && (!x.lang || x.lang === baseLang) && !altRep) return x.value
|
| 222 |
+
const map = { [x.lang ?? baseLang]: x.value }
|
| 223 |
+
if (altRep) map[x.attrs['alt-rep-lang']] = altRep
|
| 224 |
+
for (const y of alts) map[y.lang] ??= y.value
|
| 225 |
+
return map
|
| 226 |
+
}
|
| 227 |
+
const makeContributor = x => x ? ({
|
| 228 |
+
name: makeLanguageMap(x),
|
| 229 |
+
sortAs: makeLanguageMap(x.props?.['file-as']?.[0]) ?? x.attrs['file-as'],
|
| 230 |
+
role: x.props?.role?.filter(x => x.scheme === PREFIX.marc + 'relators')
|
| 231 |
+
?.map(x => x.value) ?? [x.attrs.role],
|
| 232 |
+
code: prop(x, 'term') ?? x.attrs.term,
|
| 233 |
+
scheme: prop(x, 'authority') ?? x.attrs.authority,
|
| 234 |
+
}) : null
|
| 235 |
+
const makeCollection = x => ({
|
| 236 |
+
name: makeLanguageMap(x),
|
| 237 |
+
// NOTE: webpub requires number but EPUB allows values like "2.2.1"
|
| 238 |
+
position: one(x.props?.['group-position']),
|
| 239 |
+
})
|
| 240 |
+
const makeSeries = x => ({
|
| 241 |
+
name: x.value,
|
| 242 |
+
position: one(x.props?.['group-position']),
|
| 243 |
+
})
|
| 244 |
+
const makeAltIdentifier = x => {
|
| 245 |
+
const { value } = x
|
| 246 |
+
if (/^urn:/i.test(value)) return value
|
| 247 |
+
if (/^doi:/i.test(value)) return `urn:${value}`
|
| 248 |
+
const type = x.props?.['identifier-type']
|
| 249 |
+
if (!type) {
|
| 250 |
+
const scheme = x.attrs.scheme
|
| 251 |
+
if (!scheme) return value
|
| 252 |
+
// https://idpf.github.io/epub-registries/identifiers/
|
| 253 |
+
// but no "jdcn", which isn't a registered URN namespace
|
| 254 |
+
if (/^(doi|isbn|uuid)$/i.test(scheme)) return `urn:${scheme}:${value}`
|
| 255 |
+
// NOTE: webpub requires scheme to be a URI; EPUB allows anything
|
| 256 |
+
return { scheme, value }
|
| 257 |
+
}
|
| 258 |
+
if (type.scheme === PREFIX.onix + 'codelist5') {
|
| 259 |
+
const nid = ONIX5[type.value]
|
| 260 |
+
if (nid) return `urn:${nid}:${value}`
|
| 261 |
+
}
|
| 262 |
+
return value
|
| 263 |
+
}
|
| 264 |
+
const belongsTo = Object.groupBy(properties['belongs-to-collection'] ?? [],
|
| 265 |
+
x => prop(x, 'collection-type') === 'series' ? 'series' : 'collection')
|
| 266 |
+
const mainTitle = dc.title?.find(x => prop(x, 'title-type') === 'main') ?? dc.title?.[0]
|
| 267 |
+
const metadata = {
|
| 268 |
+
identifier: getIdentifier(opf),
|
| 269 |
+
title: makeLanguageMap(mainTitle),
|
| 270 |
+
sortAs: makeLanguageMap(mainTitle?.props?.['file-as']?.[0])
|
| 271 |
+
?? mainTitle?.attrs?.['file-as']
|
| 272 |
+
?? legacyMeta?.['calibre:title_sort'],
|
| 273 |
+
subtitle: dc.title?.find(x => prop(x, 'title-type') === 'subtitle')?.value,
|
| 274 |
+
language: dc.language?.map(x => x.value),
|
| 275 |
+
description: one(dc.description),
|
| 276 |
+
publisher: makeContributor(dc.publisher?.[0]),
|
| 277 |
+
published: dc.date?.find(x => x.attrs.event === 'publication')?.value
|
| 278 |
+
?? one(dc.date),
|
| 279 |
+
modified: one(properties[PREFIX.dcterms + 'modified'])
|
| 280 |
+
?? dc.date?.find(x => x.attrs.event === 'modification')?.value,
|
| 281 |
+
subject: dc.subject?.map(makeContributor),
|
| 282 |
+
belongsTo: {
|
| 283 |
+
collection: belongsTo.collection?.map(makeCollection),
|
| 284 |
+
series: belongsTo.series?.map(makeSeries)
|
| 285 |
+
?? (legacyMeta?.['calibre:series'] ? {
|
| 286 |
+
name: legacyMeta?.['calibre:series'],
|
| 287 |
+
position: parseFloat(legacyMeta?.['calibre:series_index']),
|
| 288 |
+
} : null),
|
| 289 |
+
},
|
| 290 |
+
altIdentifier: dc.identifier?.map(makeAltIdentifier),
|
| 291 |
+
source: dc.source?.map(makeAltIdentifier), // NOTE: not in webpub schema
|
| 292 |
+
rights: one(dc.rights), // NOTE: not in webpub schema
|
| 293 |
+
}
|
| 294 |
+
const remapContributor = defaultKey => x => {
|
| 295 |
+
const keys = new Set(x.role?.map(role => RELATORS[role] ?? defaultKey))
|
| 296 |
+
return [keys.size ? keys : [defaultKey], x]
|
| 297 |
+
}
|
| 298 |
+
for (const [keys, val] of [].concat(
|
| 299 |
+
dc.creator?.map(makeContributor)?.map(remapContributor('author')) ?? [],
|
| 300 |
+
dc.contributor?.map(makeContributor)?.map(remapContributor('contributor')) ?? []))
|
| 301 |
+
for (const key of keys) {
|
| 302 |
+
// if already parsed publisher don't remap it from author/contributor again
|
| 303 |
+
if (key === 'publisher' && metadata.publisher) continue
|
| 304 |
+
if (metadata[key]) metadata[key].push(val)
|
| 305 |
+
else metadata[key] = [val]
|
| 306 |
+
}
|
| 307 |
+
tidy(metadata)
|
| 308 |
+
if (metadata.altIdentifier === metadata.identifier)
|
| 309 |
+
delete metadata.altIdentifier
|
| 310 |
+
|
| 311 |
+
const rendition = {}
|
| 312 |
+
const media = {}
|
| 313 |
+
for (const [key, val] of Object.entries(properties)) {
|
| 314 |
+
if (key.startsWith(PREFIX.rendition))
|
| 315 |
+
rendition[camel(key.replace(PREFIX.rendition, ''))] = one(val)
|
| 316 |
+
else if (key.startsWith(PREFIX.media))
|
| 317 |
+
media[camel(key.replace(PREFIX.media, ''))] = one(val)
|
| 318 |
+
}
|
| 319 |
+
if (media.duration) media.duration = parseClock(media.duration)
|
| 320 |
+
return { metadata, rendition, media }
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
const parseNav = (doc, resolve = f => f) => {
|
| 324 |
+
const { $, $$, $$$ } = childGetter(doc, NS.XHTML)
|
| 325 |
+
const resolveHref = href => href ? decodeURI(resolve(href)) : null
|
| 326 |
+
const parseLI = getType => $li => {
|
| 327 |
+
const $a = $($li, 'a') ?? $($li, 'span')
|
| 328 |
+
const $ol = $($li, 'ol')
|
| 329 |
+
const href = resolveHref($a?.getAttribute('href'))
|
| 330 |
+
const label = getElementText($a) || $a?.getAttribute('title')
|
| 331 |
+
// TODO: get and concat alt/title texts in content
|
| 332 |
+
const result = { label, href, subitems: parseOL($ol) }
|
| 333 |
+
if (getType) result.type = $a?.getAttributeNS(NS.EPUB, 'type')?.split(/\s/)
|
| 334 |
+
return result
|
| 335 |
+
}
|
| 336 |
+
const parseOL = ($ol, getType) => $ol ? $$($ol, 'li').map(parseLI(getType)) : null
|
| 337 |
+
const parseNav = ($nav, getType) => parseOL($($nav, 'ol'), getType)
|
| 338 |
+
|
| 339 |
+
const $$nav = $$$(doc, 'nav')
|
| 340 |
+
let toc = null, pageList = null, landmarks = null, others = []
|
| 341 |
+
for (const $nav of $$nav) {
|
| 342 |
+
const type = $nav.getAttributeNS(NS.EPUB, 'type')?.split(/\s/) ?? []
|
| 343 |
+
if (type.includes('toc')) toc ??= parseNav($nav)
|
| 344 |
+
else if (type.includes('page-list')) pageList ??= parseNav($nav)
|
| 345 |
+
else if (type.includes('landmarks')) landmarks ??= parseNav($nav, true)
|
| 346 |
+
else others.push({
|
| 347 |
+
label: getElementText($nav.firstElementChild), type,
|
| 348 |
+
list: parseNav($nav),
|
| 349 |
+
})
|
| 350 |
+
}
|
| 351 |
+
return { toc, pageList, landmarks, others }
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
const parseNCX = (doc, resolve = f => f) => {
|
| 355 |
+
const { $, $$ } = childGetter(doc, NS.NCX)
|
| 356 |
+
const resolveHref = href => href ? decodeURI(resolve(href)) : null
|
| 357 |
+
const parseItem = el => {
|
| 358 |
+
const $label = $(el, 'navLabel')
|
| 359 |
+
const $content = $(el, 'content')
|
| 360 |
+
const label = getElementText($label)
|
| 361 |
+
const href = resolveHref($content.getAttribute('src'))
|
| 362 |
+
if (el.localName === 'navPoint') {
|
| 363 |
+
const els = $$(el, 'navPoint')
|
| 364 |
+
return { label, href, subitems: els.length ? els.map(parseItem) : null }
|
| 365 |
+
}
|
| 366 |
+
return { label, href }
|
| 367 |
+
}
|
| 368 |
+
const parseList = (el, itemName) => $$(el, itemName).map(parseItem)
|
| 369 |
+
const getSingle = (container, itemName) => {
|
| 370 |
+
const $container = $(doc.documentElement, container)
|
| 371 |
+
return $container ? parseList($container, itemName) : null
|
| 372 |
+
}
|
| 373 |
+
return {
|
| 374 |
+
toc: getSingle('navMap', 'navPoint'),
|
| 375 |
+
pageList: getSingle('pageList', 'pageTarget'),
|
| 376 |
+
others: $$(doc.documentElement, 'navList').map(el => ({
|
| 377 |
+
label: getElementText($(el, 'navLabel')),
|
| 378 |
+
list: parseList(el, 'navTarget'),
|
| 379 |
+
})),
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
const parseClock = str => {
|
| 384 |
+
if (!str) return
|
| 385 |
+
const parts = str.split(':').map(x => parseFloat(x))
|
| 386 |
+
if (parts.length === 3) {
|
| 387 |
+
const [h, m, s] = parts
|
| 388 |
+
return h * 60 * 60 + m * 60 + s
|
| 389 |
+
}
|
| 390 |
+
if (parts.length === 2) {
|
| 391 |
+
const [m, s] = parts
|
| 392 |
+
return m * 60 + s
|
| 393 |
+
}
|
| 394 |
+
const [x, unit] = str.split(/(?=[^\d.])/)
|
| 395 |
+
const n = parseFloat(x)
|
| 396 |
+
const f = unit === 'h' ? 60 * 60
|
| 397 |
+
: unit === 'min' ? 60
|
| 398 |
+
: unit === 'ms' ? .001
|
| 399 |
+
: 1
|
| 400 |
+
return n * f
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp']
|
| 404 |
+
|
| 405 |
+
const getImageMediaType = (path) => {
|
| 406 |
+
const extension = path.toLowerCase().split('.').pop()
|
| 407 |
+
const mediaTypeMap = {
|
| 408 |
+
'jpg': 'image/jpeg',
|
| 409 |
+
'jpeg': 'image/jpeg',
|
| 410 |
+
'png': 'image/png',
|
| 411 |
+
'gif': 'image/gif',
|
| 412 |
+
'webp': 'image/webp',
|
| 413 |
+
}
|
| 414 |
+
return mediaTypeMap[extension] || 'image/jpeg'
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
class MediaOverlay extends EventTarget {
|
| 418 |
+
#entries
|
| 419 |
+
#lastMediaOverlayItem
|
| 420 |
+
#sectionIndex
|
| 421 |
+
#audioIndex
|
| 422 |
+
#itemIndex
|
| 423 |
+
#audio
|
| 424 |
+
#volume = 1
|
| 425 |
+
#rate = 1
|
| 426 |
+
#state
|
| 427 |
+
constructor(book, loadXML) {
|
| 428 |
+
super()
|
| 429 |
+
this.book = book
|
| 430 |
+
this.loadXML = loadXML
|
| 431 |
+
}
|
| 432 |
+
async #loadSMIL(item) {
|
| 433 |
+
if (this.#lastMediaOverlayItem === item) return
|
| 434 |
+
const doc = await this.loadXML(item.href)
|
| 435 |
+
const resolve = href => href ? resolveURL(href, item.href) : null
|
| 436 |
+
const { $, $$$ } = childGetter(doc, NS.SMIL)
|
| 437 |
+
this.#audioIndex = -1
|
| 438 |
+
this.#itemIndex = -1
|
| 439 |
+
this.#entries = $$$(doc, 'par').reduce((arr, $par) => {
|
| 440 |
+
const text = resolve($($par, 'text')?.getAttribute('src'))
|
| 441 |
+
const $audio = $($par, 'audio')
|
| 442 |
+
if (!text || !$audio) return arr
|
| 443 |
+
const src = resolve($audio.getAttribute('src'))
|
| 444 |
+
const begin = parseClock($audio.getAttribute('clipBegin'))
|
| 445 |
+
const end = parseClock($audio.getAttribute('clipEnd'))
|
| 446 |
+
const last = arr.at(-1)
|
| 447 |
+
if (last?.src === src) last.items.push({ text, begin, end })
|
| 448 |
+
else arr.push({ src, items: [{ text, begin, end }] })
|
| 449 |
+
return arr
|
| 450 |
+
}, [])
|
| 451 |
+
this.#lastMediaOverlayItem = item
|
| 452 |
+
}
|
| 453 |
+
get #activeAudio() {
|
| 454 |
+
return this.#entries[this.#audioIndex]
|
| 455 |
+
}
|
| 456 |
+
get #activeItem() {
|
| 457 |
+
return this.#activeAudio?.items?.[this.#itemIndex]
|
| 458 |
+
}
|
| 459 |
+
#error(e) {
|
| 460 |
+
console.error(e)
|
| 461 |
+
this.dispatchEvent(new CustomEvent('error', { detail: e }))
|
| 462 |
+
}
|
| 463 |
+
#highlight() {
|
| 464 |
+
this.dispatchEvent(new CustomEvent('highlight', { detail: this.#activeItem }))
|
| 465 |
+
}
|
| 466 |
+
#unhighlight() {
|
| 467 |
+
this.dispatchEvent(new CustomEvent('unhighlight', { detail: this.#activeItem }))
|
| 468 |
+
}
|
| 469 |
+
async #play(audioIndex, itemIndex) {
|
| 470 |
+
this.#stop()
|
| 471 |
+
this.#audioIndex = audioIndex
|
| 472 |
+
this.#itemIndex = itemIndex
|
| 473 |
+
const src = this.#activeAudio?.src
|
| 474 |
+
if (!src || !this.#activeItem) return this.start(this.#sectionIndex + 1)
|
| 475 |
+
|
| 476 |
+
const url = URL.createObjectURL(await this.book.loadBlob(src))
|
| 477 |
+
const audio = new Audio(url)
|
| 478 |
+
this.#audio = audio
|
| 479 |
+
audio.volume = this.#volume
|
| 480 |
+
audio.playbackRate = this.#rate
|
| 481 |
+
audio.addEventListener('timeupdate', () => {
|
| 482 |
+
if (audio.paused) return
|
| 483 |
+
const t = audio.currentTime
|
| 484 |
+
const { items } = this.#activeAudio
|
| 485 |
+
if (t > this.#activeItem?.end) {
|
| 486 |
+
this.#unhighlight()
|
| 487 |
+
if (this.#itemIndex === items.length - 1) {
|
| 488 |
+
this.#play(this.#audioIndex + 1, 0).catch(e => this.#error(e))
|
| 489 |
+
return
|
| 490 |
+
}
|
| 491 |
+
}
|
| 492 |
+
const oldIndex = this.#itemIndex
|
| 493 |
+
while (items[this.#itemIndex + 1]?.begin <= t) this.#itemIndex++
|
| 494 |
+
if (this.#itemIndex !== oldIndex) this.#highlight()
|
| 495 |
+
})
|
| 496 |
+
audio.addEventListener('error', () =>
|
| 497 |
+
this.#error(new Error(`Failed to load ${src}`)))
|
| 498 |
+
audio.addEventListener('playing', () => this.#highlight())
|
| 499 |
+
audio.addEventListener('ended', () => {
|
| 500 |
+
this.#unhighlight()
|
| 501 |
+
URL.revokeObjectURL(url)
|
| 502 |
+
this.#audio = null
|
| 503 |
+
this.#play(audioIndex + 1, 0).catch(e => this.#error(e))
|
| 504 |
+
})
|
| 505 |
+
if (this.#state === 'paused') {
|
| 506 |
+
this.#highlight()
|
| 507 |
+
audio.currentTime = this.#activeItem.begin ?? 0
|
| 508 |
+
}
|
| 509 |
+
else audio.addEventListener('canplaythrough', () => {
|
| 510 |
+
// for some reason need to seek in `canplaythrough`
|
| 511 |
+
// or it won't play when skipping in WebKit
|
| 512 |
+
audio.currentTime = this.#activeItem.begin ?? 0
|
| 513 |
+
this.#state = 'playing'
|
| 514 |
+
audio.play().catch(e => this.#error(e))
|
| 515 |
+
}, { once: true })
|
| 516 |
+
}
|
| 517 |
+
async start(sectionIndex, filter = () => true) {
|
| 518 |
+
this.#audio?.pause()
|
| 519 |
+
const section = this.book.sections[sectionIndex]
|
| 520 |
+
const href = section?.id
|
| 521 |
+
if (!href) return
|
| 522 |
+
|
| 523 |
+
const { mediaOverlay } = section
|
| 524 |
+
if (!mediaOverlay) return this.start(sectionIndex + 1)
|
| 525 |
+
this.#sectionIndex = sectionIndex
|
| 526 |
+
await this.#loadSMIL(mediaOverlay)
|
| 527 |
+
|
| 528 |
+
for (let i = 0; i < this.#entries.length; i++) {
|
| 529 |
+
const { items } = this.#entries[i]
|
| 530 |
+
for (let j = 0; j < items.length; j++) {
|
| 531 |
+
if (items[j].text.split('#')[0] === href && filter(items[j], j, items))
|
| 532 |
+
return this.#play(i, j).catch(e => this.#error(e))
|
| 533 |
+
}
|
| 534 |
+
}
|
| 535 |
+
}
|
| 536 |
+
pause() {
|
| 537 |
+
this.#state = 'paused'
|
| 538 |
+
this.#audio?.pause()
|
| 539 |
+
}
|
| 540 |
+
resume() {
|
| 541 |
+
this.#state = 'playing'
|
| 542 |
+
this.#audio?.play().catch(e => this.#error(e))
|
| 543 |
+
}
|
| 544 |
+
#stop() {
|
| 545 |
+
if (this.#audio) {
|
| 546 |
+
this.#audio.pause()
|
| 547 |
+
URL.revokeObjectURL(this.#audio.src)
|
| 548 |
+
this.#audio = null
|
| 549 |
+
this.#unhighlight()
|
| 550 |
+
}
|
| 551 |
+
}
|
| 552 |
+
stop() {
|
| 553 |
+
this.#state = 'stopped'
|
| 554 |
+
this.#stop()
|
| 555 |
+
}
|
| 556 |
+
prev() {
|
| 557 |
+
if (this.#itemIndex > 0) this.#play(this.#audioIndex, this.#itemIndex - 1)
|
| 558 |
+
else if (this.#audioIndex > 0) this.#play(this.#audioIndex - 1,
|
| 559 |
+
this.#entries[this.#audioIndex - 1].items.length - 1)
|
| 560 |
+
else if (this.#sectionIndex > 0)
|
| 561 |
+
this.start(this.#sectionIndex - 1, (_, i, items) => i === items.length - 1)
|
| 562 |
+
}
|
| 563 |
+
next() {
|
| 564 |
+
this.#play(this.#audioIndex, this.#itemIndex + 1)
|
| 565 |
+
}
|
| 566 |
+
setVolume(volume) {
|
| 567 |
+
this.#volume = volume
|
| 568 |
+
if (this.#audio) this.#audio.volume = volume
|
| 569 |
+
}
|
| 570 |
+
setRate(rate) {
|
| 571 |
+
this.#rate = rate
|
| 572 |
+
if (this.#audio) this.#audio.playbackRate = rate
|
| 573 |
+
}
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
const isUUID = /([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/
|
| 577 |
+
|
| 578 |
+
const getUUID = opf => {
|
| 579 |
+
for (const el of opf.getElementsByTagNameNS(NS.DC, 'identifier')) {
|
| 580 |
+
const [id] = getElementText(el).split(':').slice(-1)
|
| 581 |
+
if (isUUID.test(id)) return id
|
| 582 |
+
}
|
| 583 |
+
return ''
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
const getIdentifier = opf => getElementText(
|
| 587 |
+
opf.getElementById(opf.documentElement.getAttribute('unique-identifier'))
|
| 588 |
+
?? opf.getElementsByTagNameNS(NS.DC, 'identifier')[0])
|
| 589 |
+
|
| 590 |
+
// https://www.w3.org/publishing/epub32/epub-ocf.html#sec-resource-obfuscation
|
| 591 |
+
const deobfuscate = async (key, length, blob) => {
|
| 592 |
+
const array = new Uint8Array(await blob.slice(0, length).arrayBuffer())
|
| 593 |
+
length = Math.min(length, array.length)
|
| 594 |
+
for (var i = 0; i < length; i++) array[i] = array[i] ^ key[i % key.length]
|
| 595 |
+
return new Blob([array, blob.slice(length)], { type: blob.type })
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
const WebCryptoSHA1 = async str => {
|
| 599 |
+
const data = new TextEncoder().encode(str)
|
| 600 |
+
const buffer = await globalThis.crypto.subtle.digest('SHA-1', data)
|
| 601 |
+
return new Uint8Array(buffer)
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
const deobfuscators = (sha1 = WebCryptoSHA1) => ({
|
| 605 |
+
'http://www.idpf.org/2008/embedding': {
|
| 606 |
+
key: opf => sha1(getIdentifier(opf)
|
| 607 |
+
// eslint-disable-next-line no-control-regex
|
| 608 |
+
.replaceAll(/[\u0020\u0009\u000d\u000a]/g, '')),
|
| 609 |
+
decode: (key, blob) => deobfuscate(key, 1040, blob),
|
| 610 |
+
},
|
| 611 |
+
'http://ns.adobe.com/pdf/enc#RC': {
|
| 612 |
+
key: opf => {
|
| 613 |
+
const uuid = getUUID(opf).replaceAll('-', '')
|
| 614 |
+
return Uint8Array.from({ length: 16 }, (_, i) =>
|
| 615 |
+
parseInt(uuid.slice(i * 2, i * 2 + 2), 16))
|
| 616 |
+
},
|
| 617 |
+
decode: (key, blob) => deobfuscate(key, 1024, blob),
|
| 618 |
+
},
|
| 619 |
+
})
|
| 620 |
+
|
| 621 |
+
class Encryption {
|
| 622 |
+
#uris = new Map()
|
| 623 |
+
#decoders = new Map()
|
| 624 |
+
#algorithms
|
| 625 |
+
constructor(algorithms) {
|
| 626 |
+
this.#algorithms = algorithms
|
| 627 |
+
}
|
| 628 |
+
async init(encryption, opf) {
|
| 629 |
+
if (!encryption) return
|
| 630 |
+
const data = Array.from(
|
| 631 |
+
encryption.getElementsByTagNameNS(NS.ENC, 'EncryptedData'), el => ({
|
| 632 |
+
algorithm: el.getElementsByTagNameNS(NS.ENC, 'EncryptionMethod')[0]
|
| 633 |
+
?.getAttribute('Algorithm'),
|
| 634 |
+
uri: el.getElementsByTagNameNS(NS.ENC, 'CipherReference')[0]
|
| 635 |
+
?.getAttribute('URI'),
|
| 636 |
+
}))
|
| 637 |
+
for (const { algorithm, uri } of data) {
|
| 638 |
+
if (!this.#decoders.has(algorithm)) {
|
| 639 |
+
const algo = this.#algorithms[algorithm]
|
| 640 |
+
if (!algo) {
|
| 641 |
+
console.warn('Unknown encryption algorithm')
|
| 642 |
+
continue
|
| 643 |
+
}
|
| 644 |
+
const key = await algo.key(opf)
|
| 645 |
+
this.#decoders.set(algorithm, blob => algo.decode(key, blob))
|
| 646 |
+
}
|
| 647 |
+
this.#uris.set(uri, algorithm)
|
| 648 |
+
}
|
| 649 |
+
}
|
| 650 |
+
getDecoder(uri) {
|
| 651 |
+
return this.#decoders.get(this.#uris.get(uri)) ?? (x => x)
|
| 652 |
+
}
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
class Resources {
|
| 656 |
+
constructor({ opf, resolveHref }) {
|
| 657 |
+
this.opf = opf
|
| 658 |
+
const { $, $$, $$$ } = childGetter(opf, NS.OPF)
|
| 659 |
+
|
| 660 |
+
const $manifest = $(opf.documentElement, 'manifest')
|
| 661 |
+
const $spine = $(opf.documentElement, 'spine')
|
| 662 |
+
const $$itemref = $$($spine, 'itemref')
|
| 663 |
+
|
| 664 |
+
this.manifest = $$($manifest, 'item')
|
| 665 |
+
.map(getAttributes('href', 'id', 'media-type', 'properties', 'media-overlay'))
|
| 666 |
+
.map(item => {
|
| 667 |
+
item.href = resolveHref(item.href)
|
| 668 |
+
item.properties = item.properties?.split(/\s/)
|
| 669 |
+
return item
|
| 670 |
+
})
|
| 671 |
+
this.manifestById = new Map(this.manifest.map(item => [item.id, item]))
|
| 672 |
+
this.spine = $$itemref
|
| 673 |
+
.map(getAttributes('idref', 'id', 'linear', 'properties'))
|
| 674 |
+
.map(item => (item.properties = item.properties?.split(/\s/), item))
|
| 675 |
+
this.pageProgressionDirection = $spine
|
| 676 |
+
.getAttribute('page-progression-direction')
|
| 677 |
+
|
| 678 |
+
this.navPath = this.getItemByProperty('nav')?.href
|
| 679 |
+
this.ncxPath = (this.getItemByID($spine.getAttribute('toc'))
|
| 680 |
+
?? this.manifest.find(item => item.mediaType === MIME.NCX))?.href
|
| 681 |
+
|
| 682 |
+
const $guide = $(opf.documentElement, 'guide')
|
| 683 |
+
if ($guide) this.guide = $$($guide, 'reference')
|
| 684 |
+
.map(getAttributes('type', 'title', 'href'))
|
| 685 |
+
.map(({ type, title, href }) => ({
|
| 686 |
+
label: title,
|
| 687 |
+
type: type.split(/\s/),
|
| 688 |
+
href: resolveHref(href),
|
| 689 |
+
}))
|
| 690 |
+
|
| 691 |
+
this.cover = this.getItemByProperty('cover-image')
|
| 692 |
+
// EPUB 2 compat
|
| 693 |
+
?? this.getItemByID($$$(opf, 'meta')
|
| 694 |
+
.find(filterAttribute('name', 'cover'))
|
| 695 |
+
?.getAttribute('content'))
|
| 696 |
+
?? this.manifest.find(item => item.id === 'cover'
|
| 697 |
+
&& item.mediaType.startsWith('image'))
|
| 698 |
+
?? this.manifest.find(item => item.href.includes('cover')
|
| 699 |
+
&& item.mediaType.startsWith('image'))
|
| 700 |
+
?? this.getItemByHref(this.guide
|
| 701 |
+
?.find(ref => ref.type.includes('cover'))?.href)
|
| 702 |
+
// last resort: first image in manifest
|
| 703 |
+
?? this.manifest.find(item => item.mediaType.startsWith('image'))
|
| 704 |
+
|
| 705 |
+
this.cfis = CFI.fromElements($$itemref)
|
| 706 |
+
}
|
| 707 |
+
getItemByID(id) {
|
| 708 |
+
return this.manifestById.get(id)
|
| 709 |
+
}
|
| 710 |
+
getItemByHref(href) {
|
| 711 |
+
return this.manifest.find(item => item.href === href)
|
| 712 |
+
}
|
| 713 |
+
getItemByProperty(prop) {
|
| 714 |
+
return this.manifest.find(item => item.properties?.includes(prop))
|
| 715 |
+
}
|
| 716 |
+
resolveCFI(cfi) {
|
| 717 |
+
const parts = CFI.parse(cfi)
|
| 718 |
+
const top = (parts.parent ?? parts).shift()
|
| 719 |
+
let $itemref = CFI.toElement(this.opf, top)
|
| 720 |
+
// make sure it's an idref; if not, try again without the ID assertion
|
| 721 |
+
// mainly because Epub.js used to generate wrong ID assertions
|
| 722 |
+
// https://github.com/futurepress/epub.js/issues/1236
|
| 723 |
+
if ($itemref && $itemref.nodeName !== 'idref') {
|
| 724 |
+
top.at(-1).id = null
|
| 725 |
+
$itemref = CFI.toElement(this.opf, top)
|
| 726 |
+
}
|
| 727 |
+
const idref = $itemref?.getAttribute('idref')
|
| 728 |
+
const index = this.spine.findIndex(item => item.idref === idref)
|
| 729 |
+
const anchor = doc => CFI.toRange(doc, parts)
|
| 730 |
+
return { index, anchor }
|
| 731 |
+
}
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
class Loader {
|
| 735 |
+
#cache = new Map()
|
| 736 |
+
#cacheXHTMLContent = new Map()
|
| 737 |
+
#children = new Map()
|
| 738 |
+
#refCount = new Map()
|
| 739 |
+
eventTarget = new EventTarget()
|
| 740 |
+
constructor({ loadText, loadBlob, resources, entries }) {
|
| 741 |
+
this.loadText = loadText
|
| 742 |
+
this.loadBlob = loadBlob
|
| 743 |
+
this.manifest = resources.manifest
|
| 744 |
+
this.assets = resources.manifest
|
| 745 |
+
this.entries = entries
|
| 746 |
+
// needed only when replacing in (X)HTML w/o parsing (see below)
|
| 747 |
+
//.filter(({ mediaType }) => ![MIME.XHTML, MIME.HTML].includes(mediaType))
|
| 748 |
+
}
|
| 749 |
+
async createURL(href, data, type, parent) {
|
| 750 |
+
if (!data) return ''
|
| 751 |
+
const detail = { data, type }
|
| 752 |
+
Object.defineProperty(detail, 'name', { value: href }) // readonly
|
| 753 |
+
const event = new CustomEvent('data', { detail })
|
| 754 |
+
this.eventTarget.dispatchEvent(event)
|
| 755 |
+
const newData = await event.detail.data
|
| 756 |
+
const newType = await event.detail.type
|
| 757 |
+
const url = URL.createObjectURL(new Blob([newData], { type: newType }))
|
| 758 |
+
this.#cache.set(href, url)
|
| 759 |
+
this.#refCount.set(href, 1)
|
| 760 |
+
if (newType === MIME.XHTML || newType === MIME.HTML) {
|
| 761 |
+
this.#cacheXHTMLContent.set(url, {href, type: newType, data: newData})
|
| 762 |
+
}
|
| 763 |
+
if (parent) {
|
| 764 |
+
const childList = this.#children.get(parent)
|
| 765 |
+
if (childList) childList.push(href)
|
| 766 |
+
else this.#children.set(parent, [href])
|
| 767 |
+
}
|
| 768 |
+
return url
|
| 769 |
+
}
|
| 770 |
+
ref(href, parent) {
|
| 771 |
+
const childList = this.#children.get(parent)
|
| 772 |
+
if (!childList?.includes(href)) {
|
| 773 |
+
this.#refCount.set(href, this.#refCount.get(href) + 1)
|
| 774 |
+
//console.log(`referencing ${href}, now ${this.#refCount.get(href)}`)
|
| 775 |
+
if (childList) childList.push(href)
|
| 776 |
+
else this.#children.set(parent, [href])
|
| 777 |
+
}
|
| 778 |
+
return this.#cache.get(href)
|
| 779 |
+
}
|
| 780 |
+
unref(href) {
|
| 781 |
+
if (!this.#refCount.has(href)) return
|
| 782 |
+
const count = this.#refCount.get(href) - 1
|
| 783 |
+
//console.log(`unreferencing ${href}, now ${count}`)
|
| 784 |
+
if (count < 1) {
|
| 785 |
+
//console.log(`unloading ${href}`)
|
| 786 |
+
const url = this.#cache.get(href)
|
| 787 |
+
URL.revokeObjectURL(url)
|
| 788 |
+
this.#cache.delete(href)
|
| 789 |
+
this.#cacheXHTMLContent.delete(url)
|
| 790 |
+
this.#refCount.delete(href)
|
| 791 |
+
// unref children
|
| 792 |
+
const childList = this.#children.get(href)
|
| 793 |
+
if (childList) while (childList.length) this.unref(childList.pop())
|
| 794 |
+
this.#children.delete(href)
|
| 795 |
+
} else this.#refCount.set(href, count)
|
| 796 |
+
}
|
| 797 |
+
// load manifest item, recursively loading all resources as needed
|
| 798 |
+
async loadItem(item, parents = []) {
|
| 799 |
+
if (!item) return null
|
| 800 |
+
const { href, mediaType } = item
|
| 801 |
+
|
| 802 |
+
const isScript = MIME.JS.test(item.mediaType)
|
| 803 |
+
const detail = { type: mediaType, isScript, allow: true}
|
| 804 |
+
const event = new CustomEvent('load', { detail })
|
| 805 |
+
this.eventTarget.dispatchEvent(event)
|
| 806 |
+
const allow = await event.detail.allow
|
| 807 |
+
if (!allow) return null
|
| 808 |
+
|
| 809 |
+
const parent = parents.at(-1)
|
| 810 |
+
if (this.#cache.has(href)) return this.ref(href, parent)
|
| 811 |
+
|
| 812 |
+
const shouldReplace =
|
| 813 |
+
(isScript || [MIME.XHTML, MIME.HTML, MIME.CSS, MIME.SVG].includes(mediaType))
|
| 814 |
+
// prevent circular references
|
| 815 |
+
&& parents.every(p => p !== href)
|
| 816 |
+
if (shouldReplace) return this.loadReplaced(item, parents)
|
| 817 |
+
// NOTE: this can be replaced with `Promise.try()`
|
| 818 |
+
const tryLoadBlob = Promise.resolve().then(() => this.loadBlob(href))
|
| 819 |
+
return this.createURL(href, tryLoadBlob, mediaType, parent)
|
| 820 |
+
}
|
| 821 |
+
async loadItemXHTMLContent(item, parents = []) {
|
| 822 |
+
const url = await this.loadItem(item, parents)
|
| 823 |
+
if (url) return this.#cacheXHTMLContent.get(url)?.data
|
| 824 |
+
}
|
| 825 |
+
tryImageEntryItem(path) {
|
| 826 |
+
if (!IMAGE_EXTENSIONS.some(ext => path.toLowerCase().endsWith(`.${ext}`))) {
|
| 827 |
+
return null
|
| 828 |
+
}
|
| 829 |
+
if (!this.entries.get(path)) {
|
| 830 |
+
return null
|
| 831 |
+
}
|
| 832 |
+
return {
|
| 833 |
+
href: path,
|
| 834 |
+
mediaType: getImageMediaType(path),
|
| 835 |
+
}
|
| 836 |
+
}
|
| 837 |
+
async loadHref(href, base, parents = []) {
|
| 838 |
+
if (isExternal(href)) return href
|
| 839 |
+
const path = resolveURL(href, base)
|
| 840 |
+
let item = this.manifest.find(item => item.href === path)
|
| 841 |
+
if (!item) {
|
| 842 |
+
item = this.tryImageEntryItem(path)
|
| 843 |
+
if (!item) {
|
| 844 |
+
return href
|
| 845 |
+
}
|
| 846 |
+
}
|
| 847 |
+
return this.loadItem(item, parents.concat(base))
|
| 848 |
+
}
|
| 849 |
+
async loadReplaced(item, parents = []) {
|
| 850 |
+
const { href, mediaType } = item
|
| 851 |
+
const parent = parents.at(-1)
|
| 852 |
+
let str = ''
|
| 853 |
+
try {
|
| 854 |
+
str = await this.loadText(href)
|
| 855 |
+
} catch (e) {
|
| 856 |
+
return this.createURL(href, Promise.reject(e), mediaType, parent)
|
| 857 |
+
}
|
| 858 |
+
if (!str) return null
|
| 859 |
+
|
| 860 |
+
// note that one can also just use `replaceString` for everything:
|
| 861 |
+
// ```
|
| 862 |
+
// const replaced = await this.replaceString(str, href, parents)
|
| 863 |
+
// return this.createURL(href, replaced, mediaType, parent)
|
| 864 |
+
// ```
|
| 865 |
+
// which is basically what Epub.js does, which is simpler, but will
|
| 866 |
+
// break things like iframes (because you don't want to replace links)
|
| 867 |
+
// or text that just happen to be paths
|
| 868 |
+
|
| 869 |
+
// parse and replace in HTML
|
| 870 |
+
if ([MIME.XHTML, MIME.HTML, MIME.SVG].includes(mediaType)) {
|
| 871 |
+
let doc = new DOMParser().parseFromString(str, mediaType)
|
| 872 |
+
// change to HTML if it's not valid XHTML
|
| 873 |
+
if (mediaType === MIME.XHTML && (doc.querySelector('parsererror')
|
| 874 |
+
|| !doc.documentElement?.namespaceURI)) {
|
| 875 |
+
console.warn(doc.querySelector('parsererror')?.innerText ?? 'Invalid XHTML')
|
| 876 |
+
item.mediaType = MIME.HTML
|
| 877 |
+
doc = new DOMParser().parseFromString(str, item.mediaType)
|
| 878 |
+
}
|
| 879 |
+
// replace hrefs in XML processing instructions
|
| 880 |
+
// this is mainly for SVGs that use xml-stylesheet
|
| 881 |
+
if ([MIME.XHTML, MIME.SVG].includes(item.mediaType)) {
|
| 882 |
+
let child = doc.firstChild
|
| 883 |
+
while (child instanceof ProcessingInstruction) {
|
| 884 |
+
if (child.data) {
|
| 885 |
+
const replacedData = await replaceSeries(child.data,
|
| 886 |
+
/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,
|
| 887 |
+
(_, p1, p2, p3) => this.loadHref(p2, href, parents)
|
| 888 |
+
.then(p2 => `${p1}${p2}${p3}`))
|
| 889 |
+
child.replaceWith(doc.createProcessingInstruction(
|
| 890 |
+
child.target, replacedData))
|
| 891 |
+
}
|
| 892 |
+
child = child.nextSibling
|
| 893 |
+
}
|
| 894 |
+
}
|
| 895 |
+
// replace hrefs (excluding anchors)
|
| 896 |
+
const replace = async (el, attr) => el.setAttribute(attr,
|
| 897 |
+
await this.loadHref(el.getAttribute(attr), href, parents))
|
| 898 |
+
for (const el of doc.querySelectorAll('link[href]')) await replace(el, 'href')
|
| 899 |
+
for (const el of doc.querySelectorAll('[src]')) await replace(el, 'src')
|
| 900 |
+
for (const el of doc.querySelectorAll('[poster]')) await replace(el, 'poster')
|
| 901 |
+
for (const el of doc.querySelectorAll('object[data]')) await replace(el, 'data')
|
| 902 |
+
for (const el of doc.querySelectorAll('[*|href]:not([href])'))
|
| 903 |
+
el.setAttributeNS(NS.XLINK, 'href', await this.loadHref(
|
| 904 |
+
el.getAttributeNS(NS.XLINK, 'href'), href, parents))
|
| 905 |
+
for (const el of doc.querySelectorAll('[srcset]'))
|
| 906 |
+
el.setAttribute('srcset', await replaceSeries(el.getAttribute('srcset'),
|
| 907 |
+
/(\s*)(.+?)\s*((?:\s[\d.]+[wx])+\s*(?:,|$)|,\s+|$)/g,
|
| 908 |
+
(_, p1, p2, p3) => this.loadHref(p2, href, parents)
|
| 909 |
+
.then(p2 => `${p1}${p2}${p3}`)))
|
| 910 |
+
// replace inline styles
|
| 911 |
+
for (const el of doc.querySelectorAll('style'))
|
| 912 |
+
if (el.textContent) el.textContent =
|
| 913 |
+
await this.replaceCSS(el.textContent, href, parents)
|
| 914 |
+
for (const el of doc.querySelectorAll('[style]'))
|
| 915 |
+
el.setAttribute('style',
|
| 916 |
+
await this.replaceCSS(el.getAttribute('style'), href, parents))
|
| 917 |
+
// TODO: replace inline scripts? probably not worth the trouble
|
| 918 |
+
const result = new XMLSerializer().serializeToString(doc)
|
| 919 |
+
return this.createURL(href, result, item.mediaType, parent)
|
| 920 |
+
}
|
| 921 |
+
|
| 922 |
+
const result = mediaType === MIME.CSS
|
| 923 |
+
? await this.replaceCSS(str, href, parents)
|
| 924 |
+
: await this.replaceString(str, href, parents)
|
| 925 |
+
return this.createURL(href, result, mediaType, parent)
|
| 926 |
+
}
|
| 927 |
+
async replaceCSS(str, href, parents = []) {
|
| 928 |
+
const replacedUrls = await replaceSeries(str,
|
| 929 |
+
/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,
|
| 930 |
+
(_, url) => this.loadHref(url, href, parents)
|
| 931 |
+
.then(url => `url("${url}")`))
|
| 932 |
+
// apart from `url()`, strings can be used for `@import` (but why?!)
|
| 933 |
+
return replaceSeries(replacedUrls,
|
| 934 |
+
/@import\s*["']([^"'\n]*?)["']/gi,
|
| 935 |
+
(_, url) => this.loadHref(url, href, parents)
|
| 936 |
+
.then(url => `@import "${url}"`))
|
| 937 |
+
}
|
| 938 |
+
// find & replace all possible relative paths for all assets without parsing
|
| 939 |
+
replaceString(str, href, parents = []) {
|
| 940 |
+
const assetMap = new Map()
|
| 941 |
+
const urls = this.assets.map(asset => {
|
| 942 |
+
// do not replace references to the file itself
|
| 943 |
+
if (asset.href === href) return
|
| 944 |
+
// href was decoded and resolved when parsing the manifest
|
| 945 |
+
const relative = pathRelative(pathDirname(href), asset.href)
|
| 946 |
+
const relativeEnc = encodeURI(relative)
|
| 947 |
+
const rootRelative = '/' + asset.href
|
| 948 |
+
const rootRelativeEnc = encodeURI(rootRelative)
|
| 949 |
+
const set = new Set([relative, relativeEnc, rootRelative, rootRelativeEnc])
|
| 950 |
+
for (const url of set) assetMap.set(url, asset)
|
| 951 |
+
return Array.from(set)
|
| 952 |
+
}).flat().filter(x => x)
|
| 953 |
+
if (!urls.length) return str
|
| 954 |
+
const regex = new RegExp(urls.map(regexEscape).join('|'), 'g')
|
| 955 |
+
return replaceSeries(str, regex, async match =>
|
| 956 |
+
this.loadItem(assetMap.get(match.replace(/^\//, '')),
|
| 957 |
+
parents.concat(href)))
|
| 958 |
+
}
|
| 959 |
+
unloadItem(item) {
|
| 960 |
+
this.unref(item?.href)
|
| 961 |
+
}
|
| 962 |
+
destroy() {
|
| 963 |
+
for (const url of this.#cache.values()) URL.revokeObjectURL(url)
|
| 964 |
+
}
|
| 965 |
+
}
|
| 966 |
+
|
| 967 |
+
const getHTMLFragment = (doc, id) => doc.getElementById(id)
|
| 968 |
+
?? doc.querySelector(`[name="${CSS.escape(id)}"]`)
|
| 969 |
+
|
| 970 |
+
const getPageSpread = properties => {
|
| 971 |
+
for (const p of properties) {
|
| 972 |
+
if (p === 'page-spread-left' || p === 'rendition:page-spread-left')
|
| 973 |
+
return 'left'
|
| 974 |
+
if (p === 'page-spread-right' || p === 'rendition:page-spread-right')
|
| 975 |
+
return 'right'
|
| 976 |
+
if (p === 'rendition:page-spread-center') return 'center'
|
| 977 |
+
}
|
| 978 |
+
}
|
| 979 |
+
|
| 980 |
+
const getDisplayOptions = doc => {
|
| 981 |
+
if (!doc) return null
|
| 982 |
+
return {
|
| 983 |
+
fixedLayout: getElementText(doc.querySelector('option[name="fixed-layout"]')),
|
| 984 |
+
openToSpread: getElementText(doc.querySelector('option[name="open-to-spread"]')),
|
| 985 |
+
}
|
| 986 |
+
}
|
| 987 |
+
|
| 988 |
+
export class EPUB {
|
| 989 |
+
parser = new DOMParser()
|
| 990 |
+
#loader
|
| 991 |
+
#encryption
|
| 992 |
+
constructor({ entries, loadText, loadBlob, getSize, sha1 }) {
|
| 993 |
+
this.entries = entries.reduce((map, entry) => {
|
| 994 |
+
map.set(entry.filename, entry)
|
| 995 |
+
return map
|
| 996 |
+
}, new Map())
|
| 997 |
+
this.loadText = loadText
|
| 998 |
+
this.loadBlob = loadBlob
|
| 999 |
+
this.getSize = getSize
|
| 1000 |
+
this.#encryption = new Encryption(deobfuscators(sha1))
|
| 1001 |
+
}
|
| 1002 |
+
#sanitizeXMLEntities(str) {
|
| 1003 |
+
// Common HTML entities that aren't valid in XML
|
| 1004 |
+
const entityMap = {
|
| 1005 |
+
'nbsp': ' ',
|
| 1006 |
+
'mdash': '—',
|
| 1007 |
+
'ndash': '–',
|
| 1008 |
+
'ldquo': '“',
|
| 1009 |
+
'rdquo': '”',
|
| 1010 |
+
'lsquo': '‘',
|
| 1011 |
+
'rsquo': '’',
|
| 1012 |
+
'hellip': '…',
|
| 1013 |
+
'copy': '©',
|
| 1014 |
+
'reg': '®',
|
| 1015 |
+
'trade': '™',
|
| 1016 |
+
'bull': '•',
|
| 1017 |
+
'middot': '·',
|
| 1018 |
+
}
|
| 1019 |
+
return str.replace(/&([a-z]+);/gi, (match, entity) => {
|
| 1020 |
+
return entityMap[entity.toLowerCase()] || match
|
| 1021 |
+
})
|
| 1022 |
+
}
|
| 1023 |
+
async #loadXML(uri) {
|
| 1024 |
+
const str = await this.loadText(uri)
|
| 1025 |
+
if (!str) return null
|
| 1026 |
+
const sanitized = this.#sanitizeXMLEntities(str)
|
| 1027 |
+
const doc = this.parser.parseFromString(sanitized, MIME.XML)
|
| 1028 |
+
if (doc.querySelector('parsererror'))
|
| 1029 |
+
throw new Error(`XML parsing error: ${uri}
|
| 1030 |
+
${doc.querySelector('parsererror').innerText}`)
|
| 1031 |
+
return doc
|
| 1032 |
+
}
|
| 1033 |
+
async init() {
|
| 1034 |
+
const $container = await this.#loadXML('META-INF/container.xml')
|
| 1035 |
+
if (!$container) throw new Error('Failed to load container file')
|
| 1036 |
+
|
| 1037 |
+
const opfs = Array.from(
|
| 1038 |
+
$container.getElementsByTagNameNS(NS.CONTAINER, 'rootfile'),
|
| 1039 |
+
getAttributes('full-path', 'media-type'))
|
| 1040 |
+
.filter(file => file.mediaType === 'application/oebps-package+xml')
|
| 1041 |
+
|
| 1042 |
+
if (!opfs.length) throw new Error('No package document defined in container')
|
| 1043 |
+
const opfPath = opfs[0].fullPath
|
| 1044 |
+
const opf = await this.#loadXML(opfPath)
|
| 1045 |
+
if (!opf) throw new Error('Failed to load package document')
|
| 1046 |
+
|
| 1047 |
+
const $encryption = await this.#loadXML('META-INF/encryption.xml')
|
| 1048 |
+
await this.#encryption.init($encryption, opf)
|
| 1049 |
+
|
| 1050 |
+
this.resources = new Resources({
|
| 1051 |
+
opf,
|
| 1052 |
+
resolveHref: url => resolveURL(url, opfPath),
|
| 1053 |
+
})
|
| 1054 |
+
this.#loader = new Loader({
|
| 1055 |
+
loadText: this.loadText,
|
| 1056 |
+
loadBlob: uri => Promise.resolve(this.loadBlob(uri))
|
| 1057 |
+
.then(this.#encryption.getDecoder(uri)),
|
| 1058 |
+
resources: this.resources,
|
| 1059 |
+
entries: this.entries,
|
| 1060 |
+
})
|
| 1061 |
+
this.transformTarget = this.#loader.eventTarget
|
| 1062 |
+
this.sections = this.resources.spine.map((spineItem, index) => {
|
| 1063 |
+
const { idref, linear, properties = [] } = spineItem
|
| 1064 |
+
const item = this.resources.getItemByID(idref)
|
| 1065 |
+
if (!item) {
|
| 1066 |
+
console.warn(`Could not find item with ID "${idref}" in manifest`)
|
| 1067 |
+
return null
|
| 1068 |
+
}
|
| 1069 |
+
return {
|
| 1070 |
+
id: item.href,
|
| 1071 |
+
load: () => this.#loader.loadItem(item),
|
| 1072 |
+
unload: () => this.#loader.unloadItem(item),
|
| 1073 |
+
loadText: () => this.#loader.loadText(item.href),
|
| 1074 |
+
loadContent: () => this.#loader.loadItemXHTMLContent(item),
|
| 1075 |
+
createDocument: () => this.loadDocument(item),
|
| 1076 |
+
size: this.getSize(item.href),
|
| 1077 |
+
cfi: this.resources.cfis[index],
|
| 1078 |
+
linear,
|
| 1079 |
+
pageSpread: getPageSpread(properties),
|
| 1080 |
+
resolveHref: href => resolveURL(href, item.href),
|
| 1081 |
+
mediaOverlay: item.mediaOverlay
|
| 1082 |
+
? this.resources.getItemByID(item.mediaOverlay) : null,
|
| 1083 |
+
}
|
| 1084 |
+
}).filter(s => s)
|
| 1085 |
+
|
| 1086 |
+
const { navPath, ncxPath } = this.resources
|
| 1087 |
+
if (navPath) try {
|
| 1088 |
+
const resolve = url => resolveURL(url, navPath)
|
| 1089 |
+
const nav = parseNav(await this.#loadXML(navPath), resolve)
|
| 1090 |
+
this.toc = nav.toc
|
| 1091 |
+
this.pageList = nav.pageList
|
| 1092 |
+
this.landmarks = nav.landmarks
|
| 1093 |
+
} catch(e) {
|
| 1094 |
+
console.warn(e)
|
| 1095 |
+
}
|
| 1096 |
+
if (!this.toc && ncxPath) try {
|
| 1097 |
+
const resolve = url => resolveURL(url, ncxPath)
|
| 1098 |
+
const ncx = parseNCX(await this.#loadXML(ncxPath), resolve)
|
| 1099 |
+
this.toc = ncx.toc
|
| 1100 |
+
this.pageList = ncx.pageList
|
| 1101 |
+
} catch(e) {
|
| 1102 |
+
console.warn(e)
|
| 1103 |
+
}
|
| 1104 |
+
|
| 1105 |
+
await this.#updateSubItems()
|
| 1106 |
+
|
| 1107 |
+
this.landmarks ??= this.resources.guide
|
| 1108 |
+
|
| 1109 |
+
const { metadata, rendition, media } = getMetadata(opf)
|
| 1110 |
+
this.metadata = metadata
|
| 1111 |
+
this.rendition = rendition
|
| 1112 |
+
this.media = media
|
| 1113 |
+
this.dir = this.resources.pageProgressionDirection
|
| 1114 |
+
const displayOptions = getDisplayOptions(
|
| 1115 |
+
await this.#loadXML('META-INF/com.apple.ibooks.display-options.xml')
|
| 1116 |
+
?? await this.#loadXML('META-INF/com.kobobooks.display-options.xml'))
|
| 1117 |
+
if (displayOptions) {
|
| 1118 |
+
if (displayOptions.fixedLayout === 'true')
|
| 1119 |
+
this.rendition.layout ??= 'pre-paginated'
|
| 1120 |
+
if (displayOptions.openToSpread === 'false') this.sections
|
| 1121 |
+
.find(section => section.linear !== 'no').pageSpread ??=
|
| 1122 |
+
this.dir === 'rtl' ? 'left' : 'right'
|
| 1123 |
+
}
|
| 1124 |
+
return this
|
| 1125 |
+
}
|
| 1126 |
+
|
| 1127 |
+
#groupTocSubitems(items) {
|
| 1128 |
+
// Helper: Group subitems by section ID
|
| 1129 |
+
const groupBySection = (subitems) => {
|
| 1130 |
+
const grouped = new Map()
|
| 1131 |
+
for (const subitem of subitems) {
|
| 1132 |
+
const [sectionId] = this.splitTOCHref(subitem.href)
|
| 1133 |
+
if (!grouped.has(sectionId)) grouped.set(sectionId, [])
|
| 1134 |
+
grouped.get(sectionId).push(subitem)
|
| 1135 |
+
}
|
| 1136 |
+
return grouped
|
| 1137 |
+
}
|
| 1138 |
+
|
| 1139 |
+
// Helper: Separate parent item from fragment items
|
| 1140 |
+
const separateParentAndFragments = (sectionId, subitems) => {
|
| 1141 |
+
let parent = null
|
| 1142 |
+
const fragments = []
|
| 1143 |
+
|
| 1144 |
+
for (const subitem of subitems) {
|
| 1145 |
+
const [, fragmentId] = this.splitTOCHref(subitem.href)
|
| 1146 |
+
if (!fragmentId || subitem.href === sectionId) {
|
| 1147 |
+
parent = subitem
|
| 1148 |
+
} else {
|
| 1149 |
+
fragments.push(subitem)
|
| 1150 |
+
}
|
| 1151 |
+
}
|
| 1152 |
+
|
| 1153 |
+
return { parent, fragments }
|
| 1154 |
+
}
|
| 1155 |
+
|
| 1156 |
+
// Helper: Create grouped structure for multiple items in same section
|
| 1157 |
+
const createGroupedItem = (sectionId, subitems) => {
|
| 1158 |
+
const { parent, fragments } = separateParentAndFragments(sectionId, subitems)
|
| 1159 |
+
|
| 1160 |
+
// Use existing parent or create new one
|
| 1161 |
+
const parentItem = parent ?? {
|
| 1162 |
+
label: subitems[0].label || sectionId,
|
| 1163 |
+
href: sectionId,
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
// Nest fragment items under parent
|
| 1167 |
+
if (fragments.length > 0) {
|
| 1168 |
+
parentItem.subitems = fragments
|
| 1169 |
+
}
|
| 1170 |
+
|
| 1171 |
+
return parentItem
|
| 1172 |
+
}
|
| 1173 |
+
|
| 1174 |
+
for (const item of items) {
|
| 1175 |
+
if (!item.subitems?.length) continue
|
| 1176 |
+
|
| 1177 |
+
const groupedBySection = groupBySection(item.subitems)
|
| 1178 |
+
const newSubitems = []
|
| 1179 |
+
|
| 1180 |
+
for (const [sectionId, subitems] of groupedBySection.entries()) {
|
| 1181 |
+
const groupedItem = subitems.length === 1
|
| 1182 |
+
? subitems[0] // Single item, keep as-is
|
| 1183 |
+
: createGroupedItem(sectionId, subitems) // Multiple items, group them
|
| 1184 |
+
|
| 1185 |
+
newSubitems.push(groupedItem)
|
| 1186 |
+
}
|
| 1187 |
+
|
| 1188 |
+
item.subitems = newSubitems
|
| 1189 |
+
}
|
| 1190 |
+
}
|
| 1191 |
+
|
| 1192 |
+
// Helper: Find position of fragment ID in HTML string
|
| 1193 |
+
#findFragmentPosition(html, fragmentId) {
|
| 1194 |
+
if (!fragmentId) return html.length
|
| 1195 |
+
|
| 1196 |
+
const patterns = [
|
| 1197 |
+
new RegExp(`\\sid=["']${CSS.escape(fragmentId)}["']`, 'i'),
|
| 1198 |
+
new RegExp(`\\sname=["']${CSS.escape(fragmentId)}["']`, 'i'),
|
| 1199 |
+
]
|
| 1200 |
+
|
| 1201 |
+
for (const pattern of patterns) {
|
| 1202 |
+
const match = html.match(pattern)
|
| 1203 |
+
if (match) return match.index
|
| 1204 |
+
}
|
| 1205 |
+
|
| 1206 |
+
return -1
|
| 1207 |
+
}
|
| 1208 |
+
|
| 1209 |
+
// Helper: Flatten nested TOC structure into single array
|
| 1210 |
+
#collectAllTocItems(tocItems) {
|
| 1211 |
+
const allItems = []
|
| 1212 |
+
const traverse = (items) => {
|
| 1213 |
+
for (const item of items) {
|
| 1214 |
+
allItems.push(item)
|
| 1215 |
+
if (item.subitems?.length) traverse(item.subitems)
|
| 1216 |
+
}
|
| 1217 |
+
}
|
| 1218 |
+
traverse(tocItems)
|
| 1219 |
+
return allItems
|
| 1220 |
+
}
|
| 1221 |
+
|
| 1222 |
+
// Helper: Group TOC items by section ID (base + fragments)
|
| 1223 |
+
#groupItemsBySection(allItems) {
|
| 1224 |
+
const sectionGroups = new Map()
|
| 1225 |
+
|
| 1226 |
+
for (const item of allItems) {
|
| 1227 |
+
const [sectionId, fragmentId] = this.splitTOCHref(item.href)
|
| 1228 |
+
|
| 1229 |
+
if (!sectionGroups.has(sectionId)) {
|
| 1230 |
+
sectionGroups.set(sectionId, { base: null, fragments: [] })
|
| 1231 |
+
}
|
| 1232 |
+
|
| 1233 |
+
const group = sectionGroups.get(sectionId)
|
| 1234 |
+
const isBase = !fragmentId || item.href === sectionId
|
| 1235 |
+
|
| 1236 |
+
if (isBase) group.base = item
|
| 1237 |
+
else group.fragments.push(item)
|
| 1238 |
+
}
|
| 1239 |
+
|
| 1240 |
+
return sectionGroups
|
| 1241 |
+
}
|
| 1242 |
+
|
| 1243 |
+
// Helper: Calculate byte size of HTML between two fragments
|
| 1244 |
+
#calculateFragmentSize(content, fragmentId, prevFragmentId) {
|
| 1245 |
+
const endPos = this.#findFragmentPosition(content, fragmentId)
|
| 1246 |
+
if (endPos < 0) return 0
|
| 1247 |
+
|
| 1248 |
+
const startPos = prevFragmentId
|
| 1249 |
+
? this.#findFragmentPosition(content, prevFragmentId)
|
| 1250 |
+
: 0
|
| 1251 |
+
|
| 1252 |
+
const validStartPos = Math.max(0, startPos)
|
| 1253 |
+
if (endPos < validStartPos) return 0
|
| 1254 |
+
|
| 1255 |
+
const htmlSubstring = content.substring(validStartPos, endPos)
|
| 1256 |
+
return new Blob([htmlSubstring]).size
|
| 1257 |
+
}
|
| 1258 |
+
|
| 1259 |
+
// Helper: Load and cache section HTML content
|
| 1260 |
+
async #loadSectionContent(section, contentCache) {
|
| 1261 |
+
const cached = contentCache.get(section.id)
|
| 1262 |
+
if (cached) return cached
|
| 1263 |
+
|
| 1264 |
+
const content = await section.loadText()
|
| 1265 |
+
if (content) contentCache.set(section.id, content)
|
| 1266 |
+
|
| 1267 |
+
return content
|
| 1268 |
+
}
|
| 1269 |
+
|
| 1270 |
+
// Helper: Create section subitems from fragments
|
| 1271 |
+
#createSectionSubitems(fragments, base, content, section) {
|
| 1272 |
+
const subitems = []
|
| 1273 |
+
for (let i = 0; i < fragments.length; i++) {
|
| 1274 |
+
const fragment = fragments[i]
|
| 1275 |
+
const [, fragmentId] = this.splitTOCHref(fragment.href)
|
| 1276 |
+
|
| 1277 |
+
const prevFragment = i > 0 ? fragments[i - 1] : base
|
| 1278 |
+
const [, prevFragmentId] = prevFragment
|
| 1279 |
+
? this.splitTOCHref(prevFragment.href)
|
| 1280 |
+
: [null, null]
|
| 1281 |
+
|
| 1282 |
+
const size = this.#calculateFragmentSize(content, fragmentId, prevFragmentId)
|
| 1283 |
+
|
| 1284 |
+
subitems.push({
|
| 1285 |
+
id: fragment.href,
|
| 1286 |
+
href: fragment.href,
|
| 1287 |
+
cfi: fragment.cfi,
|
| 1288 |
+
size,
|
| 1289 |
+
linear: section.linear,
|
| 1290 |
+
})
|
| 1291 |
+
}
|
| 1292 |
+
|
| 1293 |
+
return subitems
|
| 1294 |
+
}
|
| 1295 |
+
|
| 1296 |
+
// Update section subitems from TOC structure
|
| 1297 |
+
async #updateSubItems() {
|
| 1298 |
+
if (!this.toc || !this.sections) return
|
| 1299 |
+
|
| 1300 |
+
// Step 1: Group TOC items by section
|
| 1301 |
+
this.#groupTocSubitems(this.toc)
|
| 1302 |
+
|
| 1303 |
+
// Step 2: Prepare section lookup and content cache
|
| 1304 |
+
const sectionMap = new Map(this.sections.map(s => [s.id, s]))
|
| 1305 |
+
const contentCache = new Map()
|
| 1306 |
+
|
| 1307 |
+
// Step 3: Flatten TOC and group by section ID
|
| 1308 |
+
const allTocItems = this.#collectAllTocItems(this.toc)
|
| 1309 |
+
const sectionGroups = this.#groupItemsBySection(allTocItems)
|
| 1310 |
+
|
| 1311 |
+
// Step 4: Process each section and create subitems
|
| 1312 |
+
for (const [sectionId, { base, fragments }] of sectionGroups.entries()) {
|
| 1313 |
+
const section = sectionMap.get(sectionId)
|
| 1314 |
+
if (!section || fragments.length === 0) continue
|
| 1315 |
+
|
| 1316 |
+
// Load HTML content for this section
|
| 1317 |
+
const content = await this.#loadSectionContent(section, contentCache)
|
| 1318 |
+
if (!content) continue
|
| 1319 |
+
|
| 1320 |
+
// Create subitems from fragments
|
| 1321 |
+
const subitems = this.#createSectionSubitems(fragments, base, content, section)
|
| 1322 |
+
|
| 1323 |
+
// Assign to section
|
| 1324 |
+
if (subitems.length > 0) {
|
| 1325 |
+
section.subitems = subitems
|
| 1326 |
+
}
|
| 1327 |
+
}
|
| 1328 |
+
}
|
| 1329 |
+
async loadDocument(item) {
|
| 1330 |
+
const str = await this.loadText(item.href)
|
| 1331 |
+
return this.parser.parseFromString(str, item.mediaType)
|
| 1332 |
+
}
|
| 1333 |
+
getMediaOverlay() {
|
| 1334 |
+
return new MediaOverlay(this, this.#loadXML.bind(this))
|
| 1335 |
+
}
|
| 1336 |
+
resolveCFI(cfi) {
|
| 1337 |
+
return this.resources.resolveCFI(cfi)
|
| 1338 |
+
}
|
| 1339 |
+
resolveHref(href) {
|
| 1340 |
+
const [path, hash] = href.split('#')
|
| 1341 |
+
const item = this.resources.getItemByHref(decodeURI(path))
|
| 1342 |
+
if (!item) return null
|
| 1343 |
+
const index = this.resources.spine.findIndex(({ idref }) => idref === item.id)
|
| 1344 |
+
const anchor = hash ? doc => getHTMLFragment(doc, hash) : () => 0
|
| 1345 |
+
return { index, anchor }
|
| 1346 |
+
}
|
| 1347 |
+
splitTOCHref(href) {
|
| 1348 |
+
return href?.split('#') ?? []
|
| 1349 |
+
}
|
| 1350 |
+
getTOCFragment(doc, id) {
|
| 1351 |
+
return doc.getElementById(id)
|
| 1352 |
+
?? doc.querySelector(`[name="${CSS.escape(id)}"]`)
|
| 1353 |
+
}
|
| 1354 |
+
isExternal(uri) {
|
| 1355 |
+
return isExternal(uri)
|
| 1356 |
+
}
|
| 1357 |
+
async getCover() {
|
| 1358 |
+
const cover = this.resources?.cover
|
| 1359 |
+
return cover?.href
|
| 1360 |
+
? new Blob([await this.loadBlob(cover.href)], { type: cover.mediaType })
|
| 1361 |
+
: null
|
| 1362 |
+
}
|
| 1363 |
+
async getCalibreBookmarks() {
|
| 1364 |
+
const txt = await this.loadText('META-INF/calibre_bookmarks.txt')
|
| 1365 |
+
const magic = 'encoding=json+base64:'
|
| 1366 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const findIndices = (arr, f) => arr
|
| 2 |
+
.map((x, i, a) => f(x, i, a) ? i : null).filter(x => x != null)
|
| 3 |
+
const splitAt = (arr, is) => [-1, ...is, arr.length].reduce(({ xs, a }, b) =>
|
| 4 |
+
({ xs: xs?.concat([arr.slice(a + 1, b)]) ?? [], a: b }), {}).xs
|
| 5 |
+
const concatArrays = (a, b) =>
|
| 6 |
+
a.slice(0, -1).concat([a[a.length - 1].concat(b[0])]).concat(b.slice(1))
|
| 7 |
+
|
| 8 |
+
const isNumber = /\d/
|
| 9 |
+
export const isCFI = /^epubcfi\((.*)\)$/
|
| 10 |
+
const escapeCFI = str => str.replace(/[\^[\](),;=]/g, '^$&')
|
| 11 |
+
|
| 12 |
+
const wrap = x => isCFI.test(x) ? x : `epubcfi(${x})`
|
| 13 |
+
const unwrap = x => x.match(isCFI)?.[1] ?? x
|
| 14 |
+
const lift = f => (...xs) =>
|
| 15 |
+
`epubcfi(${f(...xs.map(x => x.match(isCFI)?.[1] ?? x))})`
|
| 16 |
+
export const joinIndir = lift((...xs) => xs.join('!'))
|
| 17 |
+
|
| 18 |
+
const tokenizer = str => {
|
| 19 |
+
const tokens = []
|
| 20 |
+
let state, escape, value = ''
|
| 21 |
+
const push = x => (tokens.push(x), state = null, value = '')
|
| 22 |
+
const cat = x => (value += x, escape = false)
|
| 23 |
+
for (const char of Array.from(str.trim()).concat('')) {
|
| 24 |
+
if (char === '^' && !escape) {
|
| 25 |
+
escape = true
|
| 26 |
+
continue
|
| 27 |
+
}
|
| 28 |
+
if (state === '!') push(['!'])
|
| 29 |
+
else if (state === ',') push([','])
|
| 30 |
+
else if (state === '/' || state === ':') {
|
| 31 |
+
if (isNumber.test(char)) {
|
| 32 |
+
cat(char)
|
| 33 |
+
continue
|
| 34 |
+
} else push([state, parseInt(value)])
|
| 35 |
+
} else if (state === '~') {
|
| 36 |
+
if (isNumber.test(char) || char === '.') {
|
| 37 |
+
cat(char)
|
| 38 |
+
continue
|
| 39 |
+
} else push(['~', parseFloat(value)])
|
| 40 |
+
} else if (state === '@') {
|
| 41 |
+
if (char === ':') {
|
| 42 |
+
push(['@', parseFloat(value)])
|
| 43 |
+
state = '@'
|
| 44 |
+
continue
|
| 45 |
+
}
|
| 46 |
+
if (isNumber.test(char) || char === '.') {
|
| 47 |
+
cat(char)
|
| 48 |
+
continue
|
| 49 |
+
} else push(['@', parseFloat(value)])
|
| 50 |
+
} else if (state === '[') {
|
| 51 |
+
if (char === ';' && !escape) {
|
| 52 |
+
push(['[', value])
|
| 53 |
+
state = ';'
|
| 54 |
+
} else if (char === ',' && !escape) {
|
| 55 |
+
push(['[', value])
|
| 56 |
+
state = '['
|
| 57 |
+
} else if (char === ']' && !escape) push(['[', value])
|
| 58 |
+
else cat(char)
|
| 59 |
+
continue
|
| 60 |
+
} else if (state?.startsWith(';')) {
|
| 61 |
+
if (char === '=' && !escape) {
|
| 62 |
+
state = `;${value}`
|
| 63 |
+
value = ''
|
| 64 |
+
} else if (char === ';' && !escape) {
|
| 65 |
+
push([state, value])
|
| 66 |
+
state = ';'
|
| 67 |
+
} else if (char === ']' && !escape) push([state, value])
|
| 68 |
+
else cat(char)
|
| 69 |
+
continue
|
| 70 |
+
}
|
| 71 |
+
if (char === '/' || char === ':' || char === '~' || char === '@'
|
| 72 |
+
|| char === '[' || char === '!' || char === ',') state = char
|
| 73 |
+
}
|
| 74 |
+
return tokens
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
const findTokens = (tokens, x) => findIndices(tokens, ([t]) => t === x)
|
| 78 |
+
|
| 79 |
+
const parser = tokens => {
|
| 80 |
+
const parts = []
|
| 81 |
+
let state
|
| 82 |
+
for (const [type, val] of tokens) {
|
| 83 |
+
if (type === '/') parts.push({ index: val })
|
| 84 |
+
else {
|
| 85 |
+
const last = parts[parts.length - 1]
|
| 86 |
+
if (type === ':') last.offset = val
|
| 87 |
+
else if (type === '~') last.temporal = val
|
| 88 |
+
else if (type === '@') last.spatial = (last.spatial ?? []).concat(val)
|
| 89 |
+
else if (type === ';s') last.side = val
|
| 90 |
+
else if (type === '[') {
|
| 91 |
+
if (state === '/' && val) last.id = val
|
| 92 |
+
else {
|
| 93 |
+
last.text = (last.text ?? []).concat(val)
|
| 94 |
+
continue
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
state = type
|
| 99 |
+
}
|
| 100 |
+
return parts
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
// split at step indirections, then parse each part
|
| 104 |
+
const parserIndir = tokens =>
|
| 105 |
+
splitAt(tokens, findTokens(tokens, '!')).map(parser)
|
| 106 |
+
|
| 107 |
+
export const parse = cfi => {
|
| 108 |
+
const tokens = tokenizer(unwrap(cfi))
|
| 109 |
+
const commas = findTokens(tokens, ',')
|
| 110 |
+
if (!commas.length) return parserIndir(tokens)
|
| 111 |
+
const [parent, start, end] = splitAt(tokens, commas).map(parserIndir)
|
| 112 |
+
return { parent, start, end }
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
const partToString = ({ index, id, offset, temporal, spatial, text, side }) => {
|
| 116 |
+
const param = side ? `;s=${side}` : ''
|
| 117 |
+
return `/${index}`
|
| 118 |
+
+ (id ? `[${escapeCFI(id)}${param}]` : '')
|
| 119 |
+
// "CFI expressions [..] SHOULD include an explicit character offset"
|
| 120 |
+
+ (offset != null && index % 2 ? `:${offset}` : '')
|
| 121 |
+
+ (temporal ? `~${temporal}` : '')
|
| 122 |
+
+ (spatial ? `@${spatial.join(':')}` : '')
|
| 123 |
+
+ (text || (!id && side) ? '['
|
| 124 |
+
+ (text?.map(escapeCFI)?.join(',') ?? '')
|
| 125 |
+
+ param + ']' : '')
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
const toInnerString = parsed => parsed.parent
|
| 129 |
+
? [parsed.parent, parsed.start, parsed.end].map(toInnerString).join(',')
|
| 130 |
+
: parsed.map(parts => parts.map(partToString).join('')).join('!')
|
| 131 |
+
|
| 132 |
+
const toString = parsed => wrap(toInnerString(parsed))
|
| 133 |
+
|
| 134 |
+
export const collapse = (x, toEnd) => typeof x === 'string'
|
| 135 |
+
? toString(collapse(parse(x), toEnd))
|
| 136 |
+
: x.parent ? concatArrays(x.parent, x[toEnd ? 'end' : 'start']) : x
|
| 137 |
+
|
| 138 |
+
// create range CFI from two CFIs
|
| 139 |
+
const buildRange = (from, to) => {
|
| 140 |
+
if (typeof from === 'string') from = parse(from)
|
| 141 |
+
if (typeof to === 'string') to = parse(to)
|
| 142 |
+
from = collapse(from)
|
| 143 |
+
to = collapse(to, true)
|
| 144 |
+
// ranges across multiple documents are not allowed; handle local paths only
|
| 145 |
+
const localFrom = from[from.length - 1], localTo = to[to.length - 1]
|
| 146 |
+
const localParent = [], localStart = [], localEnd = []
|
| 147 |
+
let pushToParent = true
|
| 148 |
+
const len = Math.max(localFrom.length, localTo.length)
|
| 149 |
+
for (let i = 0; i < len; i++) {
|
| 150 |
+
const a = localFrom[i], b = localTo[i]
|
| 151 |
+
pushToParent &&= a?.index === b?.index && !a?.offset && !b?.offset
|
| 152 |
+
if (pushToParent) localParent.push(a)
|
| 153 |
+
else {
|
| 154 |
+
if (a) localStart.push(a)
|
| 155 |
+
if (b) localEnd.push(b)
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
// copy non-local paths from `from`
|
| 159 |
+
const parent = from.slice(0, -1).concat([localParent])
|
| 160 |
+
return toString({ parent, start: [localStart], end: [localEnd] })
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
export const compare = (a, b) => {
|
| 164 |
+
if (typeof a === 'string') a = parse(a)
|
| 165 |
+
if (typeof b === 'string') b = parse(b)
|
| 166 |
+
if (a.start || b.start) return compare(collapse(a), collapse(b))
|
| 167 |
+
|| compare(collapse(a, true), collapse(b, true))
|
| 168 |
+
|
| 169 |
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
| 170 |
+
const p = a[i] ?? [], q = b[i] ?? []
|
| 171 |
+
const maxIndex = Math.max(p.length, q.length) - 1
|
| 172 |
+
for (let i = 0; i <= maxIndex; i++) {
|
| 173 |
+
const x = p[i], y = q[i]
|
| 174 |
+
if (!x) return -1
|
| 175 |
+
if (!y) return 1
|
| 176 |
+
if (x.index > y.index) return 1
|
| 177 |
+
if (x.index < y.index) return -1
|
| 178 |
+
if (i === maxIndex) {
|
| 179 |
+
// TODO: compare temporal & spatial offsets
|
| 180 |
+
if (x.offset > y.offset) return 1
|
| 181 |
+
if (x.offset < y.offset) return -1
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
return 0
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
const isTextNode = ({ nodeType }) => nodeType === 3 || nodeType === 4
|
| 189 |
+
const isElementNode = ({ nodeType }) => nodeType === 1
|
| 190 |
+
|
| 191 |
+
const getChildNodes = (node, filter) => {
|
| 192 |
+
const nodes = Array.from(node.childNodes)
|
| 193 |
+
// "content other than element and character data is ignored"
|
| 194 |
+
.filter(node => isTextNode(node) || isElementNode(node))
|
| 195 |
+
return filter ? nodes.map(node => {
|
| 196 |
+
const accept = filter(node)
|
| 197 |
+
if (accept === NodeFilter.FILTER_REJECT) return null
|
| 198 |
+
else if (accept === NodeFilter.FILTER_SKIP) return getChildNodes(node, filter)
|
| 199 |
+
else return node
|
| 200 |
+
}).flat().filter(x => x) : nodes
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
// child nodes are organized such that the result is always
|
| 204 |
+
// [element, text, element, text, ..., element],
|
| 205 |
+
// regardless of the actual structure in the document;
|
| 206 |
+
// so multiple text nodes need to be combined, and nonexistent ones counted;
|
| 207 |
+
// see "Step Reference to Child Element or Character Data (/)" in EPUB CFI spec
|
| 208 |
+
const indexChildNodes = (node, filter) => {
|
| 209 |
+
const nodes = getChildNodes(node, filter)
|
| 210 |
+
.reduce((arr, node) => {
|
| 211 |
+
let last = arr[arr.length - 1]
|
| 212 |
+
if (!last) arr.push(node)
|
| 213 |
+
// "there is one chunk between each pair of child elements"
|
| 214 |
+
else if (isTextNode(node)) {
|
| 215 |
+
if (Array.isArray(last)) last.push(node)
|
| 216 |
+
else if (isTextNode(last)) arr[arr.length - 1] = [last, node]
|
| 217 |
+
else arr.push(node)
|
| 218 |
+
} else {
|
| 219 |
+
if (isElementNode(last)) arr.push(null, node)
|
| 220 |
+
else arr.push(node)
|
| 221 |
+
}
|
| 222 |
+
return arr
|
| 223 |
+
}, [])
|
| 224 |
+
// "the first chunk is located before the first child element"
|
| 225 |
+
if (isElementNode(nodes[0])) nodes.unshift('first')
|
| 226 |
+
// "the last chunk is located after the last child element"
|
| 227 |
+
if (isElementNode(nodes[nodes.length - 1])) nodes.push('last')
|
| 228 |
+
// "'virtual' elements"
|
| 229 |
+
nodes.unshift('before') // "0 is a valid index"
|
| 230 |
+
nodes.push('after') // "n+2 is a valid index"
|
| 231 |
+
return nodes
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
const partsToNode = (node, parts, filter) => {
|
| 235 |
+
const { id } = parts[parts.length - 1]
|
| 236 |
+
if (id) {
|
| 237 |
+
const el = node.ownerDocument.getElementById(id)
|
| 238 |
+
if (el) return { node: el, offset: 0 }
|
| 239 |
+
}
|
| 240 |
+
for (const { index } of parts) {
|
| 241 |
+
const newNode = node ? indexChildNodes(node, filter)[index] : null
|
| 242 |
+
// handle non-existent nodes
|
| 243 |
+
if (newNode === 'first') return { node: node.firstChild ?? node }
|
| 244 |
+
if (newNode === 'last') return { node: node.lastChild ?? node }
|
| 245 |
+
if (newNode === 'before') return { node, before: true }
|
| 246 |
+
if (newNode === 'after') return { node, after: true }
|
| 247 |
+
node = newNode
|
| 248 |
+
}
|
| 249 |
+
const { offset } = parts[parts.length - 1]
|
| 250 |
+
if (!Array.isArray(node)) return { node, offset }
|
| 251 |
+
// get underlying text node and offset from the chunk
|
| 252 |
+
let sum = 0
|
| 253 |
+
for (const n of node) {
|
| 254 |
+
const { length } = n.nodeValue
|
| 255 |
+
if (sum + length >= offset) return { node: n, offset: offset - sum }
|
| 256 |
+
sum += length
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
const nodeToParts = (node, offset, filter) => {
|
| 261 |
+
const { parentNode, id } = node
|
| 262 |
+
const indexed = indexChildNodes(parentNode, filter)
|
| 263 |
+
const index = indexed.findIndex(x =>
|
| 264 |
+
Array.isArray(x) ? x.some(x => x === node) : x === node)
|
| 265 |
+
// adjust offset as if merging the text nodes in the chunk
|
| 266 |
+
const chunk = indexed[index]
|
| 267 |
+
if (Array.isArray(chunk)) {
|
| 268 |
+
let sum = 0
|
| 269 |
+
for (const x of chunk) {
|
| 270 |
+
if (x === node) {
|
| 271 |
+
sum += offset
|
| 272 |
+
break
|
| 273 |
+
} else sum += x.nodeValue.length
|
| 274 |
+
}
|
| 275 |
+
offset = sum
|
| 276 |
+
}
|
| 277 |
+
const part = { id, index, offset }
|
| 278 |
+
return (parentNode !== node.ownerDocument.documentElement
|
| 279 |
+
? nodeToParts(parentNode, null, filter).concat(part) : [part])
|
| 280 |
+
// remove ignored nodes
|
| 281 |
+
.filter(x => x.index !== -1)
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
export const fromRange = (range, filter) => {
|
| 285 |
+
const { startContainer, startOffset, endContainer, endOffset } = range
|
| 286 |
+
const start = nodeToParts(startContainer, startOffset, filter)
|
| 287 |
+
if (range.collapsed) return toString([start])
|
| 288 |
+
const end = nodeToParts(endContainer, endOffset, filter)
|
| 289 |
+
return buildRange([start], [end])
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
export const toRange = (doc, parts, filter) => {
|
| 293 |
+
const startParts = collapse(parts)
|
| 294 |
+
const endParts = collapse(parts, true)
|
| 295 |
+
|
| 296 |
+
const root = doc.documentElement
|
| 297 |
+
const start = partsToNode(root, startParts[0], filter)
|
| 298 |
+
const end = partsToNode(root, endParts[0], filter)
|
| 299 |
+
|
| 300 |
+
const range = doc.createRange()
|
| 301 |
+
|
| 302 |
+
if (start.before) range.setStartBefore(start.node)
|
| 303 |
+
else if (start.after) range.setStartAfter(start.node)
|
| 304 |
+
else range.setStart(start.node, start.offset)
|
| 305 |
+
|
| 306 |
+
if (end.before) range.setEndBefore(end.node)
|
| 307 |
+
else if (end.after) range.setEndAfter(end.node)
|
| 308 |
+
else range.setEnd(end.node, end.offset)
|
| 309 |
+
return range
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
// faster way of getting CFIs for sorted elements in a single parent
|
| 313 |
+
export const fromElements = elements => {
|
| 314 |
+
const results = []
|
| 315 |
+
const { parentNode } = elements[0]
|
| 316 |
+
const parts = nodeToParts(parentNode)
|
| 317 |
+
for (const [index, node] of indexChildNodes(parentNode).entries()) {
|
| 318 |
+
const el = elements[results.length]
|
| 319 |
+
if (node === el)
|
| 320 |
+
results.push(toString([parts.concat({ id: el.id, index })]))
|
| 321 |
+
}
|
| 322 |
+
return results
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
export const toElement = (doc, parts) =>
|
| 326 |
+
partsToNode(doc.documentElement, collapse(parts)).node
|
| 327 |
+
|
| 328 |
+
// turn indices into standard CFIs when you don't have an actual package document
|
| 329 |
+
export const fake = {
|
| 330 |
+
fromIndex: index => wrap(`/6/${(index + 1) * 2}`),
|
| 331 |
+
toIndex: parts => parts?.at(-1).index / 2 - 1,
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
// get CFI from Calibre bookmarks
|
| 335 |
+
// see https://github.com/johnfactotum/foliate/issues/849
|
| 336 |
+
export const fromCalibrePos = pos => {
|
| 337 |
+
const [parts] = parse(pos)
|
| 338 |
+
const item = parts.shift()
|
| 339 |
+
parts.shift()
|
| 340 |
+
return toString([[{ index: 6 }, item], parts])
|
| 341 |
+
}
|
| 342 |
+
export const fromCalibreHighlight = ({ spine_index, start_cfi, end_cfi }) => {
|
| 343 |
+
const pre = fake.fromIndex(spine_index) + '!'
|
| 344 |
+
return buildRange(pre + start_cfi.slice(2), pre + end_cfi.slice(2))
|
| 345 |
+
}
|
packages/foliate-js/eslint.config.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import js from '@eslint/js'
|
| 2 |
+
import globals from 'globals'
|
| 3 |
+
|
| 4 |
+
export default [js.configs.recommended, { ignores: ['vendor'] }, {
|
| 5 |
+
languageOptions: {
|
| 6 |
+
globals: globals.browser,
|
| 7 |
+
},
|
| 8 |
+
linterOptions: {
|
| 9 |
+
reportUnusedDisableDirectives: true,
|
| 10 |
+
},
|
| 11 |
+
rules: {
|
| 12 |
+
semi: ['error', 'never'],
|
| 13 |
+
indent: ['warn', 4, { flatTernaryExpressions: true, SwitchCase: 1 }],
|
| 14 |
+
quotes: ['warn', 'single', { avoidEscape: true }],
|
| 15 |
+
'comma-dangle': ['warn', 'always-multiline'],
|
| 16 |
+
'no-trailing-spaces': 'warn',
|
| 17 |
+
'no-unused-vars': 'warn',
|
| 18 |
+
'no-console': ['warn', { allow: ['debug', 'warn', 'error', 'assert'] }],
|
| 19 |
+
'no-constant-condition': ['error', { checkLoops: false }],
|
| 20 |
+
'no-empty': ['error', { allowEmptyCatch: true }],
|
| 21 |
+
},
|
| 22 |
+
}]
|
packages/foliate-js/fb2.js
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
const normalizeWhitespace = str => str ? str
|
| 2 |
+
.replace(/[\t\n\f\r ]+/g, ' ')
|
| 3 |
+
.replace(/^[\t\n\f\r ]+/, '')
|
| 4 |
+
.replace(/[\t\n\f\r ]+$/, '') : ''
|
| 5 |
+
const getElementText = el => normalizeWhitespace(el?.textContent)
|
| 6 |
+
|
| 7 |
+
const NS = {
|
| 8 |
+
XLINK: 'http://www.w3.org/1999/xlink',
|
| 9 |
+
EPUB: 'http://www.idpf.org/2007/ops',
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
const MIME = {
|
| 13 |
+
XML: 'application/xml',
|
| 14 |
+
XHTML: 'application/xhtml+xml',
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const STYLE = {
|
| 18 |
+
'strong': ['strong', 'self'],
|
| 19 |
+
'emphasis': ['em', 'self'],
|
| 20 |
+
'style': ['span', 'self'],
|
| 21 |
+
'a': 'anchor',
|
| 22 |
+
'strikethrough': ['s', 'self'],
|
| 23 |
+
'sub': ['sub', 'self'],
|
| 24 |
+
'sup': ['sup', 'self'],
|
| 25 |
+
'code': ['code', 'self'],
|
| 26 |
+
'image': 'image',
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
const TABLE = {
|
| 30 |
+
'tr': ['tr', {
|
| 31 |
+
'th': ['th', STYLE, ['colspan', 'rowspan', 'align', 'valign']],
|
| 32 |
+
'td': ['td', STYLE, ['colspan', 'rowspan', 'align', 'valign']],
|
| 33 |
+
}, ['align']],
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const POEM = {
|
| 37 |
+
'epigraph': ['blockquote'],
|
| 38 |
+
'subtitle': ['h2', STYLE],
|
| 39 |
+
'text-author': ['p', STYLE],
|
| 40 |
+
'date': ['p', STYLE],
|
| 41 |
+
'stanza': ['div', 'self'],
|
| 42 |
+
'v': ['div', STYLE],
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
const SECTION = {
|
| 46 |
+
'title': ['header', {
|
| 47 |
+
'p': ['h1', STYLE],
|
| 48 |
+
'empty-line': ['br'],
|
| 49 |
+
}],
|
| 50 |
+
'epigraph': ['blockquote', 'self'],
|
| 51 |
+
'image': 'image',
|
| 52 |
+
'annotation': ['aside'],
|
| 53 |
+
'section': ['section', 'self'],
|
| 54 |
+
'p': ['p', STYLE],
|
| 55 |
+
'poem': ['blockquote', POEM],
|
| 56 |
+
'subtitle': ['h2', STYLE],
|
| 57 |
+
'cite': ['blockquote', 'self'],
|
| 58 |
+
'empty-line': ['br'],
|
| 59 |
+
'table': ['table', TABLE],
|
| 60 |
+
'text-author': ['p', STYLE],
|
| 61 |
+
}
|
| 62 |
+
POEM['epigraph'].push(SECTION)
|
| 63 |
+
|
| 64 |
+
const BODY = {
|
| 65 |
+
'image': 'image',
|
| 66 |
+
'title': ['section', {
|
| 67 |
+
'p': ['h1', STYLE],
|
| 68 |
+
'empty-line': ['br'],
|
| 69 |
+
}],
|
| 70 |
+
'epigraph': ['section', SECTION],
|
| 71 |
+
'section': ['section', SECTION],
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
class FB2Converter {
|
| 75 |
+
constructor(fb2) {
|
| 76 |
+
this.fb2 = fb2
|
| 77 |
+
this.doc = document.implementation.createDocument(NS.XHTML, 'html')
|
| 78 |
+
// use this instead of `getElementById` to allow images like
|
| 79 |
+
// `<image l:href="#img1.jpg" id="img1.jpg" />`
|
| 80 |
+
this.bins = new Map(Array.from(this.fb2.getElementsByTagName('binary'),
|
| 81 |
+
el => [el.id, el]))
|
| 82 |
+
}
|
| 83 |
+
getImageSrc(el) {
|
| 84 |
+
const href = el.getAttributeNS(NS.XLINK, 'href')
|
| 85 |
+
if (!href) return 'data:,'
|
| 86 |
+
const [, id] = href.split('#')
|
| 87 |
+
if (!id) return href
|
| 88 |
+
const bin = this.bins.get(id)
|
| 89 |
+
return bin
|
| 90 |
+
? `data:${bin.getAttribute('content-type')};base64,${bin.textContent}`
|
| 91 |
+
: href
|
| 92 |
+
}
|
| 93 |
+
image(node) {
|
| 94 |
+
const el = this.doc.createElement('img')
|
| 95 |
+
el.alt = node.getAttribute('alt')
|
| 96 |
+
el.title = node.getAttribute('title')
|
| 97 |
+
el.setAttribute('src', this.getImageSrc(node))
|
| 98 |
+
return el
|
| 99 |
+
}
|
| 100 |
+
anchor(node) {
|
| 101 |
+
const el = this.convert(node, { 'a': ['a', STYLE] })
|
| 102 |
+
el.setAttribute('href', node.getAttributeNS(NS.XLINK, 'href'))
|
| 103 |
+
if (node.getAttribute('type') === 'note')
|
| 104 |
+
el.setAttributeNS(NS.EPUB, 'epub:type', 'noteref')
|
| 105 |
+
return el
|
| 106 |
+
}
|
| 107 |
+
convert(node, def) {
|
| 108 |
+
// not an element; return text content
|
| 109 |
+
if (node.nodeType === 3) return this.doc.createTextNode(node.textContent)
|
| 110 |
+
if (node.nodeType === 4) return this.doc.createCDATASection(node.textContent)
|
| 111 |
+
if (node.nodeType === 8) return this.doc.createComment(node.textContent)
|
| 112 |
+
|
| 113 |
+
const d = def?.[node.nodeName]
|
| 114 |
+
if (!d) return null
|
| 115 |
+
if (typeof d === 'string') return this[d](node)
|
| 116 |
+
|
| 117 |
+
const [name, opts, attrs] = d
|
| 118 |
+
const el = this.doc.createElement(name)
|
| 119 |
+
|
| 120 |
+
// copy the ID, and set class name from original element name
|
| 121 |
+
if (node.id) el.id = node.id
|
| 122 |
+
el.classList.add(node.nodeName)
|
| 123 |
+
|
| 124 |
+
// copy attributes
|
| 125 |
+
if (Array.isArray(attrs)) for (const attr of attrs) {
|
| 126 |
+
const value = node.getAttribute(attr)
|
| 127 |
+
if (value) el.setAttribute(attr, value)
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
// process child elements recursively
|
| 131 |
+
const childDef = opts === 'self' ? def : opts
|
| 132 |
+
let child = node.firstChild
|
| 133 |
+
while (child) {
|
| 134 |
+
const childEl = this.convert(child, childDef)
|
| 135 |
+
if (childEl) el.append(childEl)
|
| 136 |
+
child = child.nextSibling
|
| 137 |
+
}
|
| 138 |
+
return el
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
const parseXML = async blob => {
|
| 143 |
+
const buffer = await blob.arrayBuffer()
|
| 144 |
+
const str = new TextDecoder('utf-8').decode(buffer)
|
| 145 |
+
const parser = new DOMParser()
|
| 146 |
+
const doc = parser.parseFromString(str, MIME.XML)
|
| 147 |
+
const encoding = doc.xmlEncoding
|
| 148 |
+
// `Document.xmlEncoding` is deprecated, and already removed in Firefox
|
| 149 |
+
// so parse the XML declaration manually
|
| 150 |
+
|| str.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1]
|
| 151 |
+
if (encoding && encoding.toLowerCase() !== 'utf-8') {
|
| 152 |
+
const str = new TextDecoder(encoding).decode(buffer)
|
| 153 |
+
return parser.parseFromString(str, MIME.XML)
|
| 154 |
+
}
|
| 155 |
+
return doc
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
const style = URL.createObjectURL(new Blob([`
|
| 159 |
+
@namespace epub "http://www.idpf.org/2007/ops";
|
| 160 |
+
body > img, section > img {
|
| 161 |
+
display: block;
|
| 162 |
+
margin: auto;
|
| 163 |
+
}
|
| 164 |
+
.title h1 {
|
| 165 |
+
text-align: center;
|
| 166 |
+
}
|
| 167 |
+
body > section > .title, body.notesBodyType > .title {
|
| 168 |
+
margin: 3em 0;
|
| 169 |
+
}
|
| 170 |
+
body.notesBodyType > section .title h1 {
|
| 171 |
+
text-align: start;
|
| 172 |
+
}
|
| 173 |
+
body.notesBodyType > section .title {
|
| 174 |
+
margin: 1em 0;
|
| 175 |
+
}
|
| 176 |
+
p {
|
| 177 |
+
text-indent: 1em;
|
| 178 |
+
margin: 0;
|
| 179 |
+
}
|
| 180 |
+
:not(p) + p, p:first-child {
|
| 181 |
+
text-indent: 0;
|
| 182 |
+
}
|
| 183 |
+
.stanza {
|
| 184 |
+
text-indent: 0;
|
| 185 |
+
margin: 1em 0;
|
| 186 |
+
}
|
| 187 |
+
.text-author, .date {
|
| 188 |
+
text-align: end;
|
| 189 |
+
}
|
| 190 |
+
.text-author:before {
|
| 191 |
+
content: "—";
|
| 192 |
+
}
|
| 193 |
+
table {
|
| 194 |
+
border-collapse: collapse;
|
| 195 |
+
}
|
| 196 |
+
td, th {
|
| 197 |
+
padding: .25em;
|
| 198 |
+
}
|
| 199 |
+
a[epub|type~="noteref"] {
|
| 200 |
+
font-size: .75em;
|
| 201 |
+
vertical-align: super;
|
| 202 |
+
}
|
| 203 |
+
body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {
|
| 204 |
+
margin: 3em 0;
|
| 205 |
+
}
|
| 206 |
+
`], { type: 'text/css' }))
|
| 207 |
+
|
| 208 |
+
const template = html => `<?xml version="1.0" encoding="utf-8"?>
|
| 209 |
+
<html xmlns="http://www.w3.org/1999/xhtml">
|
| 210 |
+
<head><link href="${style}" rel="stylesheet" type="text/css"/></head>
|
| 211 |
+
<body>${html}</body>
|
| 212 |
+
</html>`
|
| 213 |
+
|
| 214 |
+
// name of custom ID attribute for TOC items
|
| 215 |
+
const dataID = 'data-foliate-id'
|
| 216 |
+
|
| 217 |
+
export const makeFB2 = async blob => {
|
| 218 |
+
const book = {}
|
| 219 |
+
const doc = await parseXML(blob)
|
| 220 |
+
const converter = new FB2Converter(doc)
|
| 221 |
+
|
| 222 |
+
const $ = x => doc.querySelector(x)
|
| 223 |
+
const $$ = x => [...doc.querySelectorAll(x)]
|
| 224 |
+
const getPerson = el => {
|
| 225 |
+
const nick = getElementText(el.querySelector('nickname'))
|
| 226 |
+
if (nick) return nick
|
| 227 |
+
const first = getElementText(el.querySelector('first-name'))
|
| 228 |
+
const middle = getElementText(el.querySelector('middle-name'))
|
| 229 |
+
const last = getElementText(el.querySelector('last-name'))
|
| 230 |
+
const name = [first, middle, last].filter(x => x).join(' ')
|
| 231 |
+
const sortAs = last
|
| 232 |
+
? [last, [first, middle].filter(x => x).join(' ')].join(', ')
|
| 233 |
+
: null
|
| 234 |
+
return { name, sortAs }
|
| 235 |
+
}
|
| 236 |
+
const getDate = el => el?.getAttribute('value') ?? getElementText(el)
|
| 237 |
+
const annotation = $('title-info annotation')
|
| 238 |
+
book.metadata = {
|
| 239 |
+
title: getElementText($('title-info book-title')),
|
| 240 |
+
identifier: getElementText($('document-info id')),
|
| 241 |
+
language: getElementText($('title-info lang')),
|
| 242 |
+
author: $$('title-info author').map(getPerson),
|
| 243 |
+
translator: $$('title-info translator').map(getPerson),
|
| 244 |
+
contributor: $$('document-info author').map(getPerson)
|
| 245 |
+
// techincially the program probably shouldn't get the `bkp` role
|
| 246 |
+
// but it has been so used by calibre, so ¯\_(ツ)_/¯
|
| 247 |
+
.concat($$('document-info program-used').map(getElementText))
|
| 248 |
+
.map(x => Object.assign(typeof x === 'string' ? { name: x } : x,
|
| 249 |
+
{ role: 'bkp' })),
|
| 250 |
+
publisher: getElementText($('publish-info publisher')),
|
| 251 |
+
published: getDate($('title-info date')),
|
| 252 |
+
modified: getDate($('document-info date')),
|
| 253 |
+
description: annotation ? converter.convert(annotation,
|
| 254 |
+
{ annotation: ['div', SECTION] }).innerHTML : null,
|
| 255 |
+
subject: $$('title-info genre').map(getElementText),
|
| 256 |
+
}
|
| 257 |
+
if ($('coverpage image')) {
|
| 258 |
+
const src = converter.getImageSrc($('coverpage image'))
|
| 259 |
+
book.getCover = () => fetch(src).then(res => res.blob())
|
| 260 |
+
} else book.getCover = () => null
|
| 261 |
+
|
| 262 |
+
// get convert each body
|
| 263 |
+
const bodyData = Array.from(doc.querySelectorAll('body'), body => {
|
| 264 |
+
const converted = converter.convert(body, { body: ['body', BODY] })
|
| 265 |
+
return [Array.from(converted.children, el => {
|
| 266 |
+
// get list of IDs in the section
|
| 267 |
+
const ids = [el, ...el.querySelectorAll('[id]')].map(el => el.id)
|
| 268 |
+
return { el, ids }
|
| 269 |
+
}), converted]
|
| 270 |
+
})
|
| 271 |
+
|
| 272 |
+
const urls = []
|
| 273 |
+
const sectionData = bodyData[0][0]
|
| 274 |
+
// make a separate section for each section in the first body
|
| 275 |
+
.map(({ el, ids }, id) => {
|
| 276 |
+
// set up titles for TOC
|
| 277 |
+
const titles = Array.from(
|
| 278 |
+
el.querySelectorAll(':scope > section > .title'),
|
| 279 |
+
(el, index) => {
|
| 280 |
+
el.setAttribute(dataID, index)
|
| 281 |
+
const section = el.closest('section')
|
| 282 |
+
const size = new TextEncoder().encode(section.innerHTML).length
|
| 283 |
+
- Array.from(section.querySelectorAll('[src]'))
|
| 284 |
+
.reduce((sum, el) => sum + (el.getAttribute('src')?.length ?? 0), 0)
|
| 285 |
+
return { title: getElementText(el), index, size, href: `${id}#${index}` }
|
| 286 |
+
})
|
| 287 |
+
return { ids, titles, el }
|
| 288 |
+
})
|
| 289 |
+
// for additional bodies, only make one section for each body
|
| 290 |
+
.concat(bodyData.slice(1).map(([sections, body]) => {
|
| 291 |
+
const ids = sections.map(s => s.ids).flat()
|
| 292 |
+
body.classList.add('notesBodyType')
|
| 293 |
+
return { ids, el: body, linear: 'no' }
|
| 294 |
+
}))
|
| 295 |
+
.map(({ ids, titles, el, linear }) => {
|
| 296 |
+
const str = template(el.outerHTML)
|
| 297 |
+
const blob = new Blob([str], { type: MIME.XHTML })
|
| 298 |
+
const url = URL.createObjectURL(blob)
|
| 299 |
+
urls.push(url)
|
| 300 |
+
const title = normalizeWhitespace(
|
| 301 |
+
el.querySelector('.title, .subtitle, p')?.textContent
|
| 302 |
+
?? (el.classList.contains('title') ? el.textContent : ''))
|
| 303 |
+
return {
|
| 304 |
+
ids, title, titles, load: () => url,
|
| 305 |
+
createDocument: () => new DOMParser().parseFromString(str, MIME.XHTML),
|
| 306 |
+
// doo't count image data as it'd skew the size too much
|
| 307 |
+
size: blob.size - Array.from(el.querySelectorAll('[src]'),
|
| 308 |
+
el => el.getAttribute('src')?.length ?? 0)
|
| 309 |
+
.reduce((a, b) => a + b, 0),
|
| 310 |
+
linear,
|
| 311 |
+
}
|
| 312 |
+
})
|
| 313 |
+
|
| 314 |
+
const idMap = new Map()
|
| 315 |
+
book.sections = sectionData.map((section, index) => {
|
| 316 |
+
const { ids, load, createDocument, size, linear, titles } = section
|
| 317 |
+
for (const id of ids) if (id) idMap.set(id, index)
|
| 318 |
+
return { id: index, load, createDocument, size, linear, subitems: titles }
|
| 319 |
+
})
|
| 320 |
+
|
| 321 |
+
book.toc = sectionData.map(({ title, titles }, index) => {
|
| 322 |
+
const id = index.toString()
|
| 323 |
+
return {
|
| 324 |
+
label: title,
|
| 325 |
+
href: id,
|
| 326 |
+
subitems: titles?.length ? titles.map(({ title, index }) => ({
|
| 327 |
+
label: title,
|
| 328 |
+
href: `${id}#${index}`,
|
| 329 |
+
})) : null,
|
| 330 |
+
}
|
| 331 |
+
}).filter(item => item)
|
| 332 |
+
|
| 333 |
+
book.resolveHref = href => {
|
| 334 |
+
const [a, b] = href.split('#')
|
| 335 |
+
return a
|
| 336 |
+
// the link is from the TOC
|
| 337 |
+
? { index: Number(a), anchor: doc => doc.querySelector(`[${dataID}="${b}"]`) }
|
| 338 |
+
// link from within the page
|
| 339 |
+
: { index: idMap.get(b), anchor: doc => doc.getElementById(b) }
|
| 340 |
+
}
|
| 341 |
+
book.splitTOCHref = href => href?.split('#')?.map(x => Number(x)) ?? []
|
| 342 |
+
book.getTOCFragment = (doc, id) => doc.querySelector(`[${dataID}="${id}"]`)
|
| 343 |
+
|
| 344 |
+
book.destroy = () => {
|
| 345 |
+
for (const url of urls) URL.revokeObjectURL(url)
|
| 346 |
+
}
|
| 347 |
+
return book
|
| 348 |
+
}
|
packages/foliate-js/fixed-layout.js
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import 'construct-style-sheets-polyfill'
|
| 2 |
+
|
| 3 |
+
const parseViewport = str => str
|
| 4 |
+
?.split(/[,;\s]/) // NOTE: technically, only the comma is valid
|
| 5 |
+
?.filter(x => x)
|
| 6 |
+
?.map(x => x.split('=').map(x => x.trim()))
|
| 7 |
+
|
| 8 |
+
const getViewport = (doc, viewport) => {
|
| 9 |
+
// use `viewBox` for SVG
|
| 10 |
+
if (doc.documentElement.localName === 'svg') {
|
| 11 |
+
const [, , width, height] = doc.documentElement
|
| 12 |
+
.getAttribute('viewBox')?.split(/\s/) ?? []
|
| 13 |
+
return { width, height }
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
// get `viewport` `meta` element
|
| 17 |
+
const meta = parseViewport(doc.querySelector('meta[name="viewport"]')
|
| 18 |
+
?.getAttribute('content'))
|
| 19 |
+
if (meta) return Object.fromEntries(meta)
|
| 20 |
+
|
| 21 |
+
// fallback to book's viewport
|
| 22 |
+
if (typeof viewport === 'string') return parseViewport(viewport)
|
| 23 |
+
if (viewport?.width && viewport.height) return viewport
|
| 24 |
+
|
| 25 |
+
// if no viewport (possibly with image directly in spine), get image size
|
| 26 |
+
const img = doc.querySelector('img')
|
| 27 |
+
if (img) return { width: img.naturalWidth, height: img.naturalHeight }
|
| 28 |
+
|
| 29 |
+
// just show *something*, i guess...
|
| 30 |
+
console.warn(new Error('Missing viewport properties'))
|
| 31 |
+
return { width: 1000, height: 2000 }
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
export class FixedLayout extends HTMLElement {
|
| 35 |
+
static observedAttributes = ['zoom', 'scale-factor', 'spread']
|
| 36 |
+
#root = this.attachShadow({ mode: 'open' })
|
| 37 |
+
#observer = new ResizeObserver(() => this.#render())
|
| 38 |
+
#spreads
|
| 39 |
+
#index = -1
|
| 40 |
+
defaultViewport
|
| 41 |
+
spread
|
| 42 |
+
#portrait = false
|
| 43 |
+
#left
|
| 44 |
+
#right
|
| 45 |
+
#center
|
| 46 |
+
#side
|
| 47 |
+
#zoom
|
| 48 |
+
#scaleFactor = 1.0
|
| 49 |
+
#totalScaleFactor = 1.0
|
| 50 |
+
#scrollLocked = false
|
| 51 |
+
#isOverflowX = false
|
| 52 |
+
#isOverflowY = false
|
| 53 |
+
#preloadCache = new Map()
|
| 54 |
+
#prerenderedSpreads = new Map()
|
| 55 |
+
#spreadAccessTime = new Map()
|
| 56 |
+
#maxConcurrentPreloads = 1
|
| 57 |
+
#numPrerenderedSpreads = 1
|
| 58 |
+
#maxCachedSpreads = 2
|
| 59 |
+
#preloadQueue = []
|
| 60 |
+
#activePreloads = 0
|
| 61 |
+
constructor() {
|
| 62 |
+
super()
|
| 63 |
+
|
| 64 |
+
const sheet = new CSSStyleSheet()
|
| 65 |
+
this.#root.adoptedStyleSheets = [sheet]
|
| 66 |
+
sheet.replaceSync(`:host {
|
| 67 |
+
width: 100%;
|
| 68 |
+
height: 100%;
|
| 69 |
+
display: flex;
|
| 70 |
+
justify-content: flex-start;
|
| 71 |
+
align-items: center;
|
| 72 |
+
overflow: auto;
|
| 73 |
+
}
|
| 74 |
+
@supports (justify-content: safe center) {
|
| 75 |
+
:host {
|
| 76 |
+
justify-content: safe center;
|
| 77 |
+
}
|
| 78 |
+
}`)
|
| 79 |
+
|
| 80 |
+
this.#observer.observe(this)
|
| 81 |
+
}
|
| 82 |
+
attributeChangedCallback(name, _, value) {
|
| 83 |
+
switch (name) {
|
| 84 |
+
case 'zoom':
|
| 85 |
+
this.#zoom = value !== 'fit-width' && value !== 'fit-page'
|
| 86 |
+
? parseFloat(value) : value
|
| 87 |
+
this.#render()
|
| 88 |
+
break
|
| 89 |
+
case 'scale-factor':
|
| 90 |
+
this.#scaleFactor = parseFloat(value) / 100
|
| 91 |
+
this.#render()
|
| 92 |
+
break
|
| 93 |
+
case 'spread':
|
| 94 |
+
this.#respread(value)
|
| 95 |
+
break
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
async #createFrame({ index, src: srcOption, detached = false }) {
|
| 99 |
+
const srcOptionIsString = typeof srcOption === 'string'
|
| 100 |
+
const src = srcOptionIsString ? srcOption : srcOption?.src
|
| 101 |
+
const data = srcOptionIsString ? null : srcOption?.data
|
| 102 |
+
const onZoom = srcOptionIsString ? null : srcOption?.onZoom
|
| 103 |
+
const element = document.createElement('div')
|
| 104 |
+
element.setAttribute('dir', 'ltr')
|
| 105 |
+
const iframe = document.createElement('iframe')
|
| 106 |
+
element.append(iframe)
|
| 107 |
+
Object.assign(iframe.style, {
|
| 108 |
+
border: '0',
|
| 109 |
+
display: 'none',
|
| 110 |
+
overflow: 'hidden',
|
| 111 |
+
})
|
| 112 |
+
// `allow-scripts` is needed for events because of WebKit bug
|
| 113 |
+
// https://bugs.webkit.org/show_bug.cgi?id=218086
|
| 114 |
+
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
|
| 115 |
+
iframe.setAttribute('scrolling', 'no')
|
| 116 |
+
iframe.setAttribute('part', 'filter')
|
| 117 |
+
this.#root.append(element)
|
| 118 |
+
|
| 119 |
+
if (detached) {
|
| 120 |
+
Object.assign(element.style, {
|
| 121 |
+
position: 'absolute',
|
| 122 |
+
visibility: 'hidden',
|
| 123 |
+
pointerEvents: 'none',
|
| 124 |
+
})
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
if (!src) return { blank: true, element, iframe }
|
| 128 |
+
return new Promise(resolve => {
|
| 129 |
+
iframe.addEventListener('load', () => {
|
| 130 |
+
const doc = iframe.contentDocument
|
| 131 |
+
this.dispatchEvent(new CustomEvent('load', { detail: { doc, index } }))
|
| 132 |
+
const { width, height } = getViewport(doc, this.defaultViewport)
|
| 133 |
+
resolve({
|
| 134 |
+
element, iframe,
|
| 135 |
+
width: parseFloat(width),
|
| 136 |
+
height: parseFloat(height),
|
| 137 |
+
onZoom,
|
| 138 |
+
detached,
|
| 139 |
+
})
|
| 140 |
+
}, { once: true })
|
| 141 |
+
if (data) {
|
| 142 |
+
iframe.srcdoc = data
|
| 143 |
+
} else {
|
| 144 |
+
iframe.src = src
|
| 145 |
+
}
|
| 146 |
+
})
|
| 147 |
+
}
|
| 148 |
+
#render(side = this.#side) {
|
| 149 |
+
if (!side) return
|
| 150 |
+
const left = this.#left ?? {}
|
| 151 |
+
const right = this.#center ?? this.#right ?? {}
|
| 152 |
+
const target = side === 'left' ? left : right
|
| 153 |
+
const { width, height } = this.getBoundingClientRect()
|
| 154 |
+
// for unfolded devices with slightly taller height than width also use landscape layout
|
| 155 |
+
const portrait = this.spread !== 'both' && this.spread !== 'portrait'
|
| 156 |
+
&& height > width * 1.2
|
| 157 |
+
this.#portrait = portrait
|
| 158 |
+
const blankWidth = left.width ?? right.width ?? 0
|
| 159 |
+
const blankHeight = left.height ?? right.height ?? 0
|
| 160 |
+
|
| 161 |
+
let scale = typeof this.#zoom === 'number' && !isNaN(this.#zoom)
|
| 162 |
+
? this.#zoom
|
| 163 |
+
: (this.#zoom === 'fit-width'
|
| 164 |
+
? (portrait || this.#center
|
| 165 |
+
? width / (target.width ?? blankWidth)
|
| 166 |
+
: width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)))
|
| 167 |
+
: (portrait || this.#center
|
| 168 |
+
? Math.min(
|
| 169 |
+
width / (target.width ?? blankWidth),
|
| 170 |
+
height / (target.height ?? blankHeight))
|
| 171 |
+
: Math.min(
|
| 172 |
+
width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)),
|
| 173 |
+
height / Math.max(
|
| 174 |
+
left.height ?? blankHeight,
|
| 175 |
+
right.height ?? blankHeight)))
|
| 176 |
+
) || 1
|
| 177 |
+
|
| 178 |
+
scale *= this.#scaleFactor
|
| 179 |
+
this.#totalScaleFactor = scale
|
| 180 |
+
|
| 181 |
+
const transform = ({frame, styles}) => {
|
| 182 |
+
let { element, iframe, width, height, blank, onZoom } = frame
|
| 183 |
+
if (!iframe) return
|
| 184 |
+
if (onZoom) onZoom({ doc: frame.iframe.contentDocument, scale })
|
| 185 |
+
const iframeScale = onZoom ? scale : 1
|
| 186 |
+
const zoomedOut = this.#scaleFactor < 1.0
|
| 187 |
+
Object.assign(iframe.style, {
|
| 188 |
+
width: `${width * iframeScale}px`,
|
| 189 |
+
height: `${height * iframeScale}px`,
|
| 190 |
+
transform: onZoom ? 'none' : `scale(${scale})`,
|
| 191 |
+
transformOrigin: 'top left',
|
| 192 |
+
display: blank ? 'none' : 'block',
|
| 193 |
+
})
|
| 194 |
+
Object.assign(element.style, {
|
| 195 |
+
width: `${(width ?? blankWidth) * scale}px`,
|
| 196 |
+
height: `${(height ?? blankHeight) * scale}px`,
|
| 197 |
+
flexShrink: '0',
|
| 198 |
+
display: zoomedOut ? 'flex' : 'block',
|
| 199 |
+
marginBlock: zoomedOut ? undefined : 'auto',
|
| 200 |
+
alignItems: zoomedOut ? 'center' : undefined,
|
| 201 |
+
justifyContent: zoomedOut ? 'center' : undefined,
|
| 202 |
+
...styles,
|
| 203 |
+
})
|
| 204 |
+
if (portrait && frame !== target) {
|
| 205 |
+
element.style.display = 'none'
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
const container= element.parentNode.host
|
| 209 |
+
const containerWidth = container.clientWidth
|
| 210 |
+
const containerHeight = container.clientHeight
|
| 211 |
+
container.scrollLeft = (element.clientWidth - containerWidth) / 2
|
| 212 |
+
|
| 213 |
+
return {
|
| 214 |
+
width: element.clientWidth,
|
| 215 |
+
height: element.clientHeight,
|
| 216 |
+
containerWidth,
|
| 217 |
+
containerHeight,
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
if (this.#center) {
|
| 221 |
+
const dimensions = transform({frame: this.#center, styles: { marginInline: 'auto' }})
|
| 222 |
+
const {width, height, containerWidth, containerHeight} = dimensions
|
| 223 |
+
this.#isOverflowX = width > containerWidth
|
| 224 |
+
this.#isOverflowY = height > containerHeight
|
| 225 |
+
} else {
|
| 226 |
+
const leftDimensions = transform({frame: left, styles: { marginInlineStart: 'auto' }})
|
| 227 |
+
const rightDimensions = transform({frame: right, styles: { marginInlineEnd: 'auto' }})
|
| 228 |
+
const {width: leftWidth, height: leftHeight, containerWidth, containerHeight} = leftDimensions
|
| 229 |
+
const {width: rightWidth, height: rightHeight} = rightDimensions
|
| 230 |
+
this.#isOverflowX = leftWidth + rightWidth > containerWidth
|
| 231 |
+
this.#isOverflowY = Math.max(leftHeight, rightHeight) > containerHeight
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
async #showSpread({ left, right, center, side, spreadIndex }) {
|
| 235 |
+
this.#left = null
|
| 236 |
+
this.#right = null
|
| 237 |
+
this.#center = null
|
| 238 |
+
|
| 239 |
+
const cacheKey = spreadIndex !== undefined ? `spread-${spreadIndex}` : null
|
| 240 |
+
const prerendered = cacheKey ? this.#prerenderedSpreads.get(cacheKey) : null
|
| 241 |
+
|
| 242 |
+
if (prerendered) {
|
| 243 |
+
this.#spreadAccessTime.set(cacheKey, Date.now())
|
| 244 |
+
if (prerendered.center) {
|
| 245 |
+
this.#center = prerendered.center
|
| 246 |
+
} else {
|
| 247 |
+
this.#left = prerendered.left
|
| 248 |
+
this.#right = prerendered.right
|
| 249 |
+
}
|
| 250 |
+
} else {
|
| 251 |
+
if (center) {
|
| 252 |
+
this.#center = await this.#createFrame(center)
|
| 253 |
+
if (cacheKey) {
|
| 254 |
+
this.#prerenderedSpreads.set(cacheKey, { center: this.#center })
|
| 255 |
+
this.#spreadAccessTime.set(cacheKey, Date.now())
|
| 256 |
+
}
|
| 257 |
+
} else {
|
| 258 |
+
this.#left = await this.#createFrame(left)
|
| 259 |
+
this.#right = await this.#createFrame(right)
|
| 260 |
+
if (cacheKey) {
|
| 261 |
+
this.#prerenderedSpreads.set(cacheKey, { left: this.#left, right: this.#right })
|
| 262 |
+
this.#spreadAccessTime.set(cacheKey, Date.now())
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
this.#side = center ? 'center' : this.#left.blank ? 'right'
|
| 268 |
+
: this.#right.blank ? 'left' : side
|
| 269 |
+
const visibleFrames = center
|
| 270 |
+
? [this.#center?.element]
|
| 271 |
+
: [this.#left?.element, this.#right?.element]
|
| 272 |
+
|
| 273 |
+
Array.from(this.#root.children).forEach(child => {
|
| 274 |
+
const isVisible = visibleFrames.includes(child)
|
| 275 |
+
Object.assign(child.style, {
|
| 276 |
+
position: isVisible ? 'relative' : 'absolute',
|
| 277 |
+
visibility: isVisible ? 'visible' : 'hidden',
|
| 278 |
+
pointerEvents: isVisible ? 'auto' : 'none',
|
| 279 |
+
})
|
| 280 |
+
})
|
| 281 |
+
this.#render()
|
| 282 |
+
}
|
| 283 |
+
#goLeft() {
|
| 284 |
+
if (this.#center || this.#left?.blank) return
|
| 285 |
+
if (this.#portrait && this.#left?.element?.style?.display === 'none') {
|
| 286 |
+
this.#side = 'left'
|
| 287 |
+
this.#render()
|
| 288 |
+
this.#reportLocation('page')
|
| 289 |
+
return true
|
| 290 |
+
}
|
| 291 |
+
}
|
| 292 |
+
#goRight() {
|
| 293 |
+
if (this.#center || this.#right?.blank) return
|
| 294 |
+
if (this.#portrait && this.#right?.element?.style?.display === 'none') {
|
| 295 |
+
this.#side = 'right'
|
| 296 |
+
this.#render()
|
| 297 |
+
this.#reportLocation('page')
|
| 298 |
+
return true
|
| 299 |
+
}
|
| 300 |
+
}
|
| 301 |
+
open(book) {
|
| 302 |
+
this.book = book
|
| 303 |
+
this.defaultViewport = book.rendition?.viewport
|
| 304 |
+
this.rtl = book.dir === 'rtl'
|
| 305 |
+
|
| 306 |
+
this.#spread()
|
| 307 |
+
}
|
| 308 |
+
#spread(mode) {
|
| 309 |
+
const book = this.book
|
| 310 |
+
const { rendition } = book
|
| 311 |
+
const rtl = this.rtl
|
| 312 |
+
const ltr = !rtl
|
| 313 |
+
this.spread = mode || rendition?.spread
|
| 314 |
+
|
| 315 |
+
if (this.spread === 'none')
|
| 316 |
+
this.#spreads = book.sections.map(section => ({ center: section }))
|
| 317 |
+
else this.#spreads = book.sections.reduce((arr, section, i) => {
|
| 318 |
+
const last = arr[arr.length - 1]
|
| 319 |
+
const { pageSpread } = section
|
| 320 |
+
const newSpread = () => {
|
| 321 |
+
const spread = {}
|
| 322 |
+
arr.push(spread)
|
| 323 |
+
return spread
|
| 324 |
+
}
|
| 325 |
+
if (pageSpread === 'center') {
|
| 326 |
+
const spread = last.left || last.right ? newSpread() : last
|
| 327 |
+
spread.center = section
|
| 328 |
+
}
|
| 329 |
+
else if (pageSpread === 'left') {
|
| 330 |
+
const spread = last.center || last.left || ltr && i ? newSpread() : last
|
| 331 |
+
spread.left = section
|
| 332 |
+
}
|
| 333 |
+
else if (pageSpread === 'right') {
|
| 334 |
+
const spread = last.center || last.right || rtl && i ? newSpread() : last
|
| 335 |
+
spread.right = section
|
| 336 |
+
}
|
| 337 |
+
else if (ltr) {
|
| 338 |
+
if (last.center || last.right) newSpread().left = section
|
| 339 |
+
else if (last.left || !i) last.right = section
|
| 340 |
+
else last.left = section
|
| 341 |
+
}
|
| 342 |
+
else {
|
| 343 |
+
if (last.center || last.left) newSpread().right = section
|
| 344 |
+
else if (last.right || !i) last.left = section
|
| 345 |
+
else last.right = section
|
| 346 |
+
}
|
| 347 |
+
return arr
|
| 348 |
+
}, [{}])
|
| 349 |
+
}
|
| 350 |
+
#respread(spreadMode) {
|
| 351 |
+
if (this.#index === -1) return
|
| 352 |
+
const section = this.book.sections[this.index]
|
| 353 |
+
this.#spread(spreadMode)
|
| 354 |
+
const { index } = this.getSpreadOf(section)
|
| 355 |
+
this.#index = -1
|
| 356 |
+
this.#preloadCache.clear()
|
| 357 |
+
for (const frames of this.#prerenderedSpreads.values()) {
|
| 358 |
+
if (frames.center) {
|
| 359 |
+
frames.center.element?.remove()
|
| 360 |
+
} else {
|
| 361 |
+
frames.left?.element?.remove()
|
| 362 |
+
frames.right?.element?.remove()
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
this.#prerenderedSpreads.clear()
|
| 366 |
+
this.#spreadAccessTime.clear()
|
| 367 |
+
this.goToSpread(index, this.rtl ? 'right' : 'left', 'page')
|
| 368 |
+
}
|
| 369 |
+
get index() {
|
| 370 |
+
const spread = this.#spreads[this.#index]
|
| 371 |
+
const section = spread?.center ?? (this.#side === 'left'
|
| 372 |
+
? spread.left ?? spread.right : spread.right ?? spread.left)
|
| 373 |
+
return this.book.sections.indexOf(section)
|
| 374 |
+
}
|
| 375 |
+
get scrollLocked() {
|
| 376 |
+
return this.#scrollLocked
|
| 377 |
+
}
|
| 378 |
+
set scrollLocked(value) {
|
| 379 |
+
this.#scrollLocked = value
|
| 380 |
+
}
|
| 381 |
+
get isOverflowX() {
|
| 382 |
+
return this.#isOverflowX
|
| 383 |
+
}
|
| 384 |
+
get isOverflowY() {
|
| 385 |
+
return this.#isOverflowY
|
| 386 |
+
}
|
| 387 |
+
#reportLocation(reason) {
|
| 388 |
+
this.dispatchEvent(new CustomEvent('relocate', { detail:
|
| 389 |
+
{ reason, range: null, index: this.index, fraction: 0, size: 1 } }))
|
| 390 |
+
}
|
| 391 |
+
getSpreadOf(section) {
|
| 392 |
+
const spreads = this.#spreads
|
| 393 |
+
for (let index = 0; index < spreads.length; index++) {
|
| 394 |
+
const { left, right, center } = spreads[index]
|
| 395 |
+
if (left === section) return { index, side: 'left' }
|
| 396 |
+
if (right === section) return { index, side: 'right' }
|
| 397 |
+
if (center === section) return { index, side: 'center' }
|
| 398 |
+
}
|
| 399 |
+
}
|
| 400 |
+
async goToSpread(index, side, reason) {
|
| 401 |
+
if (index < 0 || index > this.#spreads.length - 1) return
|
| 402 |
+
if (index === this.#index) {
|
| 403 |
+
this.#render(side)
|
| 404 |
+
return
|
| 405 |
+
}
|
| 406 |
+
this.#index = index
|
| 407 |
+
const spread = this.#spreads[index]
|
| 408 |
+
const cacheKey = `spread-${index}`
|
| 409 |
+
const cached = this.#preloadCache.get(cacheKey)
|
| 410 |
+
if (cached && cached !== 'loading') {
|
| 411 |
+
if (cached.center) {
|
| 412 |
+
const sectionIndex = this.book.sections.indexOf(spread.center)
|
| 413 |
+
await this.#showSpread({ center: { index: sectionIndex, src: cached.center }, spreadIndex: index, side })
|
| 414 |
+
} else {
|
| 415 |
+
const indexL = this.book.sections.indexOf(spread.left)
|
| 416 |
+
const indexR = this.book.sections.indexOf(spread.right)
|
| 417 |
+
const left = { index: indexL, src: cached.left }
|
| 418 |
+
const right = { index: indexR, src: cached.right }
|
| 419 |
+
await this.#showSpread({ left, right, side, spreadIndex: index })
|
| 420 |
+
}
|
| 421 |
+
} else {
|
| 422 |
+
if (spread.center) {
|
| 423 |
+
const sectionIndex = this.book.sections.indexOf(spread.center)
|
| 424 |
+
const src = await spread.center?.load?.()
|
| 425 |
+
await this.#showSpread({ center: { index: sectionIndex, src }, spreadIndex: index, side })
|
| 426 |
+
} else {
|
| 427 |
+
const indexL = this.book.sections.indexOf(spread.left)
|
| 428 |
+
const indexR = this.book.sections.indexOf(spread.right)
|
| 429 |
+
const srcL = await spread.left?.load?.()
|
| 430 |
+
const srcR = await spread.right?.load?.()
|
| 431 |
+
const left = { index: indexL, src: srcL }
|
| 432 |
+
const right = { index: indexR, src: srcR }
|
| 433 |
+
await this.#showSpread({ left, right, side, spreadIndex: index })
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
this.#reportLocation(reason)
|
| 438 |
+
this.#preloadNextSpreads()
|
| 439 |
+
}
|
| 440 |
+
#preloadNextSpreads() {
|
| 441 |
+
this.#cleanupPreloadCache()
|
| 442 |
+
|
| 443 |
+
if (this.#numPrerenderedSpreads <= 0) return
|
| 444 |
+
|
| 445 |
+
const toPreload = []
|
| 446 |
+
const forwardPreloadCount = Math.max(1, this.#numPrerenderedSpreads - 1)
|
| 447 |
+
const backwardPreloadCount = Math.max(0, this.#numPrerenderedSpreads - forwardPreloadCount)
|
| 448 |
+
for (let distance = 1; distance <= forwardPreloadCount; distance++) {
|
| 449 |
+
const forwardIndex = this.#index + distance
|
| 450 |
+
if (forwardIndex >= 0 && forwardIndex < this.#spreads.length) {
|
| 451 |
+
toPreload.push({ index: forwardIndex, direction: 'forward', distance })
|
| 452 |
+
}
|
| 453 |
+
}
|
| 454 |
+
for (let distance = 1; distance <= backwardPreloadCount; distance++) {
|
| 455 |
+
const backwardIndex = this.#index - distance
|
| 456 |
+
if (backwardIndex >= 0 && backwardIndex < this.#spreads.length) {
|
| 457 |
+
toPreload.push({ index: backwardIndex, direction: 'backward', distance })
|
| 458 |
+
}
|
| 459 |
+
}
|
| 460 |
+
for (const { index: targetIndex, direction } of toPreload) {
|
| 461 |
+
const cacheKey = `spread-${targetIndex}`
|
| 462 |
+
if (this.#prerenderedSpreads.has(cacheKey)) continue
|
| 463 |
+
const spread = this.#spreads[targetIndex]
|
| 464 |
+
if (!spread) continue
|
| 465 |
+
this.#preloadQueue.push({ targetIndex, direction, spread, cacheKey })
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
this.#processPreloadQueue()
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
async #processPreloadQueue() {
|
| 472 |
+
while (this.#preloadQueue.length > 0 && this.#activePreloads < this.#maxConcurrentPreloads) {
|
| 473 |
+
const task = this.#preloadQueue.shift()
|
| 474 |
+
if (!task) break
|
| 475 |
+
|
| 476 |
+
const { spread, cacheKey } = task
|
| 477 |
+
this.#preloadCache.set(cacheKey, 'loading')
|
| 478 |
+
this.#activePreloads++
|
| 479 |
+
Promise.resolve().then(async () => {
|
| 480 |
+
try {
|
| 481 |
+
if (spread.center) {
|
| 482 |
+
const src = await spread.center?.load?.()
|
| 483 |
+
this.#preloadCache.set(cacheKey, { center: src })
|
| 484 |
+
|
| 485 |
+
const sectionIndex = this.book.sections.indexOf(spread.center)
|
| 486 |
+
const frame = await this.#createFrame({ index: sectionIndex, src, detached: true })
|
| 487 |
+
|
| 488 |
+
this.#prerenderedSpreads.set(cacheKey, { center: frame })
|
| 489 |
+
this.#spreadAccessTime.set(cacheKey, Date.now())
|
| 490 |
+
if (frame.onZoom) {
|
| 491 |
+
const doc = frame.iframe.contentDocument
|
| 492 |
+
frame.onZoom({ doc, scale: this.#totalScaleFactor })
|
| 493 |
+
}
|
| 494 |
+
} else {
|
| 495 |
+
const srcL = await spread.left?.load?.()
|
| 496 |
+
const srcR = await spread.right?.load?.()
|
| 497 |
+
this.#preloadCache.set(cacheKey, { left: srcL, right: srcR })
|
| 498 |
+
|
| 499 |
+
const indexL = this.book.sections.indexOf(spread.left)
|
| 500 |
+
const indexR = this.book.sections.indexOf(spread.right)
|
| 501 |
+
const leftFrame = await this.#createFrame({ index: indexL, src: srcL, detached: true })
|
| 502 |
+
const rightFrame = await this.#createFrame({ index: indexR, src: srcR, detached: true })
|
| 503 |
+
|
| 504 |
+
this.#prerenderedSpreads.set(cacheKey, { left: leftFrame, right: rightFrame })
|
| 505 |
+
this.#spreadAccessTime.set(cacheKey, Date.now())
|
| 506 |
+
|
| 507 |
+
if (leftFrame.onZoom) {
|
| 508 |
+
const docL = leftFrame.iframe.contentDocument
|
| 509 |
+
leftFrame.onZoom({ doc: docL, scale: this.#totalScaleFactor })
|
| 510 |
+
}
|
| 511 |
+
if (rightFrame.onZoom) {
|
| 512 |
+
const docR = rightFrame.iframe.contentDocument
|
| 513 |
+
rightFrame.onZoom({ doc: docR, scale: this.#totalScaleFactor })
|
| 514 |
+
}
|
| 515 |
+
}
|
| 516 |
+
} catch {
|
| 517 |
+
this.#preloadCache.delete(cacheKey)
|
| 518 |
+
this.#prerenderedSpreads.delete(cacheKey)
|
| 519 |
+
} finally {
|
| 520 |
+
this.#activePreloads--
|
| 521 |
+
this.#processPreloadQueue()
|
| 522 |
+
}
|
| 523 |
+
})
|
| 524 |
+
}
|
| 525 |
+
}
|
| 526 |
+
#cleanupPreloadCache() {
|
| 527 |
+
const maxSpreads = this.#maxCachedSpreads
|
| 528 |
+
if (this.#prerenderedSpreads.size <= maxSpreads) {
|
| 529 |
+
return
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
const framesByAge = Array.from(this.#prerenderedSpreads.keys())
|
| 533 |
+
.map(key => ({
|
| 534 |
+
key,
|
| 535 |
+
accessTime: this.#spreadAccessTime.get(key) || 0,
|
| 536 |
+
}))
|
| 537 |
+
.sort((a, b) => a.accessTime - b.accessTime)
|
| 538 |
+
|
| 539 |
+
const numToRemove = this.#prerenderedSpreads.size - maxSpreads
|
| 540 |
+
const framesToDelete = framesByAge.slice(0, numToRemove).map(item => item.key)
|
| 541 |
+
|
| 542 |
+
if (framesToDelete.length > 0) {
|
| 543 |
+
framesToDelete.forEach(key => {
|
| 544 |
+
const frames = this.#prerenderedSpreads.get(key)
|
| 545 |
+
if (frames) {
|
| 546 |
+
if (frames.center) {
|
| 547 |
+
frames.center.element?.remove()
|
| 548 |
+
} else {
|
| 549 |
+
frames.left?.element?.remove()
|
| 550 |
+
frames.right?.element?.remove()
|
| 551 |
+
}
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
this.#prerenderedSpreads.delete(key)
|
| 555 |
+
this.#spreadAccessTime.delete(key)
|
| 556 |
+
this.#preloadCache.delete(key)
|
| 557 |
+
})
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
async select(target) {
|
| 561 |
+
await this.goTo(target)
|
| 562 |
+
// TODO
|
| 563 |
+
}
|
| 564 |
+
async goTo(target) {
|
| 565 |
+
const { book } = this
|
| 566 |
+
const resolved = await target
|
| 567 |
+
const section = book.sections[resolved.index]
|
| 568 |
+
if (!section) return
|
| 569 |
+
const { index, side } = this.getSpreadOf(section)
|
| 570 |
+
await this.goToSpread(index, side)
|
| 571 |
+
}
|
| 572 |
+
async next() {
|
| 573 |
+
const s = this.rtl ? this.#goLeft() : this.#goRight()
|
| 574 |
+
if (!s) return this.goToSpread(this.#index + 1, this.rtl ? 'right' : 'left', 'page')
|
| 575 |
+
}
|
| 576 |
+
async prev() {
|
| 577 |
+
const s = this.rtl ? this.#goRight() : this.#goLeft()
|
| 578 |
+
if (!s) return this.goToSpread(this.#index - 1, this.rtl ? 'left' : 'right', 'page')
|
| 579 |
+
}
|
| 580 |
+
async pan(dx, dy) {
|
| 581 |
+
if (this.#scrollLocked) return
|
| 582 |
+
this.#scrollLocked = true
|
| 583 |
+
|
| 584 |
+
const transform = frame => {
|
| 585 |
+
let { element, iframe } = frame
|
| 586 |
+
if (!iframe || !element) return
|
| 587 |
+
|
| 588 |
+
const scrollableContainer = element.parentNode.host
|
| 589 |
+
scrollableContainer.scrollLeft += dx
|
| 590 |
+
scrollableContainer.scrollTop += dy
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
transform(this.#center ?? this.#right ?? {})
|
| 594 |
+
this.#scrollLocked = false
|
| 595 |
+
}
|
| 596 |
+
getContents() {
|
| 597 |
+
return Array.from(this.#root.querySelectorAll('iframe'), frame => ({
|
| 598 |
+
doc: frame.contentDocument,
|
| 599 |
+
// TODO: index, overlayer
|
| 600 |
+
}))
|
| 601 |
+
}
|
| 602 |
+
destroy() {
|
| 603 |
+
this.#observer.unobserve(this)
|
| 604 |
+
for (const frames of this.#prerenderedSpreads.values()) {
|
| 605 |
+
if (frames.center) {
|
| 606 |
+
frames.center.element?.remove()
|
| 607 |
+
} else {
|
| 608 |
+
frames.left?.element?.remove()
|
| 609 |
+
frames.right?.element?.remove()
|
| 610 |
+
}
|
| 611 |
+
}
|
| 612 |
+
this.#prerenderedSpreads.clear()
|
| 613 |
+
this.#preloadCache.clear()
|
| 614 |
+
this.#spreadAccessTime.clear()
|
| 615 |
+
}
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
customElements.define('foliate-fxl', FixedLayout)
|
packages/foliate-js/footnotes.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const getTypes = el => new Set([
|
| 2 |
+
...(el?.getAttributeNS?.('http://www.idpf.org/2007/ops', 'type')?.split(' ') ?? []),
|
| 3 |
+
...(el?.attributes?.getNamedItem?.('epub:type')?.value?.split(' ') ?? []),
|
| 4 |
+
])
|
| 5 |
+
const getRoles = el => new Set(el?.getAttribute?.('role')?.split(' '))
|
| 6 |
+
|
| 7 |
+
const isSuper = el => {
|
| 8 |
+
if (el.matches('sup')) return true
|
| 9 |
+
const { verticalAlign } = getComputedStyle(el)
|
| 10 |
+
return verticalAlign === 'super'
|
| 11 |
+
|| verticalAlign === 'top'
|
| 12 |
+
|| verticalAlign === 'text-top'
|
| 13 |
+
|| /^\d/.test(verticalAlign)
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
const refTypes = ['biblioref', 'glossref', 'noteref']
|
| 17 |
+
const refRoles = ['doc-biblioref', 'doc-glossref', 'doc-noteref']
|
| 18 |
+
const isFootnoteReference = a => {
|
| 19 |
+
const types = getTypes(a)
|
| 20 |
+
const roles = getRoles(a)
|
| 21 |
+
return {
|
| 22 |
+
yes: refRoles.some(r => roles.has(r)) || refTypes.some(t => types.has(t)),
|
| 23 |
+
maybe: () => !types.has('backlink') && !roles.has('doc-backlink')
|
| 24 |
+
&& (isSuper(a) || a.children.length === 1 && isSuper(a.children[0])
|
| 25 |
+
|| isSuper(a.parentElement)),
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
const getReferencedType = el => {
|
| 30 |
+
const types = getTypes(el)
|
| 31 |
+
const roles = getRoles(el)
|
| 32 |
+
return roles.has('doc-biblioentry') || types.has('biblioentry') ? 'biblioentry'
|
| 33 |
+
: roles.has('definition') || types.has('glossdef') ? 'definition'
|
| 34 |
+
: roles.has('doc-endnote') || types.has('endnote') || types.has('rearnote') ? 'endnote'
|
| 35 |
+
: roles.has('doc-footnote') || types.has('footnote') ? 'footnote'
|
| 36 |
+
: roles.has('note') || types.has('note') ? 'note' : null
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
const isInline = 'a, span, sup, sub, em, strong, i, b, small, big'
|
| 40 |
+
const extractFootnote = (doc, anchor) => {
|
| 41 |
+
let el = anchor(doc)
|
| 42 |
+
const target = el
|
| 43 |
+
while (el.matches(isInline)) {
|
| 44 |
+
const parent = el.parentElement
|
| 45 |
+
if (!parent) break
|
| 46 |
+
el = parent
|
| 47 |
+
}
|
| 48 |
+
if (el === doc.body) {
|
| 49 |
+
const sibling = target.nextElementSibling
|
| 50 |
+
if (sibling && !sibling.matches(isInline)) return sibling
|
| 51 |
+
throw new Error('Failed to extract footnote')
|
| 52 |
+
}
|
| 53 |
+
return el
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
export class FootnoteHandler extends EventTarget {
|
| 57 |
+
detectFootnotes = true
|
| 58 |
+
#showFragment(book, { index, anchor }, href) {
|
| 59 |
+
const view = document.createElement('foliate-view')
|
| 60 |
+
return new Promise((resolve, reject) => {
|
| 61 |
+
view.addEventListener('load', e => {
|
| 62 |
+
try {
|
| 63 |
+
const { doc } = e.detail
|
| 64 |
+
const el = anchor(doc)
|
| 65 |
+
const type = getReferencedType(el)
|
| 66 |
+
const hidden = el?.matches?.('aside') && type === 'footnote'
|
| 67 |
+
if (el) {
|
| 68 |
+
let range
|
| 69 |
+
if (el.startContainer) {
|
| 70 |
+
range = el
|
| 71 |
+
} else if (el.matches('li, aside')) {
|
| 72 |
+
range = doc.createRange()
|
| 73 |
+
range.selectNodeContents(el)
|
| 74 |
+
} else if (el.matches('dt')) {
|
| 75 |
+
range = doc.createRange()
|
| 76 |
+
range.setStartBefore(el)
|
| 77 |
+
let sibling = el.nextElementSibling
|
| 78 |
+
let lastDD = null
|
| 79 |
+
while (sibling && sibling.matches('dd')) {
|
| 80 |
+
lastDD = sibling
|
| 81 |
+
sibling = sibling.nextElementSibling
|
| 82 |
+
}
|
| 83 |
+
range.setEndAfter(lastDD || el)
|
| 84 |
+
} else if (el.closest('li')) {
|
| 85 |
+
range = doc.createRange()
|
| 86 |
+
range.selectNodeContents(el.closest('li'))
|
| 87 |
+
} else if (el.closest('.note')) {
|
| 88 |
+
range = doc.createRange()
|
| 89 |
+
range.selectNodeContents(el.closest('.note'))
|
| 90 |
+
} else if (el.querySelector('a')) {
|
| 91 |
+
range = doc.createRange()
|
| 92 |
+
range.setStartBefore(el)
|
| 93 |
+
let next = el.nextElementSibling
|
| 94 |
+
while (next) {
|
| 95 |
+
if (next.querySelector('a')) break
|
| 96 |
+
next = next.nextElementSibling
|
| 97 |
+
}
|
| 98 |
+
if (next) {
|
| 99 |
+
range.setEndBefore(next)
|
| 100 |
+
} else {
|
| 101 |
+
range.setEndAfter(el.parentNode.lastChild)
|
| 102 |
+
}
|
| 103 |
+
} else {
|
| 104 |
+
range = doc.createRange()
|
| 105 |
+
const hasContent = el.textContent?.trim() || el.children.length > 0
|
| 106 |
+
if (!hasContent && el.parentElement) {
|
| 107 |
+
range.selectNodeContents(el.parentElement)
|
| 108 |
+
} else {
|
| 109 |
+
range.selectNode(el)
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
const frag = range.extractContents()
|
| 113 |
+
doc.body.replaceChildren()
|
| 114 |
+
doc.body.appendChild(frag)
|
| 115 |
+
}
|
| 116 |
+
const detail = { view, href, type, hidden, target: el }
|
| 117 |
+
this.dispatchEvent(new CustomEvent('render', { detail }))
|
| 118 |
+
resolve()
|
| 119 |
+
} catch (e) {
|
| 120 |
+
reject(e)
|
| 121 |
+
}
|
| 122 |
+
})
|
| 123 |
+
view.open(book)
|
| 124 |
+
.then(() => this.dispatchEvent(new CustomEvent('before-render', { detail: { view } })))
|
| 125 |
+
.then(() => view.goTo(index))
|
| 126 |
+
.catch(reject)
|
| 127 |
+
})
|
| 128 |
+
}
|
| 129 |
+
handle(book, e) {
|
| 130 |
+
const { a, href, follow } = e.detail
|
| 131 |
+
const { yes, maybe } = isFootnoteReference(a)
|
| 132 |
+
if (yes || follow) {
|
| 133 |
+
e.preventDefault()
|
| 134 |
+
return Promise.resolve(book.resolveHref(href)).then(target =>
|
| 135 |
+
this.#showFragment(book, target, href))
|
| 136 |
+
}
|
| 137 |
+
else if (this.detectFootnotes && maybe()) {
|
| 138 |
+
e.preventDefault()
|
| 139 |
+
return Promise.resolve(book.resolveHref(href)).then(({ index, anchor }) => {
|
| 140 |
+
const target = { index, anchor: doc => extractFootnote(doc, anchor) }
|
| 141 |
+
return this.#showFragment(book, target, href)
|
| 142 |
+
})
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
}
|
packages/foliate-js/mobi.js
ADDED
|
@@ -0,0 +1,1236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const unescapeHTML = str => {
|
| 2 |
+
if (!str) return ''
|
| 3 |
+
const textarea = document.createElement('textarea')
|
| 4 |
+
textarea.innerHTML = str
|
| 5 |
+
return textarea.value
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
const MIME = {
|
| 9 |
+
XML: 'application/xml',
|
| 10 |
+
XHTML: 'application/xhtml+xml',
|
| 11 |
+
HTML: 'text/html',
|
| 12 |
+
CSS: 'text/css',
|
| 13 |
+
SVG: 'image/svg+xml',
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
const PDB_HEADER = {
|
| 17 |
+
name: [0, 32, 'string'],
|
| 18 |
+
type: [60, 4, 'string'],
|
| 19 |
+
creator: [64, 4, 'string'],
|
| 20 |
+
numRecords: [76, 2, 'uint'],
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
const PALMDOC_HEADER = {
|
| 24 |
+
compression: [0, 2, 'uint'],
|
| 25 |
+
numTextRecords: [8, 2, 'uint'],
|
| 26 |
+
recordSize: [10, 2, 'uint'],
|
| 27 |
+
encryption: [12, 2, 'uint'],
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
const MOBI_HEADER = {
|
| 31 |
+
magic: [16, 4, 'string'],
|
| 32 |
+
length: [20, 4, 'uint'],
|
| 33 |
+
type: [24, 4, 'uint'],
|
| 34 |
+
encoding: [28, 4, 'uint'],
|
| 35 |
+
uid: [32, 4, 'uint'],
|
| 36 |
+
version: [36, 4, 'uint'],
|
| 37 |
+
titleOffset: [84, 4, 'uint'],
|
| 38 |
+
titleLength: [88, 4, 'uint'],
|
| 39 |
+
localeRegion: [94, 1, 'uint'],
|
| 40 |
+
localeLanguage: [95, 1, 'uint'],
|
| 41 |
+
resourceStart: [108, 4, 'uint'],
|
| 42 |
+
huffcdic: [112, 4, 'uint'],
|
| 43 |
+
numHuffcdic: [116, 4, 'uint'],
|
| 44 |
+
exthFlag: [128, 4, 'uint'],
|
| 45 |
+
trailingFlags: [240, 4, 'uint'],
|
| 46 |
+
indx: [244, 4, 'uint'],
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
const KF8_HEADER = {
|
| 50 |
+
resourceStart: [108, 4, 'uint'],
|
| 51 |
+
fdst: [192, 4, 'uint'],
|
| 52 |
+
numFdst: [196, 4, 'uint'],
|
| 53 |
+
frag: [248, 4, 'uint'],
|
| 54 |
+
skel: [252, 4, 'uint'],
|
| 55 |
+
guide: [260, 4, 'uint'],
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
const EXTH_HEADER = {
|
| 59 |
+
magic: [0, 4, 'string'],
|
| 60 |
+
length: [4, 4, 'uint'],
|
| 61 |
+
count: [8, 4, 'uint'],
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
const INDX_HEADER = {
|
| 65 |
+
magic: [0, 4, 'string'],
|
| 66 |
+
length: [4, 4, 'uint'],
|
| 67 |
+
type: [8, 4, 'uint'],
|
| 68 |
+
idxt: [20, 4, 'uint'],
|
| 69 |
+
numRecords: [24, 4, 'uint'],
|
| 70 |
+
encoding: [28, 4, 'uint'],
|
| 71 |
+
language: [32, 4, 'uint'],
|
| 72 |
+
total: [36, 4, 'uint'],
|
| 73 |
+
ordt: [40, 4, 'uint'],
|
| 74 |
+
ligt: [44, 4, 'uint'],
|
| 75 |
+
numLigt: [48, 4, 'uint'],
|
| 76 |
+
numCncx: [52, 4, 'uint'],
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
const TAGX_HEADER = {
|
| 80 |
+
magic: [0, 4, 'string'],
|
| 81 |
+
length: [4, 4, 'uint'],
|
| 82 |
+
numControlBytes: [8, 4, 'uint'],
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
const HUFF_HEADER = {
|
| 86 |
+
magic: [0, 4, 'string'],
|
| 87 |
+
offset1: [8, 4, 'uint'],
|
| 88 |
+
offset2: [12, 4, 'uint'],
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
const CDIC_HEADER = {
|
| 92 |
+
magic: [0, 4, 'string'],
|
| 93 |
+
length: [4, 4, 'uint'],
|
| 94 |
+
numEntries: [8, 4, 'uint'],
|
| 95 |
+
codeLength: [12, 4, 'uint'],
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
const FDST_HEADER = {
|
| 99 |
+
magic: [0, 4, 'string'],
|
| 100 |
+
numEntries: [8, 4, 'uint'],
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
const FONT_HEADER = {
|
| 104 |
+
flags: [8, 4, 'uint'],
|
| 105 |
+
dataStart: [12, 4, 'uint'],
|
| 106 |
+
keyLength: [16, 4, 'uint'],
|
| 107 |
+
keyStart: [20, 4, 'uint'],
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
const MOBI_ENCODING = {
|
| 111 |
+
1252: 'windows-1252',
|
| 112 |
+
65001: 'utf-8',
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
const EXTH_RECORD_TYPE = {
|
| 116 |
+
100: ['creator', 'string', true],
|
| 117 |
+
101: ['publisher'],
|
| 118 |
+
103: ['description'],
|
| 119 |
+
104: ['isbn'],
|
| 120 |
+
105: ['subject', 'string', true],
|
| 121 |
+
106: ['date'],
|
| 122 |
+
108: ['contributor', 'string', true],
|
| 123 |
+
109: ['rights'],
|
| 124 |
+
110: ['subjectCode', 'string', true],
|
| 125 |
+
112: ['source', 'string', true],
|
| 126 |
+
113: ['asin'],
|
| 127 |
+
121: ['boundary', 'uint'],
|
| 128 |
+
122: ['fixedLayout'],
|
| 129 |
+
125: ['numResources', 'uint'],
|
| 130 |
+
126: ['originalResolution'],
|
| 131 |
+
127: ['zeroGutter'],
|
| 132 |
+
128: ['zeroMargin'],
|
| 133 |
+
129: ['coverURI'],
|
| 134 |
+
132: ['regionMagnification'],
|
| 135 |
+
201: ['coverOffset', 'uint'],
|
| 136 |
+
202: ['thumbnailOffset', 'uint'],
|
| 137 |
+
503: ['title'],
|
| 138 |
+
524: ['language', 'string', true],
|
| 139 |
+
527: ['pageProgressionDirection'],
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
const MOBI_LANG = {
|
| 143 |
+
1: ['ar', 'ar-SA', 'ar-IQ', 'ar-EG', 'ar-LY', 'ar-DZ', 'ar-MA', 'ar-TN', 'ar-OM',
|
| 144 |
+
'ar-YE', 'ar-SY', 'ar-JO', 'ar-LB', 'ar-KW', 'ar-AE', 'ar-BH', 'ar-QA'],
|
| 145 |
+
2: ['bg'], 3: ['ca'], 4: ['zh', 'zh-TW', 'zh-CN', 'zh-HK', 'zh-SG'], 5: ['cs'],
|
| 146 |
+
6: ['da'], 7: ['de', 'de-DE', 'de-CH', 'de-AT', 'de-LU', 'de-LI'], 8: ['el'],
|
| 147 |
+
9: ['en', 'en-US', 'en-GB', 'en-AU', 'en-CA', 'en-NZ', 'en-IE', 'en-ZA',
|
| 148 |
+
'en-JM', null, 'en-BZ', 'en-TT', 'en-ZW', 'en-PH'],
|
| 149 |
+
10: ['es', 'es-ES', 'es-MX', null, 'es-GT', 'es-CR', 'es-PA', 'es-DO',
|
| 150 |
+
'es-VE', 'es-CO', 'es-PE', 'es-AR', 'es-EC', 'es-CL', 'es-UY', 'es-PY',
|
| 151 |
+
'es-BO', 'es-SV', 'es-HN', 'es-NI', 'es-PR'],
|
| 152 |
+
11: ['fi'], 12: ['fr', 'fr-FR', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-LU', 'fr-MC'],
|
| 153 |
+
13: ['he'], 14: ['hu'], 15: ['is'], 16: ['it', 'it-IT', 'it-CH'],
|
| 154 |
+
17: ['ja'], 18: ['ko'], 19: ['nl', 'nl-NL', 'nl-BE'], 20: ['no', 'nb', 'nn'],
|
| 155 |
+
21: ['pl'], 22: ['pt', 'pt-BR', 'pt-PT'], 23: ['rm'], 24: ['ro'], 25: ['ru'],
|
| 156 |
+
26: ['hr', null, 'sr'], 27: ['sk'], 28: ['sq'], 29: ['sv', 'sv-SE', 'sv-FI'],
|
| 157 |
+
30: ['th'], 31: ['tr'], 32: ['ur'], 33: ['id'], 34: ['uk'], 35: ['be'],
|
| 158 |
+
36: ['sl'], 37: ['et'], 38: ['lv'], 39: ['lt'], 41: ['fa'], 42: ['vi'],
|
| 159 |
+
43: ['hy'], 44: ['az'], 45: ['eu'], 46: ['hsb'], 47: ['mk'], 48: ['st'],
|
| 160 |
+
49: ['ts'], 50: ['tn'], 52: ['xh'], 53: ['zu'], 54: ['af'], 55: ['ka'],
|
| 161 |
+
56: ['fo'], 57: ['hi'], 58: ['mt'], 59: ['se'], 62: ['ms'], 63: ['kk'],
|
| 162 |
+
65: ['sw'], 67: ['uz', null, 'uz-UZ'], 68: ['tt'], 69: ['bn'], 70: ['pa'],
|
| 163 |
+
71: ['gu'], 72: ['or'], 73: ['ta'], 74: ['te'], 75: ['kn'], 76: ['ml'],
|
| 164 |
+
77: ['as'], 78: ['mr'], 79: ['sa'], 82: ['cy', 'cy-GB'], 83: ['gl', 'gl-ES'],
|
| 165 |
+
87: ['kok'], 97: ['ne'], 98: ['fy'],
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
const concatTypedArray = (a, b) => {
|
| 169 |
+
const result = new a.constructor(a.length + b.length)
|
| 170 |
+
result.set(a)
|
| 171 |
+
result.set(b, a.length)
|
| 172 |
+
return result
|
| 173 |
+
}
|
| 174 |
+
const concatTypedArray3 = (a, b, c) => {
|
| 175 |
+
const result = new a.constructor(a.length + b.length + c.length)
|
| 176 |
+
result.set(a)
|
| 177 |
+
result.set(b, a.length)
|
| 178 |
+
result.set(c, a.length + b.length)
|
| 179 |
+
return result
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
const decoder = new TextDecoder()
|
| 183 |
+
const getString = buffer => decoder.decode(buffer)
|
| 184 |
+
const getUint = buffer => {
|
| 185 |
+
if (!buffer) return
|
| 186 |
+
const l = buffer.byteLength
|
| 187 |
+
const func = l === 4 ? 'getUint32' : l === 2 ? 'getUint16' : 'getUint8'
|
| 188 |
+
return new DataView(buffer)[func](0)
|
| 189 |
+
}
|
| 190 |
+
const getStruct = (def, buffer) => Object.fromEntries(Array.from(Object.entries(def))
|
| 191 |
+
.map(([key, [start, len, type]]) => [key,
|
| 192 |
+
(type === 'string' ? getString : getUint)(buffer.slice(start, start + len))]))
|
| 193 |
+
|
| 194 |
+
const getDecoder = x => new TextDecoder(MOBI_ENCODING[x])
|
| 195 |
+
|
| 196 |
+
const getVarLen = (byteArray, i = 0) => {
|
| 197 |
+
let value = 0, length = 0
|
| 198 |
+
for (const byte of byteArray.subarray(i, i + 4)) {
|
| 199 |
+
value = (value << 7) | (byte & 0b111_1111) >>> 0
|
| 200 |
+
length++
|
| 201 |
+
if (byte & 0b1000_0000) break
|
| 202 |
+
}
|
| 203 |
+
return { value, length }
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// variable-length quantity, but read from the end of data
|
| 207 |
+
const getVarLenFromEnd = byteArray => {
|
| 208 |
+
let value = 0
|
| 209 |
+
for (const byte of byteArray.subarray(-4)) {
|
| 210 |
+
// `byte & 0b1000_0000` indicates the start of value
|
| 211 |
+
if (byte & 0b1000_0000) value = 0
|
| 212 |
+
value = (value << 7) | (byte & 0b111_1111)
|
| 213 |
+
}
|
| 214 |
+
return value
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
const countBitsSet = x => {
|
| 218 |
+
let count = 0
|
| 219 |
+
for (; x > 0; x = x >> 1) if ((x & 1) === 1) count++
|
| 220 |
+
return count
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
const countUnsetEnd = x => {
|
| 224 |
+
let count = 0
|
| 225 |
+
while ((x & 1) === 0) x = x >> 1, count++
|
| 226 |
+
return count
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
const decompressPalmDOC = array => {
|
| 230 |
+
let output = []
|
| 231 |
+
for (let i = 0; i < array.length; i++) {
|
| 232 |
+
const byte = array[i]
|
| 233 |
+
if (byte === 0) output.push(0) // uncompressed literal, just copy it
|
| 234 |
+
else if (byte <= 8) // copy next 1-8 bytes
|
| 235 |
+
for (const x of array.subarray(i + 1, (i += byte) + 1))
|
| 236 |
+
output.push(x)
|
| 237 |
+
else if (byte <= 0b0111_1111) output.push(byte) // uncompressed literal
|
| 238 |
+
else if (byte <= 0b1011_1111) {
|
| 239 |
+
// 1st and 2nd bits are 10, meaning this is a length-distance pair
|
| 240 |
+
// read next byte and combine it with current byte
|
| 241 |
+
const bytes = (byte << 8) | array[i++ + 1]
|
| 242 |
+
// the 3rd to 13th bits encode distance
|
| 243 |
+
const distance = (bytes & 0b0011_1111_1111_1111) >>> 3
|
| 244 |
+
// the last 3 bits, plus 3, is the length to copy
|
| 245 |
+
const length = (bytes & 0b111) + 3
|
| 246 |
+
for (let j = 0; j < length; j++)
|
| 247 |
+
output.push(output[output.length - distance])
|
| 248 |
+
}
|
| 249 |
+
// compressed from space plus char
|
| 250 |
+
else output.push(32, byte ^ 0b1000_0000)
|
| 251 |
+
}
|
| 252 |
+
return Uint8Array.from(output)
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
const read32Bits = (byteArray, from) => {
|
| 256 |
+
const startByte = from >> 3
|
| 257 |
+
const end = from + 32
|
| 258 |
+
const endByte = end >> 3
|
| 259 |
+
let bits = 0n
|
| 260 |
+
for (let i = startByte; i <= endByte; i++)
|
| 261 |
+
bits = bits << 8n | BigInt(byteArray[i] ?? 0)
|
| 262 |
+
return (bits >> (8n - BigInt(end & 7))) & 0xffffffffn
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
const huffcdic = async (mobi, loadRecord) => {
|
| 266 |
+
const huffRecord = await loadRecord(mobi.huffcdic)
|
| 267 |
+
const { magic, offset1, offset2 } = getStruct(HUFF_HEADER, huffRecord)
|
| 268 |
+
if (magic !== 'HUFF') throw new Error('Invalid HUFF record')
|
| 269 |
+
|
| 270 |
+
// table1 is indexed by byte value
|
| 271 |
+
const table1 = Array.from({ length: 256 }, (_, i) => offset1 + i * 4)
|
| 272 |
+
.map(offset => getUint(huffRecord.slice(offset, offset + 4)))
|
| 273 |
+
.map(x => [x & 0b1000_0000, x & 0b1_1111, x >>> 8])
|
| 274 |
+
|
| 275 |
+
// table2 is indexed by code length
|
| 276 |
+
const table2 = [null].concat(Array.from({ length: 32 }, (_, i) => offset2 + i * 8)
|
| 277 |
+
.map(offset => [
|
| 278 |
+
getUint(huffRecord.slice(offset, offset + 4)),
|
| 279 |
+
getUint(huffRecord.slice(offset + 4, offset + 8))]))
|
| 280 |
+
|
| 281 |
+
const dictionary = []
|
| 282 |
+
for (let i = 1; i < mobi.numHuffcdic; i++) {
|
| 283 |
+
const record = await loadRecord(mobi.huffcdic + i)
|
| 284 |
+
const cdic = getStruct(CDIC_HEADER, record)
|
| 285 |
+
if (cdic.magic !== 'CDIC') throw new Error('Invalid CDIC record')
|
| 286 |
+
// `numEntries` is the total number of dictionary data across CDIC records
|
| 287 |
+
// so `n` here is the number of entries in *this* record
|
| 288 |
+
const n = Math.min(1 << cdic.codeLength, cdic.numEntries - dictionary.length)
|
| 289 |
+
const buffer = record.slice(cdic.length)
|
| 290 |
+
for (let i = 0; i < n; i++) {
|
| 291 |
+
const offset = getUint(buffer.slice(i * 2, i * 2 + 2))
|
| 292 |
+
const x = getUint(buffer.slice(offset, offset + 2))
|
| 293 |
+
const length = x & 0x7fff
|
| 294 |
+
const decompressed = x & 0x8000
|
| 295 |
+
const value = new Uint8Array(
|
| 296 |
+
buffer.slice(offset + 2, offset + 2 + length))
|
| 297 |
+
dictionary.push([value, decompressed])
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
const decompress = byteArray => {
|
| 302 |
+
let output = new Uint8Array()
|
| 303 |
+
const bitLength = byteArray.byteLength * 8
|
| 304 |
+
for (let i = 0; i < bitLength;) {
|
| 305 |
+
const bits = Number(read32Bits(byteArray, i))
|
| 306 |
+
let [found, codeLength, value] = table1[bits >>> 24]
|
| 307 |
+
if (!found) {
|
| 308 |
+
while (bits >>> (32 - codeLength) < table2[codeLength][0])
|
| 309 |
+
codeLength += 1
|
| 310 |
+
value = table2[codeLength][1]
|
| 311 |
+
}
|
| 312 |
+
if ((i += codeLength) > bitLength) break
|
| 313 |
+
|
| 314 |
+
const code = value - (bits >>> (32 - codeLength))
|
| 315 |
+
let [result, decompressed] = dictionary[code]
|
| 316 |
+
if (!decompressed) {
|
| 317 |
+
// the result is itself compressed
|
| 318 |
+
result = decompress(result)
|
| 319 |
+
// cache the result for next time
|
| 320 |
+
dictionary[code] = [result, true]
|
| 321 |
+
}
|
| 322 |
+
output = concatTypedArray(output, result)
|
| 323 |
+
}
|
| 324 |
+
return output
|
| 325 |
+
}
|
| 326 |
+
return decompress
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
const getIndexData = async (indxIndex, loadRecord) => {
|
| 330 |
+
const indxRecord = await loadRecord(indxIndex)
|
| 331 |
+
const indx = getStruct(INDX_HEADER, indxRecord)
|
| 332 |
+
if (indx.magic !== 'INDX') throw new Error('Invalid INDX record')
|
| 333 |
+
const decoder = getDecoder(indx.encoding)
|
| 334 |
+
|
| 335 |
+
const tagxBuffer = indxRecord.slice(indx.length)
|
| 336 |
+
const tagx = getStruct(TAGX_HEADER, tagxBuffer)
|
| 337 |
+
if (tagx.magic !== 'TAGX') throw new Error('Invalid TAGX section')
|
| 338 |
+
const numTags = (tagx.length - 12) / 4
|
| 339 |
+
const tagTable = Array.from({ length: numTags }, (_, i) =>
|
| 340 |
+
new Uint8Array(tagxBuffer.slice(12 + i * 4, 12 + i * 4 + 4)))
|
| 341 |
+
|
| 342 |
+
const cncx = {}
|
| 343 |
+
let cncxRecordOffset = 0
|
| 344 |
+
for (let i = 0; i < indx.numCncx; i++) {
|
| 345 |
+
const record = await loadRecord(indxIndex + indx.numRecords + i + 1)
|
| 346 |
+
const array = new Uint8Array(record)
|
| 347 |
+
for (let pos = 0; pos < array.byteLength;) {
|
| 348 |
+
const index = pos
|
| 349 |
+
const { value, length } = getVarLen(array, pos)
|
| 350 |
+
pos += length
|
| 351 |
+
const result = record.slice(pos, pos + value)
|
| 352 |
+
pos += value
|
| 353 |
+
cncx[cncxRecordOffset + index] = decoder.decode(result)
|
| 354 |
+
}
|
| 355 |
+
cncxRecordOffset += 0x10000
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
const table = []
|
| 359 |
+
for (let i = 0; i < indx.numRecords; i++) {
|
| 360 |
+
const record = await loadRecord(indxIndex + 1 + i)
|
| 361 |
+
const array = new Uint8Array(record)
|
| 362 |
+
const indx = getStruct(INDX_HEADER, record)
|
| 363 |
+
if (indx.magic !== 'INDX') throw new Error('Invalid INDX record')
|
| 364 |
+
for (let j = 0; j < indx.numRecords; j++) {
|
| 365 |
+
const offsetOffset = indx.idxt + 4 + 2 * j
|
| 366 |
+
const offset = getUint(record.slice(offsetOffset, offsetOffset + 2))
|
| 367 |
+
|
| 368 |
+
const length = getUint(record.slice(offset, offset + 1))
|
| 369 |
+
const name = getString(record.slice(offset + 1, offset + 1 + length))
|
| 370 |
+
|
| 371 |
+
const tags = []
|
| 372 |
+
const startPos = offset + 1 + length
|
| 373 |
+
let controlByteIndex = 0
|
| 374 |
+
let pos = startPos + tagx.numControlBytes
|
| 375 |
+
for (const [tag, numValues, mask, end] of tagTable) {
|
| 376 |
+
if (end & 1) {
|
| 377 |
+
controlByteIndex++
|
| 378 |
+
continue
|
| 379 |
+
}
|
| 380 |
+
const offset = startPos + controlByteIndex
|
| 381 |
+
const value = getUint(record.slice(offset, offset + 1)) & mask
|
| 382 |
+
if (value === mask) {
|
| 383 |
+
if (countBitsSet(mask) > 1) {
|
| 384 |
+
const { value, length } = getVarLen(array, pos)
|
| 385 |
+
tags.push([tag, null, value, numValues])
|
| 386 |
+
pos += length
|
| 387 |
+
} else tags.push([tag, 1, null, numValues])
|
| 388 |
+
} else tags.push([tag, value >> countUnsetEnd(mask), null, numValues])
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
const tagMap = {}
|
| 392 |
+
for (const [tag, valueCount, valueBytes, numValues] of tags) {
|
| 393 |
+
const values = []
|
| 394 |
+
if (valueCount != null) {
|
| 395 |
+
for (let i = 0; i < valueCount * numValues; i++) {
|
| 396 |
+
const { value, length } = getVarLen(array, pos)
|
| 397 |
+
values.push(value)
|
| 398 |
+
pos += length
|
| 399 |
+
}
|
| 400 |
+
} else {
|
| 401 |
+
let count = 0
|
| 402 |
+
while (count < valueBytes) {
|
| 403 |
+
const { value, length } = getVarLen(array, pos)
|
| 404 |
+
values.push(value)
|
| 405 |
+
pos += length
|
| 406 |
+
count += length
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
tagMap[tag] = values
|
| 410 |
+
}
|
| 411 |
+
table.push({ name, tagMap })
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
return { table, cncx }
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
const getNCX = async (indxIndex, loadRecord) => {
|
| 418 |
+
const { table, cncx } = await getIndexData(indxIndex, loadRecord)
|
| 419 |
+
const items = table.map(({ tagMap }, index) => ({
|
| 420 |
+
index,
|
| 421 |
+
offset: tagMap[1]?.[0],
|
| 422 |
+
size: tagMap[2]?.[0],
|
| 423 |
+
label: cncx[tagMap[3]] ?? '',
|
| 424 |
+
headingLevel: tagMap[4]?.[0],
|
| 425 |
+
pos: tagMap[6],
|
| 426 |
+
parent: tagMap[21]?.[0],
|
| 427 |
+
firstChild: tagMap[22]?.[0],
|
| 428 |
+
lastChild: tagMap[23]?.[0],
|
| 429 |
+
}))
|
| 430 |
+
const getChildren = item => {
|
| 431 |
+
if (item.firstChild == null) return item
|
| 432 |
+
item.children = items.filter(x => x.parent === item.index).map(getChildren)
|
| 433 |
+
return item
|
| 434 |
+
}
|
| 435 |
+
return items.filter(item => item.headingLevel === 0).map(getChildren)
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
const getEXTH = (buf, encoding) => {
|
| 439 |
+
const { magic, count } = getStruct(EXTH_HEADER, buf)
|
| 440 |
+
if (magic !== 'EXTH') throw new Error('Invalid EXTH header')
|
| 441 |
+
const decoder = getDecoder(encoding)
|
| 442 |
+
const results = {}
|
| 443 |
+
let offset = 12
|
| 444 |
+
for (let i = 0; i < count; i++) {
|
| 445 |
+
const type = getUint(buf.slice(offset, offset + 4))
|
| 446 |
+
const length = getUint(buf.slice(offset + 4, offset + 8))
|
| 447 |
+
if (type in EXTH_RECORD_TYPE) {
|
| 448 |
+
const [name, typ, many] = EXTH_RECORD_TYPE[type]
|
| 449 |
+
const data = buf.slice(offset + 8, offset + length)
|
| 450 |
+
const value = typ === 'uint' ? getUint(data) : decoder.decode(data)
|
| 451 |
+
if (many) {
|
| 452 |
+
results[name] ??= []
|
| 453 |
+
results[name].push(value)
|
| 454 |
+
} else results[name] = value
|
| 455 |
+
}
|
| 456 |
+
offset += length
|
| 457 |
+
}
|
| 458 |
+
return results
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
const getFont = async (buf, unzlib) => {
|
| 462 |
+
const { flags, dataStart, keyLength, keyStart } = getStruct(FONT_HEADER, buf)
|
| 463 |
+
const array = new Uint8Array(buf.slice(dataStart))
|
| 464 |
+
// deobfuscate font
|
| 465 |
+
if (flags & 0b10) {
|
| 466 |
+
const bytes = keyLength === 16 ? 1024 : 1040
|
| 467 |
+
const key = new Uint8Array(buf.slice(keyStart, keyStart + keyLength))
|
| 468 |
+
const length = Math.min(bytes, array.length)
|
| 469 |
+
for (var i = 0; i < length; i++) array[i] = array[i] ^ key[i % key.length]
|
| 470 |
+
}
|
| 471 |
+
// decompress font
|
| 472 |
+
if (flags & 1) try {
|
| 473 |
+
return await unzlib(array)
|
| 474 |
+
} catch (e) {
|
| 475 |
+
console.warn(e)
|
| 476 |
+
console.warn('Failed to decompress font')
|
| 477 |
+
}
|
| 478 |
+
return array
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
export const isMOBI = async file => {
|
| 482 |
+
const magic = getString(await file.slice(60, 68).arrayBuffer())
|
| 483 |
+
return magic === 'BOOKMOBI'// || magic === 'TEXtREAd'
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
class PDB {
|
| 487 |
+
#file
|
| 488 |
+
#offsets
|
| 489 |
+
pdb
|
| 490 |
+
async open(file) {
|
| 491 |
+
this.#file = file
|
| 492 |
+
const pdb = getStruct(PDB_HEADER, await file.slice(0, 78).arrayBuffer())
|
| 493 |
+
this.pdb = pdb
|
| 494 |
+
const buffer = await file.slice(78, 78 + pdb.numRecords * 8).arrayBuffer()
|
| 495 |
+
// get start and end offsets for each record
|
| 496 |
+
this.#offsets = Array.from({ length: pdb.numRecords },
|
| 497 |
+
(_, i) => getUint(buffer.slice(i * 8, i * 8 + 4)))
|
| 498 |
+
.map((x, i, a) => [x, a[i + 1]])
|
| 499 |
+
}
|
| 500 |
+
loadRecord(index) {
|
| 501 |
+
const offsets = this.#offsets[index]
|
| 502 |
+
if (!offsets) throw new RangeError('Record index out of bounds')
|
| 503 |
+
return this.#file.slice(...offsets).arrayBuffer()
|
| 504 |
+
}
|
| 505 |
+
async loadMagic(index) {
|
| 506 |
+
const start = this.#offsets[index][0]
|
| 507 |
+
return getString(await this.#file.slice(start, start + 4).arrayBuffer())
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
export class MOBI extends PDB {
|
| 512 |
+
#start = 0
|
| 513 |
+
#resourceStart
|
| 514 |
+
#decoder
|
| 515 |
+
#encoder
|
| 516 |
+
#decompress
|
| 517 |
+
#removeTrailingEntries
|
| 518 |
+
constructor({ unzlib }) {
|
| 519 |
+
super()
|
| 520 |
+
this.unzlib = unzlib
|
| 521 |
+
}
|
| 522 |
+
async open(file) {
|
| 523 |
+
await super.open(file)
|
| 524 |
+
// TODO: if (this.pdb.type === 'TEXt')
|
| 525 |
+
this.headers = this.#getHeaders(await super.loadRecord(0))
|
| 526 |
+
this.#resourceStart = this.headers.mobi.resourceStart
|
| 527 |
+
let isKF8 = this.headers.mobi.version >= 8
|
| 528 |
+
if (!isKF8) {
|
| 529 |
+
const boundary = this.headers.exth?.boundary
|
| 530 |
+
if (boundary < 0xffffffff) try {
|
| 531 |
+
// it's a "combo" MOBI/KF8 file; try to open the KF8 part
|
| 532 |
+
this.headers = this.#getHeaders(await super.loadRecord(boundary))
|
| 533 |
+
this.#start = boundary
|
| 534 |
+
isKF8 = true
|
| 535 |
+
} catch (e) {
|
| 536 |
+
console.warn(e)
|
| 537 |
+
console.warn('Failed to open KF8; falling back to MOBI')
|
| 538 |
+
}
|
| 539 |
+
}
|
| 540 |
+
await this.#setup()
|
| 541 |
+
return isKF8 ? new KF8(this).init() : new MOBI6(this).init()
|
| 542 |
+
}
|
| 543 |
+
#getHeaders(buf) {
|
| 544 |
+
const palmdoc = getStruct(PALMDOC_HEADER, buf)
|
| 545 |
+
const mobi = getStruct(MOBI_HEADER, buf)
|
| 546 |
+
if (mobi.magic !== 'MOBI') throw new Error('Missing MOBI header')
|
| 547 |
+
|
| 548 |
+
const { titleOffset, titleLength, localeLanguage, localeRegion } = mobi
|
| 549 |
+
mobi.title = buf.slice(titleOffset, titleOffset + titleLength)
|
| 550 |
+
const lang = MOBI_LANG[localeLanguage]
|
| 551 |
+
mobi.language = lang?.[localeRegion >> 2] ?? lang?.[0]
|
| 552 |
+
|
| 553 |
+
const exth = mobi.exthFlag & 0b100_0000
|
| 554 |
+
? getEXTH(buf.slice(mobi.length + 16), mobi.encoding) : null
|
| 555 |
+
const kf8 = mobi.version >= 8 ? getStruct(KF8_HEADER, buf) : null
|
| 556 |
+
return { palmdoc, mobi, exth, kf8 }
|
| 557 |
+
}
|
| 558 |
+
async #setup() {
|
| 559 |
+
const { palmdoc, mobi } = this.headers
|
| 560 |
+
this.#decoder = getDecoder(mobi.encoding)
|
| 561 |
+
// `TextEncoder` only supports UTF-8
|
| 562 |
+
// we are only encoding ASCII anyway, so I think it's fine
|
| 563 |
+
this.#encoder = new TextEncoder()
|
| 564 |
+
|
| 565 |
+
// set up decompressor
|
| 566 |
+
const { compression } = palmdoc
|
| 567 |
+
this.#decompress = compression === 1 ? f => f
|
| 568 |
+
: compression === 2 ? decompressPalmDOC
|
| 569 |
+
: compression === 17480 ? await huffcdic(mobi, this.loadRecord.bind(this))
|
| 570 |
+
: null
|
| 571 |
+
if (!this.#decompress) throw new Error('Unknown compression type')
|
| 572 |
+
|
| 573 |
+
// set up function for removing trailing bytes
|
| 574 |
+
const { trailingFlags } = mobi
|
| 575 |
+
const multibyte = trailingFlags & 1
|
| 576 |
+
const numTrailingEntries = countBitsSet(trailingFlags >>> 1)
|
| 577 |
+
this.#removeTrailingEntries = array => {
|
| 578 |
+
for (let i = 0; i < numTrailingEntries; i++) {
|
| 579 |
+
const length = getVarLenFromEnd(array)
|
| 580 |
+
array = array.subarray(0, -length)
|
| 581 |
+
}
|
| 582 |
+
if (multibyte) {
|
| 583 |
+
const length = (array[array.length - 1] & 0b11) + 1
|
| 584 |
+
array = array.subarray(0, -length)
|
| 585 |
+
}
|
| 586 |
+
return array
|
| 587 |
+
}
|
| 588 |
+
}
|
| 589 |
+
decode(...args) {
|
| 590 |
+
return this.#decoder.decode(...args)
|
| 591 |
+
}
|
| 592 |
+
encode(...args) {
|
| 593 |
+
return this.#encoder.encode(...args)
|
| 594 |
+
}
|
| 595 |
+
loadRecord(index) {
|
| 596 |
+
return super.loadRecord(this.#start + index)
|
| 597 |
+
}
|
| 598 |
+
loadMagic(index) {
|
| 599 |
+
return super.loadMagic(this.#start + index)
|
| 600 |
+
}
|
| 601 |
+
loadText(index) {
|
| 602 |
+
return this.loadRecord(index + 1)
|
| 603 |
+
.then(buf => new Uint8Array(buf))
|
| 604 |
+
.then(this.#removeTrailingEntries)
|
| 605 |
+
.then(this.#decompress)
|
| 606 |
+
}
|
| 607 |
+
async loadResource(index) {
|
| 608 |
+
const buf = await super.loadRecord(this.#resourceStart + index)
|
| 609 |
+
const magic = getString(buf.slice(0, 4))
|
| 610 |
+
if (magic === 'FONT') return getFont(buf, this.unzlib)
|
| 611 |
+
if (magic === 'VIDE' || magic === 'AUDI') return buf.slice(12)
|
| 612 |
+
return buf
|
| 613 |
+
}
|
| 614 |
+
getNCX() {
|
| 615 |
+
const index = this.headers.mobi.indx
|
| 616 |
+
if (index < 0xffffffff) return getNCX(index, this.loadRecord.bind(this))
|
| 617 |
+
}
|
| 618 |
+
getMetadata() {
|
| 619 |
+
const { mobi, exth } = this.headers
|
| 620 |
+
return {
|
| 621 |
+
identifier: mobi.uid.toString(),
|
| 622 |
+
title: unescapeHTML(exth?.title || this.decode(mobi.title)),
|
| 623 |
+
author: exth?.creator?.map(unescapeHTML),
|
| 624 |
+
publisher: unescapeHTML(exth?.publisher),
|
| 625 |
+
language: exth?.language ?? mobi.language,
|
| 626 |
+
published: exth?.date,
|
| 627 |
+
description: unescapeHTML(exth?.description),
|
| 628 |
+
subject: exth?.subject?.map(unescapeHTML),
|
| 629 |
+
rights: unescapeHTML(exth?.rights),
|
| 630 |
+
contributor: exth?.contributor,
|
| 631 |
+
}
|
| 632 |
+
}
|
| 633 |
+
async getCover() {
|
| 634 |
+
const { exth } = this.headers
|
| 635 |
+
const offset = exth?.coverOffset < 0xffffffff ? exth?.coverOffset
|
| 636 |
+
: exth?.thumbnailOffset < 0xffffffff ? exth?.thumbnailOffset : null
|
| 637 |
+
if (offset != null) {
|
| 638 |
+
const buf = await this.loadResource(offset)
|
| 639 |
+
return new Blob([buf])
|
| 640 |
+
}
|
| 641 |
+
}
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
const mbpPagebreakRegex = /<\s*(?:mbp:)?pagebreak[^>]*>/gi
|
| 645 |
+
const fileposRegex = /<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi
|
| 646 |
+
|
| 647 |
+
const getIndent = el => {
|
| 648 |
+
let x = 0
|
| 649 |
+
while (el) {
|
| 650 |
+
const parent = el.parentElement
|
| 651 |
+
if (parent) {
|
| 652 |
+
const tag = parent.tagName.toLowerCase()
|
| 653 |
+
if (tag === 'p') x += 1.5
|
| 654 |
+
else if (tag === 'blockquote') x += 2
|
| 655 |
+
}
|
| 656 |
+
el = parent
|
| 657 |
+
}
|
| 658 |
+
return x
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
function rawBytesToString(uint8Array) {
|
| 662 |
+
const chunkSize = 0x8000
|
| 663 |
+
let result = ''
|
| 664 |
+
for (let i = 0; i < uint8Array.length; i += chunkSize) {
|
| 665 |
+
result += String.fromCharCode.apply(null, uint8Array.subarray(i, i + chunkSize))
|
| 666 |
+
}
|
| 667 |
+
return result
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
class MOBI6 {
|
| 671 |
+
parser = new DOMParser()
|
| 672 |
+
serializer = new XMLSerializer()
|
| 673 |
+
#resourceCache = new Map()
|
| 674 |
+
#textCache = new Map()
|
| 675 |
+
#cache = new Map()
|
| 676 |
+
#sections
|
| 677 |
+
#fileposList = []
|
| 678 |
+
#type = MIME.HTML
|
| 679 |
+
constructor(mobi) {
|
| 680 |
+
this.mobi = mobi
|
| 681 |
+
}
|
| 682 |
+
async init() {
|
| 683 |
+
const recordBuffers = []
|
| 684 |
+
for (let i = 0; i < this.mobi.headers.palmdoc.numTextRecords; i++) {
|
| 685 |
+
const buf = await this.mobi.loadText(i)
|
| 686 |
+
recordBuffers.push(buf)
|
| 687 |
+
}
|
| 688 |
+
const totalLength = recordBuffers.reduce((sum, buf) => sum + buf.byteLength, 0)
|
| 689 |
+
// load all text records in an array
|
| 690 |
+
const array = new Uint8Array(totalLength)
|
| 691 |
+
recordBuffers.reduce((offset, buf) => {
|
| 692 |
+
array.set(new Uint8Array(buf), offset)
|
| 693 |
+
return offset + buf.byteLength
|
| 694 |
+
}, 0)
|
| 695 |
+
// convert to string so we can use regex
|
| 696 |
+
// note that `filepos` are byte offsets
|
| 697 |
+
// so it needs to preserve each byte as a separate character
|
| 698 |
+
// (see https://stackoverflow.com/q/50198017)
|
| 699 |
+
const str = rawBytesToString(array)
|
| 700 |
+
|
| 701 |
+
// split content into sections at each `<mbp:pagebreak>`
|
| 702 |
+
this.#sections = [0]
|
| 703 |
+
.concat(Array.from(str.matchAll(mbpPagebreakRegex), m => m.index))
|
| 704 |
+
.map((start, i, a) => {
|
| 705 |
+
const end = a[i + 1] ?? array.length
|
| 706 |
+
return { book: this, raw: array.subarray(start, end) }
|
| 707 |
+
})
|
| 708 |
+
// get start and end filepos for each section
|
| 709 |
+
.map((section, i, arr) => {
|
| 710 |
+
section.start = arr[i - 1]?.end ?? 0
|
| 711 |
+
section.end = section.start + section.raw.byteLength
|
| 712 |
+
return section
|
| 713 |
+
})
|
| 714 |
+
|
| 715 |
+
this.sections = this.#sections.map((section, index) => ({
|
| 716 |
+
id: index,
|
| 717 |
+
load: () => this.loadSection(section),
|
| 718 |
+
createDocument: () => this.createDocument(section),
|
| 719 |
+
size: section.end - section.start,
|
| 720 |
+
}))
|
| 721 |
+
|
| 722 |
+
try {
|
| 723 |
+
this.landmarks = await this.getGuide()
|
| 724 |
+
const tocHref = this.landmarks
|
| 725 |
+
.find(({ type }) => type?.includes('toc'))?.href
|
| 726 |
+
if (tocHref) {
|
| 727 |
+
const { index } = this.resolveHref(tocHref)
|
| 728 |
+
const doc = await this.sections[index].createDocument()
|
| 729 |
+
let lastItem
|
| 730 |
+
let lastLevel = 0
|
| 731 |
+
let lastIndent = 0
|
| 732 |
+
const lastLevelOfIndent = new Map()
|
| 733 |
+
const lastParentOfLevel = new Map()
|
| 734 |
+
this.toc = Array.from(doc.querySelectorAll('a[filepos]'))
|
| 735 |
+
.reduce((arr, a) => {
|
| 736 |
+
const indent = getIndent(a)
|
| 737 |
+
const item = {
|
| 738 |
+
label: a.innerText?.trim() ?? '',
|
| 739 |
+
href: `filepos:${a.getAttribute('filepos')}`,
|
| 740 |
+
}
|
| 741 |
+
const level = indent > lastIndent ? lastLevel + 1
|
| 742 |
+
: indent === lastIndent ? lastLevel
|
| 743 |
+
: lastLevelOfIndent.get(indent) ?? Math.max(0, lastLevel - 1)
|
| 744 |
+
if (level > lastLevel) {
|
| 745 |
+
if (lastItem) {
|
| 746 |
+
lastItem.subitems ??= []
|
| 747 |
+
lastItem.subitems.push(item)
|
| 748 |
+
lastParentOfLevel.set(level, lastItem)
|
| 749 |
+
}
|
| 750 |
+
else arr.push(item)
|
| 751 |
+
}
|
| 752 |
+
else {
|
| 753 |
+
const parent = lastParentOfLevel.get(level)
|
| 754 |
+
if (parent) parent.subitems.push(item)
|
| 755 |
+
else arr.push(item)
|
| 756 |
+
}
|
| 757 |
+
lastItem = item
|
| 758 |
+
lastLevel = level
|
| 759 |
+
lastIndent = indent
|
| 760 |
+
lastLevelOfIndent.set(indent, level)
|
| 761 |
+
return arr
|
| 762 |
+
}, [])
|
| 763 |
+
}
|
| 764 |
+
} catch(e) {
|
| 765 |
+
console.warn(e)
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
// get list of all `filepos` references in the book,
|
| 769 |
+
// which will be used to insert anchor elements
|
| 770 |
+
// because only then can they be referenced in the DOM
|
| 771 |
+
this.#fileposList = [...new Set(
|
| 772 |
+
Array.from(str.matchAll(fileposRegex), m => m[1]))]
|
| 773 |
+
.map(filepos => ({ filepos, number: Number(filepos) }))
|
| 774 |
+
.sort((a, b) => a.number - b.number)
|
| 775 |
+
|
| 776 |
+
this.metadata = this.mobi.getMetadata()
|
| 777 |
+
this.getCover = this.mobi.getCover.bind(this.mobi)
|
| 778 |
+
return this
|
| 779 |
+
}
|
| 780 |
+
async getGuide() {
|
| 781 |
+
const doc = await this.createDocument(this.#sections[0])
|
| 782 |
+
return Array.from(doc.getElementsByTagName('reference'), ref => ({
|
| 783 |
+
label: ref.getAttribute('title'),
|
| 784 |
+
type: ref.getAttribute('type')?.split(/\s/),
|
| 785 |
+
href: `filepos:${ref.getAttribute('filepos')}`,
|
| 786 |
+
}))
|
| 787 |
+
}
|
| 788 |
+
async loadResource(index) {
|
| 789 |
+
if (this.#resourceCache.has(index)) return this.#resourceCache.get(index)
|
| 790 |
+
const raw = await this.mobi.loadResource(index)
|
| 791 |
+
const url = URL.createObjectURL(new Blob([raw]))
|
| 792 |
+
this.#resourceCache.set(index, url)
|
| 793 |
+
return url
|
| 794 |
+
}
|
| 795 |
+
async loadRecindex(recindex) {
|
| 796 |
+
return this.loadResource(Number(recindex) - 1)
|
| 797 |
+
}
|
| 798 |
+
async replaceResources(doc) {
|
| 799 |
+
for (const img of doc.querySelectorAll('img[recindex]')) {
|
| 800 |
+
const recindex = img.getAttribute('recindex')
|
| 801 |
+
try {
|
| 802 |
+
img.src = await this.loadRecindex(recindex)
|
| 803 |
+
} catch {
|
| 804 |
+
console.warn(`Failed to load image ${recindex}`)
|
| 805 |
+
}
|
| 806 |
+
}
|
| 807 |
+
for (const media of doc.querySelectorAll('[mediarecindex]')) {
|
| 808 |
+
const mediarecindex = media.getAttribute('mediarecindex')
|
| 809 |
+
const recindex = media.getAttribute('recindex')
|
| 810 |
+
try {
|
| 811 |
+
media.src = await this.loadRecindex(mediarecindex)
|
| 812 |
+
if (recindex) media.poster = await this.loadRecindex(recindex)
|
| 813 |
+
} catch {
|
| 814 |
+
console.warn(`Failed to load media ${mediarecindex}`)
|
| 815 |
+
}
|
| 816 |
+
}
|
| 817 |
+
for (const a of doc.querySelectorAll('[filepos]')) {
|
| 818 |
+
const filepos = a.getAttribute('filepos')
|
| 819 |
+
a.href = `filepos:${filepos}`
|
| 820 |
+
}
|
| 821 |
+
}
|
| 822 |
+
async loadText(section) {
|
| 823 |
+
if (this.#textCache.has(section)) return this.#textCache.get(section)
|
| 824 |
+
const { raw } = section
|
| 825 |
+
|
| 826 |
+
// insert anchor elements for each `filepos`
|
| 827 |
+
const fileposList = this.#fileposList
|
| 828 |
+
.filter(({ number }) => number >= section.start && number < section.end)
|
| 829 |
+
.map(obj => ({ ...obj, offset: obj.number - section.start }))
|
| 830 |
+
let arr = raw
|
| 831 |
+
if (fileposList.length) {
|
| 832 |
+
arr = raw.subarray(0, fileposList[0].offset)
|
| 833 |
+
fileposList.forEach(({ filepos, offset }, i) => {
|
| 834 |
+
const next = fileposList[i + 1]
|
| 835 |
+
const a = this.mobi.encode(`<a id="filepos${filepos}"></a>`)
|
| 836 |
+
arr = concatTypedArray3(arr, a, raw.subarray(offset, next?.offset))
|
| 837 |
+
})
|
| 838 |
+
}
|
| 839 |
+
const str = this.mobi.decode(arr).replaceAll(mbpPagebreakRegex, '')
|
| 840 |
+
this.#textCache.set(section, str)
|
| 841 |
+
return str
|
| 842 |
+
}
|
| 843 |
+
async createDocument(section) {
|
| 844 |
+
const str = await this.loadText(section)
|
| 845 |
+
return this.parser.parseFromString(str, this.#type)
|
| 846 |
+
}
|
| 847 |
+
async loadSection(section) {
|
| 848 |
+
if (this.#cache.has(section)) return this.#cache.get(section)
|
| 849 |
+
const doc = await this.createDocument(section)
|
| 850 |
+
|
| 851 |
+
// inject default stylesheet
|
| 852 |
+
const style = doc.createElement('style')
|
| 853 |
+
doc.head.append(style)
|
| 854 |
+
// blockquotes in MOBI seem to have only a small left margin by default
|
| 855 |
+
// many books seem to rely on this, as it's the only way to set margin
|
| 856 |
+
// (since there's no CSS)
|
| 857 |
+
style.append(doc.createTextNode(`blockquote {
|
| 858 |
+
margin-block-start: 0;
|
| 859 |
+
margin-block-end: 0;
|
| 860 |
+
margin-inline-start: 1em;
|
| 861 |
+
margin-inline-end: 0;
|
| 862 |
+
}`))
|
| 863 |
+
|
| 864 |
+
await this.replaceResources(doc)
|
| 865 |
+
const result = this.serializer.serializeToString(doc)
|
| 866 |
+
const url = URL.createObjectURL(new Blob([result], { type: this.#type }))
|
| 867 |
+
this.#cache.set(section, url)
|
| 868 |
+
return url
|
| 869 |
+
}
|
| 870 |
+
resolveHref(href) {
|
| 871 |
+
const filepos = href.match(/filepos:(.*)/)[1]
|
| 872 |
+
const number = Number(filepos)
|
| 873 |
+
const index = this.#sections.findIndex(section => section.end > number)
|
| 874 |
+
const anchor = doc => doc.getElementById(`filepos${filepos}`)
|
| 875 |
+
return { index, anchor }
|
| 876 |
+
}
|
| 877 |
+
splitTOCHref(href) {
|
| 878 |
+
const filepos = href.match(/filepos:(.*)/)[1]
|
| 879 |
+
const number = Number(filepos)
|
| 880 |
+
const index = this.#sections.findIndex(section => section.end > number)
|
| 881 |
+
return [index, `filepos${filepos}`]
|
| 882 |
+
}
|
| 883 |
+
getTOCFragment(doc, id) {
|
| 884 |
+
return doc.getElementById(id)
|
| 885 |
+
}
|
| 886 |
+
isExternal(uri) {
|
| 887 |
+
return /^(?!blob|filepos)\w+:/i.test(uri)
|
| 888 |
+
}
|
| 889 |
+
destroy() {
|
| 890 |
+
for (const url of this.#resourceCache.values()) URL.revokeObjectURL(url)
|
| 891 |
+
for (const url of this.#cache.values()) URL.revokeObjectURL(url)
|
| 892 |
+
}
|
| 893 |
+
}
|
| 894 |
+
|
| 895 |
+
// handlers for `kindle:` uris
|
| 896 |
+
const kindleResourceRegex = /kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/
|
| 897 |
+
const kindlePosRegex = /kindle:pos:fid:(\w+):off:(\w+)/
|
| 898 |
+
const parseResourceURI = str => {
|
| 899 |
+
const [resourceType, id, type] = str.match(kindleResourceRegex).slice(1)
|
| 900 |
+
return { resourceType, id: parseInt(id, 32), type }
|
| 901 |
+
}
|
| 902 |
+
const parsePosURI = str => {
|
| 903 |
+
const [fid, off] = str.match(kindlePosRegex).slice(1)
|
| 904 |
+
return { fid: parseInt(fid, 32), off: parseInt(off, 32) }
|
| 905 |
+
}
|
| 906 |
+
const makePosURI = (fid = 0, off = 0) =>
|
| 907 |
+
`kindle:pos:fid:${fid.toString(32).toUpperCase().padStart(4, '0')
|
| 908 |
+
}:off:${off.toString(32).toUpperCase().padStart(10, '0')}`
|
| 909 |
+
|
| 910 |
+
// `kindle:pos:` links are originally links that contain fragments identifiers
|
| 911 |
+
// so there should exist an element with `id` or `name`
|
| 912 |
+
// otherwise try to find one with an `aid` attribute
|
| 913 |
+
const getFragmentSelector = str => {
|
| 914 |
+
const match = str.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i)
|
| 915 |
+
if (!match) return
|
| 916 |
+
const [, attr, value] = match
|
| 917 |
+
return `[${attr}="${CSS.escape(value)}"]`
|
| 918 |
+
}
|
| 919 |
+
|
| 920 |
+
// replace asynchronously and sequentially
|
| 921 |
+
const replaceSeries = async (str, regex, f) => {
|
| 922 |
+
const matches = []
|
| 923 |
+
str.replace(regex, (...args) => (matches.push(args), null))
|
| 924 |
+
const results = []
|
| 925 |
+
for (const args of matches) results.push(await f(...args))
|
| 926 |
+
return str.replace(regex, () => results.shift())
|
| 927 |
+
}
|
| 928 |
+
|
| 929 |
+
const getPageSpread = properties => {
|
| 930 |
+
for (const p of properties) {
|
| 931 |
+
if (p === 'page-spread-left' || p === 'rendition:page-spread-left')
|
| 932 |
+
return 'left'
|
| 933 |
+
if (p === 'page-spread-right' || p === 'rendition:page-spread-right')
|
| 934 |
+
return 'right'
|
| 935 |
+
if (p === 'rendition:page-spread-center') return 'center'
|
| 936 |
+
}
|
| 937 |
+
}
|
| 938 |
+
|
| 939 |
+
class KF8 {
|
| 940 |
+
parser = new DOMParser()
|
| 941 |
+
serializer = new XMLSerializer()
|
| 942 |
+
transformTarget = new EventTarget()
|
| 943 |
+
#cache = new Map()
|
| 944 |
+
#fragmentOffsets = new Map()
|
| 945 |
+
#fragmentSelectors = new Map()
|
| 946 |
+
#tables = {}
|
| 947 |
+
#sections
|
| 948 |
+
#fullRawLength
|
| 949 |
+
#rawHead = new Uint8Array()
|
| 950 |
+
#rawTail = new Uint8Array()
|
| 951 |
+
#lastLoadedHead = -1
|
| 952 |
+
#lastLoadedTail = -1
|
| 953 |
+
#type = MIME.XHTML
|
| 954 |
+
#inlineMap = new Map()
|
| 955 |
+
constructor(mobi) {
|
| 956 |
+
this.mobi = mobi
|
| 957 |
+
}
|
| 958 |
+
async init() {
|
| 959 |
+
const loadRecord = this.mobi.loadRecord.bind(this.mobi)
|
| 960 |
+
const { kf8 } = this.mobi.headers
|
| 961 |
+
|
| 962 |
+
try {
|
| 963 |
+
const fdstBuffer = await loadRecord(kf8.fdst)
|
| 964 |
+
const fdst = getStruct(FDST_HEADER, fdstBuffer)
|
| 965 |
+
if (fdst.magic !== 'FDST') throw new Error('Missing FDST record')
|
| 966 |
+
const fdstTable = Array.from({ length: fdst.numEntries },
|
| 967 |
+
(_, i) => 12 + i * 8)
|
| 968 |
+
.map(offset => [
|
| 969 |
+
getUint(fdstBuffer.slice(offset, offset + 4)),
|
| 970 |
+
getUint(fdstBuffer.slice(offset + 4, offset + 8))])
|
| 971 |
+
this.#tables.fdstTable = fdstTable
|
| 972 |
+
this.#fullRawLength = fdstTable[fdstTable.length - 1][1]
|
| 973 |
+
} catch {}
|
| 974 |
+
|
| 975 |
+
const skelTable = (await getIndexData(kf8.skel, loadRecord)).table
|
| 976 |
+
.map(({ name, tagMap }, index) => ({
|
| 977 |
+
index, name,
|
| 978 |
+
numFrag: tagMap[1][0],
|
| 979 |
+
offset: tagMap[6][0],
|
| 980 |
+
length: tagMap[6][1],
|
| 981 |
+
}))
|
| 982 |
+
const fragData = await getIndexData(kf8.frag, loadRecord)
|
| 983 |
+
const fragTable = fragData.table.map(({ name, tagMap }) => ({
|
| 984 |
+
insertOffset: parseInt(name),
|
| 985 |
+
selector: fragData.cncx[tagMap[2][0]],
|
| 986 |
+
index: tagMap[4][0],
|
| 987 |
+
offset: tagMap[6][0],
|
| 988 |
+
length: tagMap[6][1],
|
| 989 |
+
}))
|
| 990 |
+
this.#tables.skelTable = skelTable
|
| 991 |
+
this.#tables.fragTable = fragTable
|
| 992 |
+
|
| 993 |
+
this.#sections = skelTable.reduce((arr, skel) => {
|
| 994 |
+
const last = arr[arr.length - 1]
|
| 995 |
+
const fragStart = last?.fragEnd ?? 0, fragEnd = fragStart + skel.numFrag
|
| 996 |
+
const frags = fragTable.slice(fragStart, fragEnd)
|
| 997 |
+
const length = skel.length + frags.map(f => f.length).reduce((a, b) => a + b, 0)
|
| 998 |
+
const totalLength = (last?.totalLength ?? 0) + length
|
| 999 |
+
return arr.concat({ skel, frags, fragEnd, length, totalLength })
|
| 1000 |
+
}, [])
|
| 1001 |
+
|
| 1002 |
+
const resources = await this.getResourcesByMagic(['RESC', 'PAGE'])
|
| 1003 |
+
const pageSpreads = new Map()
|
| 1004 |
+
if (resources.RESC) {
|
| 1005 |
+
const buf = await this.mobi.loadRecord(resources.RESC)
|
| 1006 |
+
const str = this.mobi.decode(buf.slice(16)).replace(/\0/g, '')
|
| 1007 |
+
// the RESC record lacks the root `<package>` element
|
| 1008 |
+
// but seem to be otherwise valid XML
|
| 1009 |
+
const index = str.search(/\?>/)
|
| 1010 |
+
const xmlStr = `<package>${str.slice(index)}</package>`
|
| 1011 |
+
const opf = this.parser.parseFromString(xmlStr, MIME.XML)
|
| 1012 |
+
for (const $itemref of opf.querySelectorAll('spine > itemref')) {
|
| 1013 |
+
const i = parseInt($itemref.getAttribute('skelid'))
|
| 1014 |
+
pageSpreads.set(i, getPageSpread(
|
| 1015 |
+
$itemref.getAttribute('properties')?.split(' ') ?? []))
|
| 1016 |
+
}
|
| 1017 |
+
}
|
| 1018 |
+
|
| 1019 |
+
this.sections = this.#sections.map((section, index) =>
|
| 1020 |
+
section.frags.length ? ({
|
| 1021 |
+
id: index,
|
| 1022 |
+
load: () => this.loadSection(section),
|
| 1023 |
+
createDocument: () => this.createDocument(section),
|
| 1024 |
+
size: section.length,
|
| 1025 |
+
pageSpread: pageSpreads.get(index),
|
| 1026 |
+
}) : ({ linear: 'no' }))
|
| 1027 |
+
|
| 1028 |
+
try {
|
| 1029 |
+
const ncx = await this.mobi.getNCX()
|
| 1030 |
+
const map = ({ label, pos, children }) => {
|
| 1031 |
+
const [fid, off] = pos
|
| 1032 |
+
const href = makePosURI(fid, off)
|
| 1033 |
+
const arr = this.#fragmentOffsets.get(fid)
|
| 1034 |
+
if (arr) arr.push(off)
|
| 1035 |
+
else this.#fragmentOffsets.set(fid, [off])
|
| 1036 |
+
return { label: unescapeHTML(label), href, subitems: children?.map(map) }
|
| 1037 |
+
}
|
| 1038 |
+
this.toc = ncx?.map(map)
|
| 1039 |
+
this.landmarks = await this.getGuide()
|
| 1040 |
+
} catch(e) {
|
| 1041 |
+
console.warn(e)
|
| 1042 |
+
}
|
| 1043 |
+
|
| 1044 |
+
const { exth } = this.mobi.headers
|
| 1045 |
+
this.dir = exth.pageProgressionDirection
|
| 1046 |
+
this.rendition = {
|
| 1047 |
+
layout: exth.fixedLayout === 'true' ? 'pre-paginated' : 'reflowable',
|
| 1048 |
+
viewport: Object.fromEntries(exth.originalResolution
|
| 1049 |
+
?.split('x')?.slice(0, 2)
|
| 1050 |
+
?.map((x, i) => [i ? 'height' : 'width', x]) ?? []),
|
| 1051 |
+
}
|
| 1052 |
+
|
| 1053 |
+
this.metadata = this.mobi.getMetadata()
|
| 1054 |
+
this.getCover = this.mobi.getCover.bind(this.mobi)
|
| 1055 |
+
return this
|
| 1056 |
+
}
|
| 1057 |
+
// is this really the only way of getting to RESC, PAGE, etc.?
|
| 1058 |
+
async getResourcesByMagic(keys) {
|
| 1059 |
+
const results = {}
|
| 1060 |
+
const start = this.mobi.headers.kf8.resourceStart
|
| 1061 |
+
const end = this.mobi.pdb.numRecords
|
| 1062 |
+
for (let i = start; i < end; i++) {
|
| 1063 |
+
try {
|
| 1064 |
+
const magic = await this.mobi.loadMagic(i)
|
| 1065 |
+
const match = keys.find(key => key === magic)
|
| 1066 |
+
if (match) results[match] = i
|
| 1067 |
+
} catch {}
|
| 1068 |
+
}
|
| 1069 |
+
return results
|
| 1070 |
+
}
|
| 1071 |
+
async getGuide() {
|
| 1072 |
+
const index = this.mobi.headers.kf8.guide
|
| 1073 |
+
if (index < 0xffffffff) {
|
| 1074 |
+
const loadRecord = this.mobi.loadRecord.bind(this.mobi)
|
| 1075 |
+
const { table, cncx } = await getIndexData(index, loadRecord)
|
| 1076 |
+
return table.map(({ name, tagMap }) => ({
|
| 1077 |
+
label: cncx[tagMap[1][0]] ?? '',
|
| 1078 |
+
type: name?.split(/\s/),
|
| 1079 |
+
href: makePosURI(tagMap[6]?.[0] ?? tagMap[3]?.[0]),
|
| 1080 |
+
}))
|
| 1081 |
+
}
|
| 1082 |
+
}
|
| 1083 |
+
async loadResourceBlob(str) {
|
| 1084 |
+
const { resourceType, id, type } = parseResourceURI(str)
|
| 1085 |
+
const raw = resourceType === 'flow' ? await this.loadFlow(id)
|
| 1086 |
+
: await this.mobi.loadResource(id - 1)
|
| 1087 |
+
const result = [MIME.XHTML, MIME.HTML, MIME.CSS, MIME.SVG].includes(type)
|
| 1088 |
+
? await this.replaceResources(this.mobi.decode(raw)) : raw
|
| 1089 |
+
const detail = { data: result, type }
|
| 1090 |
+
const event = new CustomEvent('data', { detail })
|
| 1091 |
+
this.transformTarget.dispatchEvent(event)
|
| 1092 |
+
const newData = await event.detail.data
|
| 1093 |
+
const newType = await event.detail.type
|
| 1094 |
+
const doc = newType === MIME.SVG ? this.parser.parseFromString(newData, newType) : null
|
| 1095 |
+
return [new Blob([newData], { newType }),
|
| 1096 |
+
// SVG wrappers need to be inlined
|
| 1097 |
+
// as browsers don't allow external resources when loading SVG as an image
|
| 1098 |
+
doc?.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')?.length
|
| 1099 |
+
? doc.documentElement : null]
|
| 1100 |
+
}
|
| 1101 |
+
async loadResource(str) {
|
| 1102 |
+
if (this.#cache.has(str)) return this.#cache.get(str)
|
| 1103 |
+
const [blob, inline] = await this.loadResourceBlob(str)
|
| 1104 |
+
const url = inline ? str : URL.createObjectURL(blob)
|
| 1105 |
+
if (inline) this.#inlineMap.set(url, inline)
|
| 1106 |
+
this.#cache.set(str, url)
|
| 1107 |
+
return url
|
| 1108 |
+
}
|
| 1109 |
+
replaceResources(str) {
|
| 1110 |
+
const regex = new RegExp(kindleResourceRegex, 'g')
|
| 1111 |
+
return replaceSeries(str, regex, this.loadResource.bind(this))
|
| 1112 |
+
}
|
| 1113 |
+
// NOTE: there doesn't seem to be a way to access text randomly?
|
| 1114 |
+
// how to know the decompressed size of the records without decompressing?
|
| 1115 |
+
// 4096 is just the maximum size
|
| 1116 |
+
async loadRaw(start, end) {
|
| 1117 |
+
// here we load either from the front or back until we have reached the
|
| 1118 |
+
// required offsets; at worst you'd have to load half the book at once
|
| 1119 |
+
const distanceHead = end - this.#rawHead.length
|
| 1120 |
+
const distanceEnd = this.#fullRawLength == null ? Infinity
|
| 1121 |
+
: (this.#fullRawLength - this.#rawTail.length) - start
|
| 1122 |
+
// load from the start
|
| 1123 |
+
if (distanceHead < 0 || distanceHead < distanceEnd) {
|
| 1124 |
+
while (this.#rawHead.length < end) {
|
| 1125 |
+
const index = ++this.#lastLoadedHead
|
| 1126 |
+
const data = await this.mobi.loadText(index)
|
| 1127 |
+
this.#rawHead = concatTypedArray(this.#rawHead, data)
|
| 1128 |
+
}
|
| 1129 |
+
return this.#rawHead.slice(start, end)
|
| 1130 |
+
}
|
| 1131 |
+
// load from the end
|
| 1132 |
+
while (this.#fullRawLength - this.#rawTail.length > start) {
|
| 1133 |
+
const index = this.mobi.headers.palmdoc.numTextRecords - 1
|
| 1134 |
+
- (++this.#lastLoadedTail)
|
| 1135 |
+
const data = await this.mobi.loadText(index)
|
| 1136 |
+
this.#rawTail = concatTypedArray(data, this.#rawTail)
|
| 1137 |
+
}
|
| 1138 |
+
const rawTailStart = this.#fullRawLength - this.#rawTail.length
|
| 1139 |
+
return this.#rawTail.slice(start - rawTailStart, end - rawTailStart)
|
| 1140 |
+
}
|
| 1141 |
+
loadFlow(index) {
|
| 1142 |
+
if (index < 0xffffffff)
|
| 1143 |
+
return this.loadRaw(...this.#tables.fdstTable[index])
|
| 1144 |
+
}
|
| 1145 |
+
async loadText(section) {
|
| 1146 |
+
const { skel, frags, length } = section
|
| 1147 |
+
const raw = await this.loadRaw(skel.offset, skel.offset + length)
|
| 1148 |
+
let skeleton = raw.slice(0, skel.length)
|
| 1149 |
+
for (const frag of frags) {
|
| 1150 |
+
const insertOffset = frag.insertOffset - skel.offset
|
| 1151 |
+
const offset = skel.length + frag.offset
|
| 1152 |
+
const fragRaw = raw.slice(offset, offset + frag.length)
|
| 1153 |
+
skeleton = concatTypedArray3(
|
| 1154 |
+
skeleton.slice(0, insertOffset), fragRaw,
|
| 1155 |
+
skeleton.slice(insertOffset))
|
| 1156 |
+
|
| 1157 |
+
const offsets = this.#fragmentOffsets.get(frag.index)
|
| 1158 |
+
if (offsets) for (const offset of offsets) {
|
| 1159 |
+
const str = this.mobi.decode(fragRaw.slice(offset))
|
| 1160 |
+
const selector = getFragmentSelector(str)
|
| 1161 |
+
this.#setFragmentSelector(frag.index, offset, selector)
|
| 1162 |
+
}
|
| 1163 |
+
}
|
| 1164 |
+
return this.mobi.decode(skeleton)
|
| 1165 |
+
}
|
| 1166 |
+
async createDocument(section) {
|
| 1167 |
+
const str = await this.loadText(section)
|
| 1168 |
+
return this.parser.parseFromString(str, this.#type)
|
| 1169 |
+
}
|
| 1170 |
+
async loadSection(section) {
|
| 1171 |
+
if (this.#cache.has(section)) return this.#cache.get(section)
|
| 1172 |
+
const str = await this.loadText(section)
|
| 1173 |
+
const replaced = await this.replaceResources(str)
|
| 1174 |
+
|
| 1175 |
+
// by default, type is XHTML; change to HTML if it's not valid XHTML
|
| 1176 |
+
let doc = this.parser.parseFromString(replaced, this.#type)
|
| 1177 |
+
if (doc.querySelector('parsererror') || !doc.documentElement?.namespaceURI) {
|
| 1178 |
+
this.#type = MIME.HTML
|
| 1179 |
+
doc = this.parser.parseFromString(replaced, this.#type)
|
| 1180 |
+
}
|
| 1181 |
+
for (const [url, node] of this.#inlineMap) {
|
| 1182 |
+
for (const el of doc.querySelectorAll(`img[src="${url}"]`))
|
| 1183 |
+
el.replaceWith(node)
|
| 1184 |
+
}
|
| 1185 |
+
const url = URL.createObjectURL(
|
| 1186 |
+
new Blob([this.serializer.serializeToString(doc)], { type: this.#type }))
|
| 1187 |
+
this.#cache.set(section, url)
|
| 1188 |
+
return url
|
| 1189 |
+
}
|
| 1190 |
+
getIndexByFID(fid) {
|
| 1191 |
+
return this.#sections.findIndex(section =>
|
| 1192 |
+
section.frags.some(frag => frag.index === fid))
|
| 1193 |
+
}
|
| 1194 |
+
#setFragmentSelector(id, offset, selector) {
|
| 1195 |
+
const map = this.#fragmentSelectors.get(id)
|
| 1196 |
+
if (map) map.set(offset, selector)
|
| 1197 |
+
else {
|
| 1198 |
+
const map = new Map()
|
| 1199 |
+
this.#fragmentSelectors.set(id, map)
|
| 1200 |
+
map.set(offset, selector)
|
| 1201 |
+
}
|
| 1202 |
+
}
|
| 1203 |
+
async resolveHref(href) {
|
| 1204 |
+
const { fid, off } = parsePosURI(href)
|
| 1205 |
+
const index = this.getIndexByFID(fid)
|
| 1206 |
+
if (index < 0) return
|
| 1207 |
+
|
| 1208 |
+
const saved = this.#fragmentSelectors.get(fid)?.get(off)
|
| 1209 |
+
if (saved) return { index, anchor: doc => doc.querySelector(saved) }
|
| 1210 |
+
|
| 1211 |
+
const { skel, frags } = this.#sections[index]
|
| 1212 |
+
const frag = frags.find(frag => frag.index === fid)
|
| 1213 |
+
const offset = skel.offset + skel.length + frag.offset
|
| 1214 |
+
const fragRaw = await this.loadRaw(offset, offset + frag.length)
|
| 1215 |
+
const str = this.mobi.decode(fragRaw.slice(off))
|
| 1216 |
+
const selector = getFragmentSelector(str)
|
| 1217 |
+
this.#setFragmentSelector(fid, off, selector)
|
| 1218 |
+
const anchor = doc => doc.querySelector(selector)
|
| 1219 |
+
return { index, anchor }
|
| 1220 |
+
}
|
| 1221 |
+
splitTOCHref(href) {
|
| 1222 |
+
const pos = parsePosURI(href)
|
| 1223 |
+
const index = this.getIndexByFID(pos.fid)
|
| 1224 |
+
return [index, pos]
|
| 1225 |
+
}
|
| 1226 |
+
getTOCFragment(doc, { fid, off }) {
|
| 1227 |
+
const selector = this.#fragmentSelectors.get(fid)?.get(off)
|
| 1228 |
+
return doc.querySelector(selector)
|
| 1229 |
+
}
|
| 1230 |
+
isExternal(uri) {
|
| 1231 |
+
return /^(?!blob|kindle)\w+:/i.test(uri)
|
| 1232 |
+
}
|
| 1233 |
+
destroy() {
|
| 1234 |
+
for (const url of this.#cache.values()) URL.revokeObjectURL(url)
|
| 1235 |
+
}
|
| 1236 |
+
}
|
packages/foliate-js/opds.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const NS = {
|
| 2 |
+
ATOM: 'http://www.w3.org/2005/Atom',
|
| 3 |
+
OPDS: 'http://opds-spec.org/2010/catalog',
|
| 4 |
+
THR: 'http://purl.org/syndication/thread/1.0',
|
| 5 |
+
DC: 'http://purl.org/dc/elements/1.1/',
|
| 6 |
+
DCTERMS: 'http://purl.org/dc/terms/',
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
const MIME = {
|
| 10 |
+
ATOM: 'application/atom+xml',
|
| 11 |
+
OPDS2: 'application/opds+json',
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export const REL = {
|
| 15 |
+
ACQ: 'http://opds-spec.org/acquisition',
|
| 16 |
+
FACET: 'http://opds-spec.org/facet',
|
| 17 |
+
GROUP: 'http://opds-spec.org/group',
|
| 18 |
+
COVER: [
|
| 19 |
+
'http://opds-spec.org/image',
|
| 20 |
+
'http://opds-spec.org/cover',
|
| 21 |
+
],
|
| 22 |
+
THUMBNAIL: [
|
| 23 |
+
'http://opds-spec.org/image/thumbnail',
|
| 24 |
+
'http://opds-spec.org/thumbnail',
|
| 25 |
+
],
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export const SYMBOL = {
|
| 29 |
+
SUMMARY: Symbol('summary'),
|
| 30 |
+
CONTENT: Symbol('content'),
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
const FACET_GROUP = Symbol('facetGroup')
|
| 34 |
+
|
| 35 |
+
const groupByArray = (arr, f) => {
|
| 36 |
+
const map = new Map()
|
| 37 |
+
if (arr) for (const el of arr) {
|
| 38 |
+
const keys = f(el)
|
| 39 |
+
for (const key of [keys].flat()) {
|
| 40 |
+
const group = map.get(key)
|
| 41 |
+
if (group) group.push(el)
|
| 42 |
+
else map.set(key, [el])
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
return map
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.1
|
| 49 |
+
const parseMediaType = str => {
|
| 50 |
+
if (!str) return null
|
| 51 |
+
const [mediaType, ...ps] = str.split(/ *; */)
|
| 52 |
+
return {
|
| 53 |
+
mediaType: mediaType.toLowerCase(),
|
| 54 |
+
parameters: Object.fromEntries(ps.map(p => {
|
| 55 |
+
const [name, val] = p.split('=')
|
| 56 |
+
return [name.toLowerCase(), val?.replace(/(^"|"$)/g, '')]
|
| 57 |
+
})),
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
export const isOPDSCatalog = str => {
|
| 62 |
+
const parsed = parseMediaType(str)
|
| 63 |
+
if (!parsed) return false
|
| 64 |
+
const { mediaType, parameters } = parsed
|
| 65 |
+
if (mediaType === MIME.OPDS2) return true
|
| 66 |
+
return mediaType === MIME.ATOM && parameters.profile?.toLowerCase() === 'opds-catalog'
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
export const isOPDSSearch = str => {
|
| 70 |
+
const parsed = parseMediaType(str)
|
| 71 |
+
if (!parsed) return false
|
| 72 |
+
const { mediaType } = parsed
|
| 73 |
+
return mediaType === MIME.ATOM
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// ignore the namespace if it doesn't appear in document at all
|
| 77 |
+
const useNS = (doc, ns) =>
|
| 78 |
+
doc.lookupNamespaceURI(null) === ns || doc.lookupPrefix(ns) ? ns : null
|
| 79 |
+
|
| 80 |
+
const filterNS = ns => ns
|
| 81 |
+
? name => el => el.namespaceURI === ns && el.localName === name
|
| 82 |
+
: name => el => el.localName === name
|
| 83 |
+
|
| 84 |
+
const getContent = el => {
|
| 85 |
+
if (!el) return
|
| 86 |
+
const type = el.getAttribute('type') ?? 'text'
|
| 87 |
+
const value = type === 'xhtml' ? el.innerHTML
|
| 88 |
+
: type === 'html' ? el.textContent
|
| 89 |
+
.replaceAll('<', '<')
|
| 90 |
+
.replaceAll('>', '>')
|
| 91 |
+
.replaceAll('&', '&')
|
| 92 |
+
: el.textContent
|
| 93 |
+
return { value, type }
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
const getTextContent = el => {
|
| 97 |
+
const content = getContent(el)
|
| 98 |
+
if (content?.type === 'text') return content?.value
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
const getSummary = (a, b) => getTextContent(a) ?? getTextContent(b)
|
| 102 |
+
|
| 103 |
+
const getPrice = link => {
|
| 104 |
+
const price = link.getElementsByTagNameNS(NS.OPDS, 'price')[0]
|
| 105 |
+
return price ? {
|
| 106 |
+
currency: price.getAttribute('currencycode'),
|
| 107 |
+
value: price.textContent,
|
| 108 |
+
} : null
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const getIndirectAcquisition = el => {
|
| 112 |
+
const ia = el.getElementsByTagNameNS(NS.OPDS, 'indirectAcquisition')[0]
|
| 113 |
+
if (!ia) return []
|
| 114 |
+
return [{ type: ia.getAttribute('type') }, ...getIndirectAcquisition(ia)]
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
const getLink = link => {
|
| 118 |
+
const obj = {
|
| 119 |
+
rel: link.getAttribute('rel')?.split(/ +/),
|
| 120 |
+
href: link.getAttribute('href'),
|
| 121 |
+
type: link.getAttribute('type'),
|
| 122 |
+
title: link.getAttribute('title'),
|
| 123 |
+
properties: {
|
| 124 |
+
price: getPrice(link),
|
| 125 |
+
indirectAcquisition: getIndirectAcquisition(link),
|
| 126 |
+
numberOfItems: link.getAttributeNS(NS.THR, 'count'),
|
| 127 |
+
},
|
| 128 |
+
[FACET_GROUP]: link.getAttributeNS(NS.OPDS, 'facetGroup'),
|
| 129 |
+
}
|
| 130 |
+
if (link.getAttributeNS(NS.OPDS, 'activeFacet') === 'true')
|
| 131 |
+
obj.rel = [obj.rel ?? []].flat().concat('self')
|
| 132 |
+
return obj
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
const getPerson = person => {
|
| 136 |
+
const NS = person.namespaceURI
|
| 137 |
+
const uri = person.getElementsByTagNameNS(NS, 'uri')[0]?.textContent
|
| 138 |
+
return {
|
| 139 |
+
name: person.getElementsByTagNameNS(NS, 'name')[0]?.textContent ?? '',
|
| 140 |
+
links: uri ? [{ href: uri }] : [],
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
export const getPublication = entry => {
|
| 145 |
+
const filter = filterNS(useNS(entry.ownerDocument, NS.ATOM))
|
| 146 |
+
const children = Array.from(entry.children)
|
| 147 |
+
const filterDCEL = filterNS(NS.DC)
|
| 148 |
+
const filterDCTERMS = filterNS(NS.DCTERMS)
|
| 149 |
+
const filterDC = x => {
|
| 150 |
+
const a = filterDCEL(x), b = filterDCTERMS(x)
|
| 151 |
+
return y => a(y) || b(y)
|
| 152 |
+
}
|
| 153 |
+
const links = children.filter(filter('link')).map(getLink)
|
| 154 |
+
const linksByRel = groupByArray(links, link => link.rel)
|
| 155 |
+
return {
|
| 156 |
+
metadata: {
|
| 157 |
+
title: children.find(filter('title'))?.textContent ?? '',
|
| 158 |
+
author: children.filter(filter('author')).map(getPerson),
|
| 159 |
+
contributor: children.filter(filter('contributor')).map(getPerson),
|
| 160 |
+
publisher: children.find(filterDC('publisher'))?.textContent,
|
| 161 |
+
published: (children.find(filterDCTERMS('issued'))
|
| 162 |
+
?? children.find(filterDC('date')))?.textContent,
|
| 163 |
+
language: children.find(filterDC('language'))?.textContent,
|
| 164 |
+
identifier: children.find(filterDC('identifier'))?.textContent,
|
| 165 |
+
subject: children.filter(filter('category')).map(category => ({
|
| 166 |
+
name: category.getAttribute('label'),
|
| 167 |
+
code: category.getAttribute('term'),
|
| 168 |
+
scheme: category.getAttribute('scheme'),
|
| 169 |
+
})),
|
| 170 |
+
rights: children.find(filter('rights'))?.textContent ?? '',
|
| 171 |
+
[SYMBOL.CONTENT]: getContent(children.find(filter('content'))
|
| 172 |
+
?? children.find(filter('summary'))),
|
| 173 |
+
},
|
| 174 |
+
links,
|
| 175 |
+
images: REL.COVER.concat(REL.THUMBNAIL)
|
| 176 |
+
.map(R => linksByRel.get(R)?.[0]).filter(x => x),
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
export const getFeed = doc => {
|
| 181 |
+
const ns = useNS(doc, NS.ATOM)
|
| 182 |
+
const filter = filterNS(ns)
|
| 183 |
+
const children = Array.from(doc.documentElement.children)
|
| 184 |
+
const entries = children.filter(filter('entry'))
|
| 185 |
+
const links = children.filter(filter('link')).map(getLink)
|
| 186 |
+
const linksByRel = groupByArray(links, link => link.rel)
|
| 187 |
+
|
| 188 |
+
const groupedItems = new Map([[null, []]])
|
| 189 |
+
const groupLinkMap = new Map()
|
| 190 |
+
for (const entry of entries) {
|
| 191 |
+
const children = Array.from(entry.children)
|
| 192 |
+
const links = children.filter(filter('link')).map(getLink)
|
| 193 |
+
const linksByRel = groupByArray(links, link => link.rel)
|
| 194 |
+
const isPub = [...linksByRel.keys()]
|
| 195 |
+
.some(rel => rel?.startsWith(REL.ACQ) || rel === 'preview')
|
| 196 |
+
|
| 197 |
+
const groupLinks = linksByRel.get(REL.GROUP) ?? linksByRel.get('collection')
|
| 198 |
+
const groupLink = groupLinks?.length
|
| 199 |
+
? groupLinks.find(link => groupedItems.has(link.href)) ?? groupLinks[0] : null
|
| 200 |
+
if (groupLink && !groupLinkMap.has(groupLink.href))
|
| 201 |
+
groupLinkMap.set(groupLink.href, groupLink)
|
| 202 |
+
|
| 203 |
+
const item = isPub
|
| 204 |
+
? getPublication(entry)
|
| 205 |
+
: Object.assign(links.find(link => isOPDSCatalog(link.type)) ?? links[0] ?? {}, {
|
| 206 |
+
title: children.find(filter('title'))?.textContent,
|
| 207 |
+
[SYMBOL.SUMMARY]: getSummary(children.find(filter('summary')),
|
| 208 |
+
children.find(filter('content'))),
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
const arr = groupedItems.get(groupLink?.href ?? null)
|
| 212 |
+
if (arr) arr.push(item)
|
| 213 |
+
else groupedItems.set(groupLink.href, [item])
|
| 214 |
+
}
|
| 215 |
+
const [items, ...groups] = Array.from(groupedItems, ([key, items]) => {
|
| 216 |
+
const itemsKey = items[0]?.metadata ? 'publications' : 'navigation'
|
| 217 |
+
if (key == null) return { [itemsKey]: items }
|
| 218 |
+
const link = groupLinkMap.get(key)
|
| 219 |
+
return {
|
| 220 |
+
metadata: {
|
| 221 |
+
title: link.title,
|
| 222 |
+
numberOfItems: link.properties.numberOfItems,
|
| 223 |
+
},
|
| 224 |
+
links: [{ rel: 'self', href: link.href, type: link.type }],
|
| 225 |
+
[itemsKey]: items,
|
| 226 |
+
}
|
| 227 |
+
})
|
| 228 |
+
return {
|
| 229 |
+
metadata: {
|
| 230 |
+
title: children.find(filter('title'))?.textContent,
|
| 231 |
+
subtitle: children.find(filter('subtitle'))?.textContent,
|
| 232 |
+
},
|
| 233 |
+
links,
|
| 234 |
+
...items,
|
| 235 |
+
groups,
|
| 236 |
+
facets: Array.from(
|
| 237 |
+
groupByArray(linksByRel.get(REL.FACET) ?? [], link => link[FACET_GROUP]),
|
| 238 |
+
([facet, links]) => ({ metadata: { title: facet }, links })),
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
export const getSearch = async link => {
|
| 243 |
+
const { replace, getVariables } = await import('./uri-template.js')
|
| 244 |
+
return {
|
| 245 |
+
metadata: {
|
| 246 |
+
title: link.title,
|
| 247 |
+
},
|
| 248 |
+
search: map => replace(link.href, map.get(null)),
|
| 249 |
+
params: Array.from(getVariables(link.href), name => ({ name })),
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
export const getOpenSearch = doc => {
|
| 254 |
+
const defaultNS = doc.documentElement.namespaceURI
|
| 255 |
+
const filter = filterNS(defaultNS)
|
| 256 |
+
const children = Array.from(doc.documentElement.children)
|
| 257 |
+
|
| 258 |
+
const $$urls = children.filter(filter('Url'))
|
| 259 |
+
const $url = $$urls.find(url => isOPDSCatalog(url.getAttribute('type'))) ?? $$urls.find(url => isOPDSSearch(url.getAttribute('type'))) ?? $$urls[0]
|
| 260 |
+
if (!$url) throw new Error('document must contain at least one Url element')
|
| 261 |
+
|
| 262 |
+
const regex = /{(?:([^}]+?):)?(.+?)(\?)?}/g
|
| 263 |
+
const defaultMap = new Map([
|
| 264 |
+
['count', '100'],
|
| 265 |
+
['startIndex', $url.getAttribute('indexOffset') ?? '0'],
|
| 266 |
+
['startPage', $url.getAttribute('pageOffset') ?? '0'],
|
| 267 |
+
['language', '*'],
|
| 268 |
+
['inputEncoding', 'UTF-8'],
|
| 269 |
+
['outputEncoding', 'UTF-8'],
|
| 270 |
+
])
|
| 271 |
+
|
| 272 |
+
const template = $url.getAttribute('template')
|
| 273 |
+
return {
|
| 274 |
+
metadata: {
|
| 275 |
+
title: (children.find(filter('LongName')) ?? children.find(filter('ShortName')))?.textContent,
|
| 276 |
+
description: children.find(filter('Description'))?.textContent,
|
| 277 |
+
},
|
| 278 |
+
search: map => template.replace(regex, (_, prefix, param) => {
|
| 279 |
+
const namespace = prefix ? $url.lookupNamespaceURI(prefix) : null
|
| 280 |
+
const ns = namespace === defaultNS ? null : namespace
|
| 281 |
+
const val = map.get(ns)?.get(param)
|
| 282 |
+
return encodeURIComponent(val ? val : (!ns ? defaultMap.get(param) ?? '' : ''))
|
| 283 |
+
}),
|
| 284 |
+
params: Array.from(template.matchAll(regex), ([, prefix, param, optional]) => {
|
| 285 |
+
const namespace = prefix ? $url.lookupNamespaceURI(prefix) : null
|
| 286 |
+
const ns = namespace === defaultNS ? null : namespace
|
| 287 |
+
return {
|
| 288 |
+
ns, name: param,
|
| 289 |
+
required: !optional,
|
| 290 |
+
value: ns && ns !== defaultNS ? '' : defaultMap.get(param) ?? '',
|
| 291 |
+
}
|
| 292 |
+
}),
|
| 293 |
+
}
|
| 294 |
+
}
|
packages/foliate-js/overlayer.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 8 |
+
#clipPath = null
|
| 9 |
+
#clipPathPath = null
|
| 10 |
+
|
| 11 |
+
constructor(doc) {
|
| 12 |
+
this.#doc = doc
|
| 13 |
+
Object.assign(this.#svg.style, {
|
| 14 |
+
position: 'absolute', top: '0', left: '0',
|
| 15 |
+
width: '100%', height: '100%',
|
| 16 |
+
pointerEvents: 'none',
|
| 17 |
+
})
|
| 18 |
+
|
| 19 |
+
// Create a clipPath to cut a hole for the loupe.
|
| 20 |
+
// We use clip-rule="evenodd" with a large outer rect and inner circle
|
| 21 |
+
// to create the hole effect efficiently without mask compositing.
|
| 22 |
+
const defs = createSVGElement('defs')
|
| 23 |
+
this.#clipPath = createSVGElement('clipPath')
|
| 24 |
+
this.#clipPath.setAttribute('id', 'foliate-loupe-clip')
|
| 25 |
+
this.#clipPath.setAttribute('clipPathUnits', 'userSpaceOnUse')
|
| 26 |
+
|
| 27 |
+
this.#clipPathPath = createSVGElement('path')
|
| 28 |
+
this.#clipPathPath.setAttribute('clip-rule', 'evenodd')
|
| 29 |
+
this.#clipPathPath.setAttribute('fill-rule', 'evenodd') // for older renderers
|
| 30 |
+
|
| 31 |
+
this.#clipPath.append(this.#clipPathPath)
|
| 32 |
+
defs.append(this.#clipPath)
|
| 33 |
+
this.#svg.append(defs)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
setHole(x, y, r) {
|
| 37 |
+
// Define a path with a large outer rect and a circular hole
|
| 38 |
+
// "Infinite" outer rect coverage is safe for userSpaceOnUse
|
| 39 |
+
// (20,000px limit was too small for long scrolls; use 2,000,000px)
|
| 40 |
+
const outer = 'M -2000000 -2000000 H 4000000 V 4000000 H -2000000 Z'
|
| 41 |
+
const inner = `M ${x} ${y} m -${r} 0 a ${r} ${r} 0 1 0 ${2*r} 0 a ${r} ${r} 0 1 0 -${2*r} 0`
|
| 42 |
+
this.#clipPathPath.setAttribute('d', `${outer} ${inner}`)
|
| 43 |
+
|
| 44 |
+
this.#svg.setAttribute('clip-path', 'url(#foliate-loupe-clip)')
|
| 45 |
+
this.#svg.style.webkitClipPath = 'url(#foliate-loupe-clip)'
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
clearHole() {
|
| 49 |
+
this.#svg.removeAttribute('clip-path')
|
| 50 |
+
this.#svg.style.webkitClipPath = ''
|
| 51 |
+
this.#clipPathPath.removeAttribute('d')
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
get element() {
|
| 55 |
+
return this.#svg
|
| 56 |
+
}
|
| 57 |
+
get #zoom() {
|
| 58 |
+
// Safari does not zoom the client rects, while Chrome, Edge and Firefox does
|
| 59 |
+
if (/^((?!chrome|android).)*AppleWebKit/i.test(navigator.userAgent) && !window.chrome) {
|
| 60 |
+
return window.getComputedStyle(this.#doc.body).zoom || 1.0
|
| 61 |
+
}
|
| 62 |
+
return 1.0
|
| 63 |
+
}
|
| 64 |
+
#splitRangeByParagraph(range) {
|
| 65 |
+
const ancestor = range.commonAncestorContainer
|
| 66 |
+
const paragraphs = Array.from(ancestor.querySelectorAll?.('p, h1, h2, h3, h4') || [])
|
| 67 |
+
|
| 68 |
+
const splitRanges = []
|
| 69 |
+
paragraphs.forEach((p) => {
|
| 70 |
+
const pRange = document.createRange()
|
| 71 |
+
if (range.intersectsNode(p)) {
|
| 72 |
+
pRange.selectNodeContents(p)
|
| 73 |
+
if (pRange.compareBoundaryPoints(Range.START_TO_START, range) < 0) {
|
| 74 |
+
pRange.setStart(range.startContainer, range.startOffset)
|
| 75 |
+
}
|
| 76 |
+
if (pRange.compareBoundaryPoints(Range.END_TO_END, range) > 0) {
|
| 77 |
+
pRange.setEnd(range.endContainer, range.endOffset)
|
| 78 |
+
}
|
| 79 |
+
splitRanges.push(pRange)
|
| 80 |
+
}
|
| 81 |
+
})
|
| 82 |
+
return splitRanges.length === 0 ? [range] : splitRanges
|
| 83 |
+
}
|
| 84 |
+
add(key, range, draw, options) {
|
| 85 |
+
if (this.#map.has(key)) this.remove(key)
|
| 86 |
+
if (typeof range === 'function') range = range(this.#svg.getRootNode())
|
| 87 |
+
const zoom = this.#zoom
|
| 88 |
+
let rects = []
|
| 89 |
+
this.#splitRangeByParagraph(range).forEach((pRange) => {
|
| 90 |
+
const pRects = Array.from(pRange.getClientRects()).map(rect => ({
|
| 91 |
+
left: rect.left * zoom,
|
| 92 |
+
top: rect.top * zoom,
|
| 93 |
+
right: rect.right * zoom,
|
| 94 |
+
bottom: rect.bottom * zoom,
|
| 95 |
+
width: rect.width * zoom,
|
| 96 |
+
height: rect.height * zoom,
|
| 97 |
+
}))
|
| 98 |
+
rects = rects.concat(pRects)
|
| 99 |
+
})
|
| 100 |
+
const element = draw(rects, options)
|
| 101 |
+
this.#svg.append(element)
|
| 102 |
+
this.#map.set(key, { range, draw, options, element, rects })
|
| 103 |
+
}
|
| 104 |
+
remove(key) {
|
| 105 |
+
if (!this.#map.has(key)) return
|
| 106 |
+
this.#svg.removeChild(this.#map.get(key).element)
|
| 107 |
+
this.#map.delete(key)
|
| 108 |
+
}
|
| 109 |
+
redraw() {
|
| 110 |
+
for (const obj of this.#map.values()) {
|
| 111 |
+
const { range, draw, options, element } = obj
|
| 112 |
+
this.#svg.removeChild(element)
|
| 113 |
+
const zoom = this.#zoom
|
| 114 |
+
let rects = []
|
| 115 |
+
this.#splitRangeByParagraph(range).forEach((pRange) => {
|
| 116 |
+
const pRects = Array.from(pRange.getClientRects()).map(rect => ({
|
| 117 |
+
left: rect.left * zoom,
|
| 118 |
+
top: rect.top * zoom,
|
| 119 |
+
right: rect.right * zoom,
|
| 120 |
+
bottom: rect.bottom * zoom,
|
| 121 |
+
width: rect.width * zoom,
|
| 122 |
+
height: rect.height * zoom,
|
| 123 |
+
}))
|
| 124 |
+
rects = rects.concat(pRects)
|
| 125 |
+
})
|
| 126 |
+
const el = draw(rects, options)
|
| 127 |
+
this.#svg.append(el)
|
| 128 |
+
obj.element = el
|
| 129 |
+
obj.rects = rects
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
hitTest({ x, y }) {
|
| 133 |
+
const arr = Array.from(this.#map.entries())
|
| 134 |
+
// loop in reverse to hit more recently added items first
|
| 135 |
+
for (let i = arr.length - 1; i >= 0; i--) {
|
| 136 |
+
const tolerance = 5
|
| 137 |
+
const [key, obj] = arr[i]
|
| 138 |
+
for (const { left, top, right, bottom } of obj.rects) {
|
| 139 |
+
if (
|
| 140 |
+
top <= y + tolerance &&
|
| 141 |
+
left <= x + tolerance &&
|
| 142 |
+
bottom > y - tolerance &&
|
| 143 |
+
right > x - tolerance
|
| 144 |
+
) {
|
| 145 |
+
return [key, obj.range, { left, top, right, bottom }]
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
return []
|
| 150 |
+
}
|
| 151 |
+
static underline(rects, options = {}) {
|
| 152 |
+
const { color = 'red', width: strokeWidth = 2, padding = 0, writingMode } = options
|
| 153 |
+
const g = createSVGElement('g')
|
| 154 |
+
g.setAttribute('fill', color)
|
| 155 |
+
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
|
| 156 |
+
for (const { right, top, height } of rects) {
|
| 157 |
+
const el = createSVGElement('rect')
|
| 158 |
+
el.setAttribute('x', right - strokeWidth / 2 + padding)
|
| 159 |
+
el.setAttribute('y', top)
|
| 160 |
+
el.setAttribute('height', height)
|
| 161 |
+
el.setAttribute('width', strokeWidth)
|
| 162 |
+
g.append(el)
|
| 163 |
+
}
|
| 164 |
+
else for (const { left, bottom, width } of rects) {
|
| 165 |
+
const el = createSVGElement('rect')
|
| 166 |
+
el.setAttribute('x', left)
|
| 167 |
+
el.setAttribute('y', bottom - strokeWidth / 2 + padding)
|
| 168 |
+
el.setAttribute('height', strokeWidth)
|
| 169 |
+
el.setAttribute('width', width)
|
| 170 |
+
g.append(el)
|
| 171 |
+
}
|
| 172 |
+
return g
|
| 173 |
+
}
|
| 174 |
+
static strikethrough(rects, options = {}) {
|
| 175 |
+
const { color = 'red', width: strokeWidth = 2, writingMode } = options
|
| 176 |
+
const g = createSVGElement('g')
|
| 177 |
+
g.setAttribute('fill', color)
|
| 178 |
+
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
|
| 179 |
+
for (const { right, left, top, height } of rects) {
|
| 180 |
+
const el = createSVGElement('rect')
|
| 181 |
+
el.setAttribute('x', (right + left) / 2)
|
| 182 |
+
el.setAttribute('y', top)
|
| 183 |
+
el.setAttribute('height', height)
|
| 184 |
+
el.setAttribute('width', strokeWidth)
|
| 185 |
+
g.append(el)
|
| 186 |
+
}
|
| 187 |
+
else for (const { left, top, bottom, width } of rects) {
|
| 188 |
+
const el = createSVGElement('rect')
|
| 189 |
+
el.setAttribute('x', left)
|
| 190 |
+
el.setAttribute('y', (top + bottom) / 2)
|
| 191 |
+
el.setAttribute('height', strokeWidth)
|
| 192 |
+
el.setAttribute('width', width)
|
| 193 |
+
g.append(el)
|
| 194 |
+
}
|
| 195 |
+
return g
|
| 196 |
+
}
|
| 197 |
+
static squiggly(rects, options = {}) {
|
| 198 |
+
const { color = 'red', width: strokeWidth = 2, padding = 0, writingMode } = options
|
| 199 |
+
const g = createSVGElement('g')
|
| 200 |
+
g.setAttribute('fill', 'none')
|
| 201 |
+
g.setAttribute('stroke', color)
|
| 202 |
+
g.setAttribute('stroke-width', strokeWidth)
|
| 203 |
+
const block = strokeWidth * 1.5
|
| 204 |
+
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
|
| 205 |
+
for (const { right, top, height } of rects) {
|
| 206 |
+
const el = createSVGElement('path')
|
| 207 |
+
const n = Math.round(height / block / 1.5)
|
| 208 |
+
const inline = height / n
|
| 209 |
+
const ls = Array.from({ length: n },
|
| 210 |
+
(_, i) => `l${i % 2 ? -block : block} ${inline}`).join('')
|
| 211 |
+
el.setAttribute('d', `M${right - strokeWidth / 2 + padding} ${top}${ls}`)
|
| 212 |
+
g.append(el)
|
| 213 |
+
}
|
| 214 |
+
else for (const { left, bottom, width } of rects) {
|
| 215 |
+
const el = createSVGElement('path')
|
| 216 |
+
const n = Math.round(width / block / 1.5)
|
| 217 |
+
const inline = width / n
|
| 218 |
+
const ls = Array.from({ length: n },
|
| 219 |
+
(_, i) => `l${inline} ${i % 2 ? block : -block}`).join('')
|
| 220 |
+
el.setAttribute('d', `M${left} ${bottom + strokeWidth / 2 + padding}${ls}`)
|
| 221 |
+
g.append(el)
|
| 222 |
+
}
|
| 223 |
+
return g
|
| 224 |
+
}
|
| 225 |
+
static highlight(rects, options = {}) {
|
| 226 |
+
const {
|
| 227 |
+
color = 'red',
|
| 228 |
+
padding = 0,
|
| 229 |
+
radius = 4,
|
| 230 |
+
radiusPadding = 2,
|
| 231 |
+
vertical = false,
|
| 232 |
+
} = options
|
| 233 |
+
|
| 234 |
+
const g = createSVGElement('g')
|
| 235 |
+
g.setAttribute('fill', color)
|
| 236 |
+
g.style.opacity = 'var(--overlayer-highlight-opacity, .3)'
|
| 237 |
+
g.style.mixBlendMode = 'var(--overlayer-highlight-blend-mode, normal)'
|
| 238 |
+
|
| 239 |
+
for (const [index, { left, top, height, width }] of rects.entries()) {
|
| 240 |
+
const isFirst = index === 0
|
| 241 |
+
const isLast = index === rects.length - 1
|
| 242 |
+
|
| 243 |
+
let x, y, w, h
|
| 244 |
+
|
| 245 |
+
let radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft
|
| 246 |
+
|
| 247 |
+
if (vertical) {
|
| 248 |
+
x = left - padding
|
| 249 |
+
y = top - padding - (isFirst ? radiusPadding : 0)
|
| 250 |
+
w = width + padding * 2
|
| 251 |
+
h = height + padding * 2 + (isFirst ? radiusPadding : 0) + (isLast ? radiusPadding : 0)
|
| 252 |
+
radiusTopLeft = isFirst ? radius : 0
|
| 253 |
+
radiusTopRight = isFirst ? radius : 0
|
| 254 |
+
radiusBottomRight = isLast ? radius : 0
|
| 255 |
+
radiusBottomLeft = isLast ? radius : 0
|
| 256 |
+
} else {
|
| 257 |
+
x = left - padding - (isFirst ? radiusPadding : 0)
|
| 258 |
+
y = top - padding
|
| 259 |
+
w = width + padding * 2 + (isFirst ? radiusPadding : 0) + (isLast ? radiusPadding : 0)
|
| 260 |
+
h = height + padding * 2
|
| 261 |
+
radiusTopLeft = isFirst ? radius : 0
|
| 262 |
+
radiusTopRight = isLast ? radius : 0
|
| 263 |
+
radiusBottomRight = isLast ? radius : 0
|
| 264 |
+
radiusBottomLeft = isFirst ? radius : 0
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
const rtl = Math.min(radiusTopLeft, w / 2, h / 2)
|
| 268 |
+
const rtr = Math.min(radiusTopRight, w / 2, h / 2)
|
| 269 |
+
const rbr = Math.min(radiusBottomRight, w / 2, h / 2)
|
| 270 |
+
const rbl = Math.min(radiusBottomLeft, w / 2, h / 2)
|
| 271 |
+
|
| 272 |
+
if (rtl === 0 && rtr === 0 && rbr === 0 && rbl === 0) {
|
| 273 |
+
const el = createSVGElement('rect')
|
| 274 |
+
el.setAttribute('x', x)
|
| 275 |
+
el.setAttribute('y', y)
|
| 276 |
+
el.setAttribute('height', h)
|
| 277 |
+
el.setAttribute('width', w)
|
| 278 |
+
g.append(el)
|
| 279 |
+
} else {
|
| 280 |
+
const el = createSVGElement('path')
|
| 281 |
+
const d = `
|
| 282 |
+
M ${x + rtl} ${y}
|
| 283 |
+
L ${x + w - rtr} ${y}
|
| 284 |
+
${rtr > 0 ? `Q ${x + w} ${y} ${x + w} ${y + rtr}` : `L ${x + w} ${y}`}
|
| 285 |
+
L ${x + w} ${y + h - rbr}
|
| 286 |
+
${rbr > 0 ? `Q ${x + w} ${y + h} ${x + w - rbr} ${y + h}` : `L ${x + w} ${y + h}`}
|
| 287 |
+
L ${x + rbl} ${y + h}
|
| 288 |
+
${rbl > 0 ? `Q ${x} ${y + h} ${x} ${y + h - rbl}` : `L ${x} ${y + h}`}
|
| 289 |
+
L ${x} ${y + rtl}
|
| 290 |
+
${rtl > 0 ? `Q ${x} ${y} ${x + rtl} ${y}` : `L ${x} ${y}`}
|
| 291 |
+
Z
|
| 292 |
+
`.trim().replace(/\s+/g, ' ')
|
| 293 |
+
el.setAttribute('d', d)
|
| 294 |
+
g.append(el)
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
return g
|
| 298 |
+
}
|
| 299 |
+
static outline(rects, options = {}) {
|
| 300 |
+
const { color = 'red', width: strokeWidth = 3, padding = 0, radius = 3 } = options
|
| 301 |
+
const g = createSVGElement('g')
|
| 302 |
+
g.setAttribute('fill', 'none')
|
| 303 |
+
g.setAttribute('stroke', color)
|
| 304 |
+
g.setAttribute('stroke-width', strokeWidth)
|
| 305 |
+
for (const { left, top, height, width } of rects) {
|
| 306 |
+
const el = createSVGElement('rect')
|
| 307 |
+
el.setAttribute('x', left - padding)
|
| 308 |
+
el.setAttribute('y', top - padding)
|
| 309 |
+
el.setAttribute('height', height + padding * 2)
|
| 310 |
+
el.setAttribute('width', width + padding * 2)
|
| 311 |
+
el.setAttribute('rx', radius)
|
| 312 |
+
g.append(el)
|
| 313 |
+
}
|
| 314 |
+
return g
|
| 315 |
+
}
|
| 316 |
+
static bubble(rects, options = {}) {
|
| 317 |
+
const { color = '#fbbf24', writingMode, opacity = 0.85, size = 20, padding = 10 } = options
|
| 318 |
+
const isVertical = writingMode === 'vertical-rl' || writingMode === 'vertical-lr'
|
| 319 |
+
const g = createSVGElement('g')
|
| 320 |
+
g.style.opacity = opacity
|
| 321 |
+
if (rects.length === 0) return g
|
| 322 |
+
rects.splice(1)
|
| 323 |
+
const firstRect = rects[0]
|
| 324 |
+
const x = isVertical ? firstRect.right - size + padding : firstRect.right - size + padding
|
| 325 |
+
const y = isVertical ? firstRect.bottom - size + padding : firstRect.top - size + padding
|
| 326 |
+
firstRect.top = y - padding
|
| 327 |
+
firstRect.right = x + size + padding
|
| 328 |
+
firstRect.bottom = y + size + padding
|
| 329 |
+
firstRect.left = x - padding
|
| 330 |
+
const bubble = createSVGElement('path')
|
| 331 |
+
const s = size
|
| 332 |
+
const r = s * 0.15
|
| 333 |
+
// Speech bubble shape with a small tail
|
| 334 |
+
// Main rounded rectangle body
|
| 335 |
+
const d = `
|
| 336 |
+
M ${x + r} ${y}
|
| 337 |
+
h ${s - 2 * r}
|
| 338 |
+
a ${r} ${r} 0 0 1 ${r} ${r}
|
| 339 |
+
v ${s * 0.65 - 2 * r}
|
| 340 |
+
a ${r} ${r} 0 0 1 ${-r} ${r}
|
| 341 |
+
h ${-s * 0.3}
|
| 342 |
+
l ${-s * 0.15} ${s * 0.2}
|
| 343 |
+
l ${s * 0.05} ${-s * 0.2}
|
| 344 |
+
h ${-s * 0.6 + 2 * r}
|
| 345 |
+
a ${r} ${r} 0 0 1 ${-r} ${-r}
|
| 346 |
+
v ${-s * 0.65 + 2 * r}
|
| 347 |
+
a ${r} ${r} 0 0 1 ${r} ${-r}
|
| 348 |
+
z
|
| 349 |
+
`.replace(/\s+/g, ' ').trim()
|
| 350 |
+
|
| 351 |
+
bubble.setAttribute('d', d)
|
| 352 |
+
bubble.setAttribute('fill', color)
|
| 353 |
+
bubble.setAttribute('stroke', 'rgba(0, 0, 0, 0.2)')
|
| 354 |
+
bubble.setAttribute('stroke-width', '1')
|
| 355 |
+
// Add horizontal lines inside to represent text
|
| 356 |
+
const lineGroup = createSVGElement('g')
|
| 357 |
+
lineGroup.setAttribute('stroke', 'rgba(0, 0, 0, 0.3)')
|
| 358 |
+
lineGroup.setAttribute('stroke-width', '1.5')
|
| 359 |
+
lineGroup.setAttribute('stroke-linecap', 'round')
|
| 360 |
+
const lineY1 = y + s * 0.18
|
| 361 |
+
const lineY2 = y + s * 0.33
|
| 362 |
+
const lineY3 = y + s * 0.48
|
| 363 |
+
const lineX1 = x + s * 0.2
|
| 364 |
+
const lineX2 = x + s * 0.8
|
| 365 |
+
const line1 = createSVGElement('line')
|
| 366 |
+
line1.setAttribute('x1', lineX1)
|
| 367 |
+
line1.setAttribute('y1', lineY1)
|
| 368 |
+
line1.setAttribute('x2', lineX2)
|
| 369 |
+
line1.setAttribute('y2', lineY1)
|
| 370 |
+
const line2 = createSVGElement('line')
|
| 371 |
+
line2.setAttribute('x1', lineX1)
|
| 372 |
+
line2.setAttribute('y1', lineY2)
|
| 373 |
+
line2.setAttribute('x2', lineX2)
|
| 374 |
+
line2.setAttribute('y2', lineY2)
|
| 375 |
+
const line3 = createSVGElement('line')
|
| 376 |
+
line3.setAttribute('x1', lineX1)
|
| 377 |
+
line3.setAttribute('y1', lineY3)
|
| 378 |
+
line3.setAttribute('x2', x + s * 0.6)
|
| 379 |
+
line3.setAttribute('y2', lineY3)
|
| 380 |
+
lineGroup.append(line1, line2, line3)
|
| 381 |
+
|
| 382 |
+
if (isVertical) {
|
| 383 |
+
const centerX = x + s / 2
|
| 384 |
+
const centerY = y + s / 2
|
| 385 |
+
bubble.setAttribute('transform', `rotate(90 ${centerX} ${centerY})`)
|
| 386 |
+
lineGroup.setAttribute('transform', `rotate(90 ${centerX} ${centerY})`)
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
g.append(bubble)
|
| 390 |
+
g.append(lineGroup)
|
| 391 |
+
return g
|
| 392 |
+
}
|
| 393 |
+
// make an exact copy of an image in the overlay
|
| 394 |
+
// one can then apply filters to the entire element, without affecting them;
|
| 395 |
+
// it's a bit silly and probably better to just invert images twice
|
| 396 |
+
// (though the color will be off in that case if you do heu-rotate)
|
| 397 |
+
static copyImage([rect], options = {}) {
|
| 398 |
+
const { src } = options
|
| 399 |
+
const image = createSVGElement('image')
|
| 400 |
+
const { left, top, height, width } = rect
|
| 401 |
+
image.setAttribute('href', src)
|
| 402 |
+
image.setAttribute('x', left)
|
| 403 |
+
image.setAttribute('y', top)
|
| 404 |
+
image.setAttribute('height', height)
|
| 405 |
+
image.setAttribute('width', width)
|
| 406 |
+
return image
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
packages/foliate-js/package-lock.json
ADDED
|
@@ -0,0 +1,1584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "foliate-js",
|
| 3 |
+
"version": "0.0.0",
|
| 4 |
+
"lockfileVersion": 3,
|
| 5 |
+
"requires": true,
|
| 6 |
+
"packages": {
|
| 7 |
+
"": {
|
| 8 |
+
"name": "foliate-js",
|
| 9 |
+
"version": "0.0.0",
|
| 10 |
+
"license": "MIT",
|
| 11 |
+
"dependencies": {
|
| 12 |
+
"construct-style-sheets-polyfill": "^3.1.0"
|
| 13 |
+
},
|
| 14 |
+
"devDependencies": {
|
| 15 |
+
"@eslint/js": "^9.9.1",
|
| 16 |
+
"@rollup/plugin-node-resolve": "^15.2.3",
|
| 17 |
+
"@rollup/plugin-terser": "^0.4.4",
|
| 18 |
+
"@zip.js/zip.js": "^2.7.52",
|
| 19 |
+
"fflate": "^0.8.2",
|
| 20 |
+
"fs-extra": "^11.2.0",
|
| 21 |
+
"globals": "^15.9.0",
|
| 22 |
+
"pdfjs-dist": "^4.7.76",
|
| 23 |
+
"rollup": "^4.22.4"
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
"node_modules/@eslint/js": {
|
| 27 |
+
"version": "9.12.0",
|
| 28 |
+
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.12.0.tgz",
|
| 29 |
+
"integrity": "sha512-eohesHH8WFRUprDNyEREgqP6beG6htMeUYeCpkEgBCieCMme5r9zFWjzAJp//9S+Kub4rqE+jXe9Cp1a7IYIIA==",
|
| 30 |
+
"dev": true,
|
| 31 |
+
"license": "MIT",
|
| 32 |
+
"engines": {
|
| 33 |
+
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"node_modules/@jridgewell/gen-mapping": {
|
| 37 |
+
"version": "0.3.5",
|
| 38 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz",
|
| 39 |
+
"integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==",
|
| 40 |
+
"dev": true,
|
| 41 |
+
"license": "MIT",
|
| 42 |
+
"dependencies": {
|
| 43 |
+
"@jridgewell/set-array": "^1.2.1",
|
| 44 |
+
"@jridgewell/sourcemap-codec": "^1.4.10",
|
| 45 |
+
"@jridgewell/trace-mapping": "^0.3.24"
|
| 46 |
+
},
|
| 47 |
+
"engines": {
|
| 48 |
+
"node": ">=6.0.0"
|
| 49 |
+
}
|
| 50 |
+
},
|
| 51 |
+
"node_modules/@jridgewell/resolve-uri": {
|
| 52 |
+
"version": "3.1.2",
|
| 53 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
|
| 54 |
+
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
|
| 55 |
+
"dev": true,
|
| 56 |
+
"license": "MIT",
|
| 57 |
+
"engines": {
|
| 58 |
+
"node": ">=6.0.0"
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
"node_modules/@jridgewell/set-array": {
|
| 62 |
+
"version": "1.2.1",
|
| 63 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz",
|
| 64 |
+
"integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==",
|
| 65 |
+
"dev": true,
|
| 66 |
+
"license": "MIT",
|
| 67 |
+
"engines": {
|
| 68 |
+
"node": ">=6.0.0"
|
| 69 |
+
}
|
| 70 |
+
},
|
| 71 |
+
"node_modules/@jridgewell/source-map": {
|
| 72 |
+
"version": "0.3.6",
|
| 73 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz",
|
| 74 |
+
"integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==",
|
| 75 |
+
"dev": true,
|
| 76 |
+
"license": "MIT",
|
| 77 |
+
"dependencies": {
|
| 78 |
+
"@jridgewell/gen-mapping": "^0.3.5",
|
| 79 |
+
"@jridgewell/trace-mapping": "^0.3.25"
|
| 80 |
+
}
|
| 81 |
+
},
|
| 82 |
+
"node_modules/@jridgewell/sourcemap-codec": {
|
| 83 |
+
"version": "1.5.0",
|
| 84 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz",
|
| 85 |
+
"integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==",
|
| 86 |
+
"dev": true,
|
| 87 |
+
"license": "MIT"
|
| 88 |
+
},
|
| 89 |
+
"node_modules/@jridgewell/trace-mapping": {
|
| 90 |
+
"version": "0.3.25",
|
| 91 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz",
|
| 92 |
+
"integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==",
|
| 93 |
+
"dev": true,
|
| 94 |
+
"license": "MIT",
|
| 95 |
+
"dependencies": {
|
| 96 |
+
"@jridgewell/resolve-uri": "^3.1.0",
|
| 97 |
+
"@jridgewell/sourcemap-codec": "^1.4.14"
|
| 98 |
+
}
|
| 99 |
+
},
|
| 100 |
+
"node_modules/@mapbox/node-pre-gyp": {
|
| 101 |
+
"version": "1.0.11",
|
| 102 |
+
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
|
| 103 |
+
"integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
|
| 104 |
+
"dev": true,
|
| 105 |
+
"license": "BSD-3-Clause",
|
| 106 |
+
"optional": true,
|
| 107 |
+
"dependencies": {
|
| 108 |
+
"detect-libc": "^2.0.0",
|
| 109 |
+
"https-proxy-agent": "^5.0.0",
|
| 110 |
+
"make-dir": "^3.1.0",
|
| 111 |
+
"node-fetch": "^2.6.7",
|
| 112 |
+
"nopt": "^5.0.0",
|
| 113 |
+
"npmlog": "^5.0.1",
|
| 114 |
+
"rimraf": "^3.0.2",
|
| 115 |
+
"semver": "^7.3.5",
|
| 116 |
+
"tar": "^6.1.11"
|
| 117 |
+
},
|
| 118 |
+
"bin": {
|
| 119 |
+
"node-pre-gyp": "bin/node-pre-gyp"
|
| 120 |
+
}
|
| 121 |
+
},
|
| 122 |
+
"node_modules/@rollup/plugin-node-resolve": {
|
| 123 |
+
"version": "15.3.0",
|
| 124 |
+
"resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.3.0.tgz",
|
| 125 |
+
"integrity": "sha512-9eO5McEICxMzJpDW9OnMYSv4Sta3hmt7VtBFz5zR9273suNOydOyq/FrGeGy+KsTRFm8w0SLVhzig2ILFT63Ag==",
|
| 126 |
+
"dev": true,
|
| 127 |
+
"license": "MIT",
|
| 128 |
+
"dependencies": {
|
| 129 |
+
"@rollup/pluginutils": "^5.0.1",
|
| 130 |
+
"@types/resolve": "1.20.2",
|
| 131 |
+
"deepmerge": "^4.2.2",
|
| 132 |
+
"is-module": "^1.0.0",
|
| 133 |
+
"resolve": "^1.22.1"
|
| 134 |
+
},
|
| 135 |
+
"engines": {
|
| 136 |
+
"node": ">=14.0.0"
|
| 137 |
+
},
|
| 138 |
+
"peerDependencies": {
|
| 139 |
+
"rollup": "^2.78.0||^3.0.0||^4.0.0"
|
| 140 |
+
},
|
| 141 |
+
"peerDependenciesMeta": {
|
| 142 |
+
"rollup": {
|
| 143 |
+
"optional": true
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
},
|
| 147 |
+
"node_modules/@rollup/plugin-terser": {
|
| 148 |
+
"version": "0.4.4",
|
| 149 |
+
"resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz",
|
| 150 |
+
"integrity": "sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==",
|
| 151 |
+
"dev": true,
|
| 152 |
+
"license": "MIT",
|
| 153 |
+
"dependencies": {
|
| 154 |
+
"serialize-javascript": "^6.0.1",
|
| 155 |
+
"smob": "^1.0.0",
|
| 156 |
+
"terser": "^5.17.4"
|
| 157 |
+
},
|
| 158 |
+
"engines": {
|
| 159 |
+
"node": ">=14.0.0"
|
| 160 |
+
},
|
| 161 |
+
"peerDependencies": {
|
| 162 |
+
"rollup": "^2.0.0||^3.0.0||^4.0.0"
|
| 163 |
+
},
|
| 164 |
+
"peerDependenciesMeta": {
|
| 165 |
+
"rollup": {
|
| 166 |
+
"optional": true
|
| 167 |
+
}
|
| 168 |
+
}
|
| 169 |
+
},
|
| 170 |
+
"node_modules/@rollup/pluginutils": {
|
| 171 |
+
"version": "5.1.2",
|
| 172 |
+
"resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.2.tgz",
|
| 173 |
+
"integrity": "sha512-/FIdS3PyZ39bjZlwqFnWqCOVnW7o963LtKMwQOD0NhQqw22gSr2YY1afu3FxRip4ZCZNsD5jq6Aaz6QV3D/Njw==",
|
| 174 |
+
"dev": true,
|
| 175 |
+
"license": "MIT",
|
| 176 |
+
"dependencies": {
|
| 177 |
+
"@types/estree": "^1.0.0",
|
| 178 |
+
"estree-walker": "^2.0.2",
|
| 179 |
+
"picomatch": "^2.3.1"
|
| 180 |
+
},
|
| 181 |
+
"engines": {
|
| 182 |
+
"node": ">=14.0.0"
|
| 183 |
+
},
|
| 184 |
+
"peerDependencies": {
|
| 185 |
+
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
|
| 186 |
+
},
|
| 187 |
+
"peerDependenciesMeta": {
|
| 188 |
+
"rollup": {
|
| 189 |
+
"optional": true
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
},
|
| 193 |
+
"node_modules/@rollup/rollup-android-arm-eabi": {
|
| 194 |
+
"version": "4.24.0",
|
| 195 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.24.0.tgz",
|
| 196 |
+
"integrity": "sha512-Q6HJd7Y6xdB48x8ZNVDOqsbh2uByBhgK8PiQgPhwkIw/HC/YX5Ghq2mQY5sRMZWHb3VsFkWooUVOZHKr7DmDIA==",
|
| 197 |
+
"cpu": [
|
| 198 |
+
"arm"
|
| 199 |
+
],
|
| 200 |
+
"dev": true,
|
| 201 |
+
"license": "MIT",
|
| 202 |
+
"optional": true,
|
| 203 |
+
"os": [
|
| 204 |
+
"android"
|
| 205 |
+
]
|
| 206 |
+
},
|
| 207 |
+
"node_modules/@rollup/rollup-android-arm64": {
|
| 208 |
+
"version": "4.24.0",
|
| 209 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.24.0.tgz",
|
| 210 |
+
"integrity": "sha512-ijLnS1qFId8xhKjT81uBHuuJp2lU4x2yxa4ctFPtG+MqEE6+C5f/+X/bStmxapgmwLwiL3ih122xv8kVARNAZA==",
|
| 211 |
+
"cpu": [
|
| 212 |
+
"arm64"
|
| 213 |
+
],
|
| 214 |
+
"dev": true,
|
| 215 |
+
"license": "MIT",
|
| 216 |
+
"optional": true,
|
| 217 |
+
"os": [
|
| 218 |
+
"android"
|
| 219 |
+
]
|
| 220 |
+
},
|
| 221 |
+
"node_modules/@rollup/rollup-darwin-arm64": {
|
| 222 |
+
"version": "4.24.0",
|
| 223 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.24.0.tgz",
|
| 224 |
+
"integrity": "sha512-bIv+X9xeSs1XCk6DVvkO+S/z8/2AMt/2lMqdQbMrmVpgFvXlmde9mLcbQpztXm1tajC3raFDqegsH18HQPMYtA==",
|
| 225 |
+
"cpu": [
|
| 226 |
+
"arm64"
|
| 227 |
+
],
|
| 228 |
+
"dev": true,
|
| 229 |
+
"license": "MIT",
|
| 230 |
+
"optional": true,
|
| 231 |
+
"os": [
|
| 232 |
+
"darwin"
|
| 233 |
+
]
|
| 234 |
+
},
|
| 235 |
+
"node_modules/@rollup/rollup-darwin-x64": {
|
| 236 |
+
"version": "4.24.0",
|
| 237 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.24.0.tgz",
|
| 238 |
+
"integrity": "sha512-X6/nOwoFN7RT2svEQWUsW/5C/fYMBe4fnLK9DQk4SX4mgVBiTA9h64kjUYPvGQ0F/9xwJ5U5UfTbl6BEjaQdBQ==",
|
| 239 |
+
"cpu": [
|
| 240 |
+
"x64"
|
| 241 |
+
],
|
| 242 |
+
"dev": true,
|
| 243 |
+
"license": "MIT",
|
| 244 |
+
"optional": true,
|
| 245 |
+
"os": [
|
| 246 |
+
"darwin"
|
| 247 |
+
]
|
| 248 |
+
},
|
| 249 |
+
"node_modules/@rollup/rollup-linux-arm-gnueabihf": {
|
| 250 |
+
"version": "4.24.0",
|
| 251 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.24.0.tgz",
|
| 252 |
+
"integrity": "sha512-0KXvIJQMOImLCVCz9uvvdPgfyWo93aHHp8ui3FrtOP57svqrF/roSSR5pjqL2hcMp0ljeGlU4q9o/rQaAQ3AYA==",
|
| 253 |
+
"cpu": [
|
| 254 |
+
"arm"
|
| 255 |
+
],
|
| 256 |
+
"dev": true,
|
| 257 |
+
"license": "MIT",
|
| 258 |
+
"optional": true,
|
| 259 |
+
"os": [
|
| 260 |
+
"linux"
|
| 261 |
+
]
|
| 262 |
+
},
|
| 263 |
+
"node_modules/@rollup/rollup-linux-arm-musleabihf": {
|
| 264 |
+
"version": "4.24.0",
|
| 265 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.24.0.tgz",
|
| 266 |
+
"integrity": "sha512-it2BW6kKFVh8xk/BnHfakEeoLPv8STIISekpoF+nBgWM4d55CZKc7T4Dx1pEbTnYm/xEKMgy1MNtYuoA8RFIWw==",
|
| 267 |
+
"cpu": [
|
| 268 |
+
"arm"
|
| 269 |
+
],
|
| 270 |
+
"dev": true,
|
| 271 |
+
"license": "MIT",
|
| 272 |
+
"optional": true,
|
| 273 |
+
"os": [
|
| 274 |
+
"linux"
|
| 275 |
+
]
|
| 276 |
+
},
|
| 277 |
+
"node_modules/@rollup/rollup-linux-arm64-gnu": {
|
| 278 |
+
"version": "4.24.0",
|
| 279 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.24.0.tgz",
|
| 280 |
+
"integrity": "sha512-i0xTLXjqap2eRfulFVlSnM5dEbTVque/3Pi4g2y7cxrs7+a9De42z4XxKLYJ7+OhE3IgxvfQM7vQc43bwTgPwA==",
|
| 281 |
+
"cpu": [
|
| 282 |
+
"arm64"
|
| 283 |
+
],
|
| 284 |
+
"dev": true,
|
| 285 |
+
"license": "MIT",
|
| 286 |
+
"optional": true,
|
| 287 |
+
"os": [
|
| 288 |
+
"linux"
|
| 289 |
+
]
|
| 290 |
+
},
|
| 291 |
+
"node_modules/@rollup/rollup-linux-arm64-musl": {
|
| 292 |
+
"version": "4.24.0",
|
| 293 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.24.0.tgz",
|
| 294 |
+
"integrity": "sha512-9E6MKUJhDuDh604Qco5yP/3qn3y7SLXYuiC0Rpr89aMScS2UAmK1wHP2b7KAa1nSjWJc/f/Lc0Wl1L47qjiyQw==",
|
| 295 |
+
"cpu": [
|
| 296 |
+
"arm64"
|
| 297 |
+
],
|
| 298 |
+
"dev": true,
|
| 299 |
+
"license": "MIT",
|
| 300 |
+
"optional": true,
|
| 301 |
+
"os": [
|
| 302 |
+
"linux"
|
| 303 |
+
]
|
| 304 |
+
},
|
| 305 |
+
"node_modules/@rollup/rollup-linux-powerpc64le-gnu": {
|
| 306 |
+
"version": "4.24.0",
|
| 307 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.24.0.tgz",
|
| 308 |
+
"integrity": "sha512-2XFFPJ2XMEiF5Zi2EBf4h73oR1V/lycirxZxHZNc93SqDN/IWhYYSYj8I9381ikUFXZrz2v7r2tOVk2NBwxrWw==",
|
| 309 |
+
"cpu": [
|
| 310 |
+
"ppc64"
|
| 311 |
+
],
|
| 312 |
+
"dev": true,
|
| 313 |
+
"license": "MIT",
|
| 314 |
+
"optional": true,
|
| 315 |
+
"os": [
|
| 316 |
+
"linux"
|
| 317 |
+
]
|
| 318 |
+
},
|
| 319 |
+
"node_modules/@rollup/rollup-linux-riscv64-gnu": {
|
| 320 |
+
"version": "4.24.0",
|
| 321 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.24.0.tgz",
|
| 322 |
+
"integrity": "sha512-M3Dg4hlwuntUCdzU7KjYqbbd+BLq3JMAOhCKdBE3TcMGMZbKkDdJ5ivNdehOssMCIokNHFOsv7DO4rlEOfyKpg==",
|
| 323 |
+
"cpu": [
|
| 324 |
+
"riscv64"
|
| 325 |
+
],
|
| 326 |
+
"dev": true,
|
| 327 |
+
"license": "MIT",
|
| 328 |
+
"optional": true,
|
| 329 |
+
"os": [
|
| 330 |
+
"linux"
|
| 331 |
+
]
|
| 332 |
+
},
|
| 333 |
+
"node_modules/@rollup/rollup-linux-s390x-gnu": {
|
| 334 |
+
"version": "4.24.0",
|
| 335 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.24.0.tgz",
|
| 336 |
+
"integrity": "sha512-mjBaoo4ocxJppTorZVKWFpy1bfFj9FeCMJqzlMQGjpNPY9JwQi7OuS1axzNIk0nMX6jSgy6ZURDZ2w0QW6D56g==",
|
| 337 |
+
"cpu": [
|
| 338 |
+
"s390x"
|
| 339 |
+
],
|
| 340 |
+
"dev": true,
|
| 341 |
+
"license": "MIT",
|
| 342 |
+
"optional": true,
|
| 343 |
+
"os": [
|
| 344 |
+
"linux"
|
| 345 |
+
]
|
| 346 |
+
},
|
| 347 |
+
"node_modules/@rollup/rollup-linux-x64-gnu": {
|
| 348 |
+
"version": "4.24.0",
|
| 349 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.24.0.tgz",
|
| 350 |
+
"integrity": "sha512-ZXFk7M72R0YYFN5q13niV0B7G8/5dcQ9JDp8keJSfr3GoZeXEoMHP/HlvqROA3OMbMdfr19IjCeNAnPUG93b6A==",
|
| 351 |
+
"cpu": [
|
| 352 |
+
"x64"
|
| 353 |
+
],
|
| 354 |
+
"dev": true,
|
| 355 |
+
"license": "MIT",
|
| 356 |
+
"optional": true,
|
| 357 |
+
"os": [
|
| 358 |
+
"linux"
|
| 359 |
+
]
|
| 360 |
+
},
|
| 361 |
+
"node_modules/@rollup/rollup-linux-x64-musl": {
|
| 362 |
+
"version": "4.24.0",
|
| 363 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.24.0.tgz",
|
| 364 |
+
"integrity": "sha512-w1i+L7kAXZNdYl+vFvzSZy8Y1arS7vMgIy8wusXJzRrPyof5LAb02KGr1PD2EkRcl73kHulIID0M501lN+vobQ==",
|
| 365 |
+
"cpu": [
|
| 366 |
+
"x64"
|
| 367 |
+
],
|
| 368 |
+
"dev": true,
|
| 369 |
+
"license": "MIT",
|
| 370 |
+
"optional": true,
|
| 371 |
+
"os": [
|
| 372 |
+
"linux"
|
| 373 |
+
]
|
| 374 |
+
},
|
| 375 |
+
"node_modules/@rollup/rollup-win32-arm64-msvc": {
|
| 376 |
+
"version": "4.24.0",
|
| 377 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.24.0.tgz",
|
| 378 |
+
"integrity": "sha512-VXBrnPWgBpVDCVY6XF3LEW0pOU51KbaHhccHw6AS6vBWIC60eqsH19DAeeObl+g8nKAz04QFdl/Cefta0xQtUQ==",
|
| 379 |
+
"cpu": [
|
| 380 |
+
"arm64"
|
| 381 |
+
],
|
| 382 |
+
"dev": true,
|
| 383 |
+
"license": "MIT",
|
| 384 |
+
"optional": true,
|
| 385 |
+
"os": [
|
| 386 |
+
"win32"
|
| 387 |
+
]
|
| 388 |
+
},
|
| 389 |
+
"node_modules/@rollup/rollup-win32-ia32-msvc": {
|
| 390 |
+
"version": "4.24.0",
|
| 391 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.24.0.tgz",
|
| 392 |
+
"integrity": "sha512-xrNcGDU0OxVcPTH/8n/ShH4UevZxKIO6HJFK0e15XItZP2UcaiLFd5kiX7hJnqCbSztUF8Qot+JWBC/QXRPYWQ==",
|
| 393 |
+
"cpu": [
|
| 394 |
+
"ia32"
|
| 395 |
+
],
|
| 396 |
+
"dev": true,
|
| 397 |
+
"license": "MIT",
|
| 398 |
+
"optional": true,
|
| 399 |
+
"os": [
|
| 400 |
+
"win32"
|
| 401 |
+
]
|
| 402 |
+
},
|
| 403 |
+
"node_modules/@rollup/rollup-win32-x64-msvc": {
|
| 404 |
+
"version": "4.24.0",
|
| 405 |
+
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.24.0.tgz",
|
| 406 |
+
"integrity": "sha512-fbMkAF7fufku0N2dE5TBXcNlg0pt0cJue4xBRE2Qc5Vqikxr4VCgKj/ht6SMdFcOacVA9rqF70APJ8RN/4vMJw==",
|
| 407 |
+
"cpu": [
|
| 408 |
+
"x64"
|
| 409 |
+
],
|
| 410 |
+
"dev": true,
|
| 411 |
+
"license": "MIT",
|
| 412 |
+
"optional": true,
|
| 413 |
+
"os": [
|
| 414 |
+
"win32"
|
| 415 |
+
]
|
| 416 |
+
},
|
| 417 |
+
"node_modules/@types/estree": {
|
| 418 |
+
"version": "1.0.6",
|
| 419 |
+
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",
|
| 420 |
+
"integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==",
|
| 421 |
+
"dev": true,
|
| 422 |
+
"license": "MIT"
|
| 423 |
+
},
|
| 424 |
+
"node_modules/@types/resolve": {
|
| 425 |
+
"version": "1.20.2",
|
| 426 |
+
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
|
| 427 |
+
"integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==",
|
| 428 |
+
"dev": true,
|
| 429 |
+
"license": "MIT"
|
| 430 |
+
},
|
| 431 |
+
"node_modules/@zip.js/zip.js": {
|
| 432 |
+
"version": "2.7.52",
|
| 433 |
+
"resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.7.52.tgz",
|
| 434 |
+
"integrity": "sha512-+5g7FQswvrCHwYKNMd/KFxZSObctLSsQOgqBSi0LzwHo3li9Eh1w5cF5ndjQw9Zbr3ajVnd2+XyiX85gAetx1Q==",
|
| 435 |
+
"dev": true,
|
| 436 |
+
"license": "BSD-3-Clause",
|
| 437 |
+
"engines": {
|
| 438 |
+
"bun": ">=0.7.0",
|
| 439 |
+
"deno": ">=1.0.0",
|
| 440 |
+
"node": ">=16.5.0"
|
| 441 |
+
}
|
| 442 |
+
},
|
| 443 |
+
"node_modules/abbrev": {
|
| 444 |
+
"version": "1.1.1",
|
| 445 |
+
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
|
| 446 |
+
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
|
| 447 |
+
"dev": true,
|
| 448 |
+
"license": "ISC",
|
| 449 |
+
"optional": true
|
| 450 |
+
},
|
| 451 |
+
"node_modules/acorn": {
|
| 452 |
+
"version": "8.12.1",
|
| 453 |
+
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz",
|
| 454 |
+
"integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==",
|
| 455 |
+
"dev": true,
|
| 456 |
+
"license": "MIT",
|
| 457 |
+
"bin": {
|
| 458 |
+
"acorn": "bin/acorn"
|
| 459 |
+
},
|
| 460 |
+
"engines": {
|
| 461 |
+
"node": ">=0.4.0"
|
| 462 |
+
}
|
| 463 |
+
},
|
| 464 |
+
"node_modules/agent-base": {
|
| 465 |
+
"version": "6.0.2",
|
| 466 |
+
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
| 467 |
+
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
|
| 468 |
+
"dev": true,
|
| 469 |
+
"license": "MIT",
|
| 470 |
+
"optional": true,
|
| 471 |
+
"dependencies": {
|
| 472 |
+
"debug": "4"
|
| 473 |
+
},
|
| 474 |
+
"engines": {
|
| 475 |
+
"node": ">= 6.0.0"
|
| 476 |
+
}
|
| 477 |
+
},
|
| 478 |
+
"node_modules/ansi-regex": {
|
| 479 |
+
"version": "5.0.1",
|
| 480 |
+
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
| 481 |
+
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
| 482 |
+
"dev": true,
|
| 483 |
+
"license": "MIT",
|
| 484 |
+
"optional": true,
|
| 485 |
+
"engines": {
|
| 486 |
+
"node": ">=8"
|
| 487 |
+
}
|
| 488 |
+
},
|
| 489 |
+
"node_modules/aproba": {
|
| 490 |
+
"version": "2.0.0",
|
| 491 |
+
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
|
| 492 |
+
"integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==",
|
| 493 |
+
"dev": true,
|
| 494 |
+
"license": "ISC",
|
| 495 |
+
"optional": true
|
| 496 |
+
},
|
| 497 |
+
"node_modules/are-we-there-yet": {
|
| 498 |
+
"version": "2.0.0",
|
| 499 |
+
"resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
|
| 500 |
+
"integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
|
| 501 |
+
"deprecated": "This package is no longer supported.",
|
| 502 |
+
"dev": true,
|
| 503 |
+
"license": "ISC",
|
| 504 |
+
"optional": true,
|
| 505 |
+
"dependencies": {
|
| 506 |
+
"delegates": "^1.0.0",
|
| 507 |
+
"readable-stream": "^3.6.0"
|
| 508 |
+
},
|
| 509 |
+
"engines": {
|
| 510 |
+
"node": ">=10"
|
| 511 |
+
}
|
| 512 |
+
},
|
| 513 |
+
"node_modules/balanced-match": {
|
| 514 |
+
"version": "1.0.2",
|
| 515 |
+
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
| 516 |
+
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
| 517 |
+
"dev": true,
|
| 518 |
+
"license": "MIT",
|
| 519 |
+
"optional": true
|
| 520 |
+
},
|
| 521 |
+
"node_modules/brace-expansion": {
|
| 522 |
+
"version": "1.1.11",
|
| 523 |
+
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
|
| 524 |
+
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
|
| 525 |
+
"dev": true,
|
| 526 |
+
"license": "MIT",
|
| 527 |
+
"optional": true,
|
| 528 |
+
"dependencies": {
|
| 529 |
+
"balanced-match": "^1.0.0",
|
| 530 |
+
"concat-map": "0.0.1"
|
| 531 |
+
}
|
| 532 |
+
},
|
| 533 |
+
"node_modules/buffer-from": {
|
| 534 |
+
"version": "1.1.2",
|
| 535 |
+
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
| 536 |
+
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
| 537 |
+
"dev": true,
|
| 538 |
+
"license": "MIT"
|
| 539 |
+
},
|
| 540 |
+
"node_modules/canvas": {
|
| 541 |
+
"version": "2.11.2",
|
| 542 |
+
"resolved": "https://registry.npmjs.org/canvas/-/canvas-2.11.2.tgz",
|
| 543 |
+
"integrity": "sha512-ItanGBMrmRV7Py2Z+Xhs7cT+FNt5K0vPL4p9EZ/UX/Mu7hFbkxSjKF2KVtPwX7UYWp7dRKnrTvReflgrItJbdw==",
|
| 544 |
+
"dev": true,
|
| 545 |
+
"hasInstallScript": true,
|
| 546 |
+
"license": "MIT",
|
| 547 |
+
"optional": true,
|
| 548 |
+
"dependencies": {
|
| 549 |
+
"@mapbox/node-pre-gyp": "^1.0.0",
|
| 550 |
+
"nan": "^2.17.0",
|
| 551 |
+
"simple-get": "^3.0.3"
|
| 552 |
+
},
|
| 553 |
+
"engines": {
|
| 554 |
+
"node": ">=6"
|
| 555 |
+
}
|
| 556 |
+
},
|
| 557 |
+
"node_modules/chownr": {
|
| 558 |
+
"version": "2.0.0",
|
| 559 |
+
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
|
| 560 |
+
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
|
| 561 |
+
"dev": true,
|
| 562 |
+
"license": "ISC",
|
| 563 |
+
"optional": true,
|
| 564 |
+
"engines": {
|
| 565 |
+
"node": ">=10"
|
| 566 |
+
}
|
| 567 |
+
},
|
| 568 |
+
"node_modules/color-support": {
|
| 569 |
+
"version": "1.1.3",
|
| 570 |
+
"resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
|
| 571 |
+
"integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
|
| 572 |
+
"dev": true,
|
| 573 |
+
"license": "ISC",
|
| 574 |
+
"optional": true,
|
| 575 |
+
"bin": {
|
| 576 |
+
"color-support": "bin.js"
|
| 577 |
+
}
|
| 578 |
+
},
|
| 579 |
+
"node_modules/commander": {
|
| 580 |
+
"version": "2.20.3",
|
| 581 |
+
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
|
| 582 |
+
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
|
| 583 |
+
"dev": true,
|
| 584 |
+
"license": "MIT"
|
| 585 |
+
},
|
| 586 |
+
"node_modules/concat-map": {
|
| 587 |
+
"version": "0.0.1",
|
| 588 |
+
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
| 589 |
+
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
|
| 590 |
+
"dev": true,
|
| 591 |
+
"license": "MIT",
|
| 592 |
+
"optional": true
|
| 593 |
+
},
|
| 594 |
+
"node_modules/console-control-strings": {
|
| 595 |
+
"version": "1.1.0",
|
| 596 |
+
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
|
| 597 |
+
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==",
|
| 598 |
+
"dev": true,
|
| 599 |
+
"license": "ISC",
|
| 600 |
+
"optional": true
|
| 601 |
+
},
|
| 602 |
+
"node_modules/construct-style-sheets-polyfill": {
|
| 603 |
+
"version": "3.1.0",
|
| 604 |
+
"resolved": "https://registry.npmmirror.com/construct-style-sheets-polyfill/-/construct-style-sheets-polyfill-3.1.0.tgz",
|
| 605 |
+
"integrity": "sha512-HBLKP0chz8BAY6rBdzda11c3wAZeCZ+kIG4weVC2NM3AXzxx09nhe8t0SQNdloAvg5GLuHwq/0SPOOSPvtCcKw==",
|
| 606 |
+
"license": "MIT"
|
| 607 |
+
},
|
| 608 |
+
"node_modules/debug": {
|
| 609 |
+
"version": "4.3.7",
|
| 610 |
+
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
|
| 611 |
+
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
|
| 612 |
+
"dev": true,
|
| 613 |
+
"license": "MIT",
|
| 614 |
+
"optional": true,
|
| 615 |
+
"dependencies": {
|
| 616 |
+
"ms": "^2.1.3"
|
| 617 |
+
},
|
| 618 |
+
"engines": {
|
| 619 |
+
"node": ">=6.0"
|
| 620 |
+
},
|
| 621 |
+
"peerDependenciesMeta": {
|
| 622 |
+
"supports-color": {
|
| 623 |
+
"optional": true
|
| 624 |
+
}
|
| 625 |
+
}
|
| 626 |
+
},
|
| 627 |
+
"node_modules/decompress-response": {
|
| 628 |
+
"version": "4.2.1",
|
| 629 |
+
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-4.2.1.tgz",
|
| 630 |
+
"integrity": "sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==",
|
| 631 |
+
"dev": true,
|
| 632 |
+
"license": "MIT",
|
| 633 |
+
"optional": true,
|
| 634 |
+
"dependencies": {
|
| 635 |
+
"mimic-response": "^2.0.0"
|
| 636 |
+
},
|
| 637 |
+
"engines": {
|
| 638 |
+
"node": ">=8"
|
| 639 |
+
}
|
| 640 |
+
},
|
| 641 |
+
"node_modules/deepmerge": {
|
| 642 |
+
"version": "4.3.1",
|
| 643 |
+
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
|
| 644 |
+
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
|
| 645 |
+
"dev": true,
|
| 646 |
+
"license": "MIT",
|
| 647 |
+
"engines": {
|
| 648 |
+
"node": ">=0.10.0"
|
| 649 |
+
}
|
| 650 |
+
},
|
| 651 |
+
"node_modules/delegates": {
|
| 652 |
+
"version": "1.0.0",
|
| 653 |
+
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
|
| 654 |
+
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==",
|
| 655 |
+
"dev": true,
|
| 656 |
+
"license": "MIT",
|
| 657 |
+
"optional": true
|
| 658 |
+
},
|
| 659 |
+
"node_modules/detect-libc": {
|
| 660 |
+
"version": "2.0.3",
|
| 661 |
+
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
|
| 662 |
+
"integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==",
|
| 663 |
+
"dev": true,
|
| 664 |
+
"license": "Apache-2.0",
|
| 665 |
+
"optional": true,
|
| 666 |
+
"engines": {
|
| 667 |
+
"node": ">=8"
|
| 668 |
+
}
|
| 669 |
+
},
|
| 670 |
+
"node_modules/emoji-regex": {
|
| 671 |
+
"version": "8.0.0",
|
| 672 |
+
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
| 673 |
+
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
| 674 |
+
"dev": true,
|
| 675 |
+
"license": "MIT",
|
| 676 |
+
"optional": true
|
| 677 |
+
},
|
| 678 |
+
"node_modules/estree-walker": {
|
| 679 |
+
"version": "2.0.2",
|
| 680 |
+
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
|
| 681 |
+
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
| 682 |
+
"dev": true,
|
| 683 |
+
"license": "MIT"
|
| 684 |
+
},
|
| 685 |
+
"node_modules/fflate": {
|
| 686 |
+
"version": "0.8.2",
|
| 687 |
+
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
|
| 688 |
+
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
|
| 689 |
+
"dev": true,
|
| 690 |
+
"license": "MIT"
|
| 691 |
+
},
|
| 692 |
+
"node_modules/fs-extra": {
|
| 693 |
+
"version": "11.2.0",
|
| 694 |
+
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz",
|
| 695 |
+
"integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==",
|
| 696 |
+
"dev": true,
|
| 697 |
+
"license": "MIT",
|
| 698 |
+
"dependencies": {
|
| 699 |
+
"graceful-fs": "^4.2.0",
|
| 700 |
+
"jsonfile": "^6.0.1",
|
| 701 |
+
"universalify": "^2.0.0"
|
| 702 |
+
},
|
| 703 |
+
"engines": {
|
| 704 |
+
"node": ">=14.14"
|
| 705 |
+
}
|
| 706 |
+
},
|
| 707 |
+
"node_modules/fs-minipass": {
|
| 708 |
+
"version": "2.1.0",
|
| 709 |
+
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
|
| 710 |
+
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
|
| 711 |
+
"dev": true,
|
| 712 |
+
"license": "ISC",
|
| 713 |
+
"optional": true,
|
| 714 |
+
"dependencies": {
|
| 715 |
+
"minipass": "^3.0.0"
|
| 716 |
+
},
|
| 717 |
+
"engines": {
|
| 718 |
+
"node": ">= 8"
|
| 719 |
+
}
|
| 720 |
+
},
|
| 721 |
+
"node_modules/fs-minipass/node_modules/minipass": {
|
| 722 |
+
"version": "3.3.6",
|
| 723 |
+
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
|
| 724 |
+
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
|
| 725 |
+
"dev": true,
|
| 726 |
+
"license": "ISC",
|
| 727 |
+
"optional": true,
|
| 728 |
+
"dependencies": {
|
| 729 |
+
"yallist": "^4.0.0"
|
| 730 |
+
},
|
| 731 |
+
"engines": {
|
| 732 |
+
"node": ">=8"
|
| 733 |
+
}
|
| 734 |
+
},
|
| 735 |
+
"node_modules/fs.realpath": {
|
| 736 |
+
"version": "1.0.0",
|
| 737 |
+
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
| 738 |
+
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
| 739 |
+
"dev": true,
|
| 740 |
+
"license": "ISC",
|
| 741 |
+
"optional": true
|
| 742 |
+
},
|
| 743 |
+
"node_modules/fsevents": {
|
| 744 |
+
"version": "2.3.3",
|
| 745 |
+
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
| 746 |
+
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
| 747 |
+
"dev": true,
|
| 748 |
+
"hasInstallScript": true,
|
| 749 |
+
"license": "MIT",
|
| 750 |
+
"optional": true,
|
| 751 |
+
"os": [
|
| 752 |
+
"darwin"
|
| 753 |
+
],
|
| 754 |
+
"engines": {
|
| 755 |
+
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
| 756 |
+
}
|
| 757 |
+
},
|
| 758 |
+
"node_modules/function-bind": {
|
| 759 |
+
"version": "1.1.2",
|
| 760 |
+
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
| 761 |
+
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
| 762 |
+
"dev": true,
|
| 763 |
+
"license": "MIT",
|
| 764 |
+
"funding": {
|
| 765 |
+
"url": "https://github.com/sponsors/ljharb"
|
| 766 |
+
}
|
| 767 |
+
},
|
| 768 |
+
"node_modules/gauge": {
|
| 769 |
+
"version": "3.0.2",
|
| 770 |
+
"resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
|
| 771 |
+
"integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
|
| 772 |
+
"deprecated": "This package is no longer supported.",
|
| 773 |
+
"dev": true,
|
| 774 |
+
"license": "ISC",
|
| 775 |
+
"optional": true,
|
| 776 |
+
"dependencies": {
|
| 777 |
+
"aproba": "^1.0.3 || ^2.0.0",
|
| 778 |
+
"color-support": "^1.1.2",
|
| 779 |
+
"console-control-strings": "^1.0.0",
|
| 780 |
+
"has-unicode": "^2.0.1",
|
| 781 |
+
"object-assign": "^4.1.1",
|
| 782 |
+
"signal-exit": "^3.0.0",
|
| 783 |
+
"string-width": "^4.2.3",
|
| 784 |
+
"strip-ansi": "^6.0.1",
|
| 785 |
+
"wide-align": "^1.1.2"
|
| 786 |
+
},
|
| 787 |
+
"engines": {
|
| 788 |
+
"node": ">=10"
|
| 789 |
+
}
|
| 790 |
+
},
|
| 791 |
+
"node_modules/glob": {
|
| 792 |
+
"version": "7.2.3",
|
| 793 |
+
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
| 794 |
+
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
| 795 |
+
"deprecated": "Glob versions prior to v9 are no longer supported",
|
| 796 |
+
"dev": true,
|
| 797 |
+
"license": "ISC",
|
| 798 |
+
"optional": true,
|
| 799 |
+
"dependencies": {
|
| 800 |
+
"fs.realpath": "^1.0.0",
|
| 801 |
+
"inflight": "^1.0.4",
|
| 802 |
+
"inherits": "2",
|
| 803 |
+
"minimatch": "^3.1.1",
|
| 804 |
+
"once": "^1.3.0",
|
| 805 |
+
"path-is-absolute": "^1.0.0"
|
| 806 |
+
},
|
| 807 |
+
"engines": {
|
| 808 |
+
"node": "*"
|
| 809 |
+
},
|
| 810 |
+
"funding": {
|
| 811 |
+
"url": "https://github.com/sponsors/isaacs"
|
| 812 |
+
}
|
| 813 |
+
},
|
| 814 |
+
"node_modules/globals": {
|
| 815 |
+
"version": "15.11.0",
|
| 816 |
+
"resolved": "https://registry.npmjs.org/globals/-/globals-15.11.0.tgz",
|
| 817 |
+
"integrity": "sha512-yeyNSjdbyVaWurlwCpcA6XNBrHTMIeDdj0/hnvX/OLJ9ekOXYbLsLinH/MucQyGvNnXhidTdNhTtJaffL2sMfw==",
|
| 818 |
+
"dev": true,
|
| 819 |
+
"license": "MIT",
|
| 820 |
+
"engines": {
|
| 821 |
+
"node": ">=18"
|
| 822 |
+
},
|
| 823 |
+
"funding": {
|
| 824 |
+
"url": "https://github.com/sponsors/sindresorhus"
|
| 825 |
+
}
|
| 826 |
+
},
|
| 827 |
+
"node_modules/graceful-fs": {
|
| 828 |
+
"version": "4.2.11",
|
| 829 |
+
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
| 830 |
+
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
| 831 |
+
"dev": true,
|
| 832 |
+
"license": "ISC"
|
| 833 |
+
},
|
| 834 |
+
"node_modules/has-unicode": {
|
| 835 |
+
"version": "2.0.1",
|
| 836 |
+
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
|
| 837 |
+
"integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==",
|
| 838 |
+
"dev": true,
|
| 839 |
+
"license": "ISC",
|
| 840 |
+
"optional": true
|
| 841 |
+
},
|
| 842 |
+
"node_modules/hasown": {
|
| 843 |
+
"version": "2.0.2",
|
| 844 |
+
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
| 845 |
+
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
| 846 |
+
"dev": true,
|
| 847 |
+
"license": "MIT",
|
| 848 |
+
"dependencies": {
|
| 849 |
+
"function-bind": "^1.1.2"
|
| 850 |
+
},
|
| 851 |
+
"engines": {
|
| 852 |
+
"node": ">= 0.4"
|
| 853 |
+
}
|
| 854 |
+
},
|
| 855 |
+
"node_modules/https-proxy-agent": {
|
| 856 |
+
"version": "5.0.1",
|
| 857 |
+
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
| 858 |
+
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
|
| 859 |
+
"dev": true,
|
| 860 |
+
"license": "MIT",
|
| 861 |
+
"optional": true,
|
| 862 |
+
"dependencies": {
|
| 863 |
+
"agent-base": "6",
|
| 864 |
+
"debug": "4"
|
| 865 |
+
},
|
| 866 |
+
"engines": {
|
| 867 |
+
"node": ">= 6"
|
| 868 |
+
}
|
| 869 |
+
},
|
| 870 |
+
"node_modules/inflight": {
|
| 871 |
+
"version": "1.0.6",
|
| 872 |
+
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
| 873 |
+
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
|
| 874 |
+
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
|
| 875 |
+
"dev": true,
|
| 876 |
+
"license": "ISC",
|
| 877 |
+
"optional": true,
|
| 878 |
+
"dependencies": {
|
| 879 |
+
"once": "^1.3.0",
|
| 880 |
+
"wrappy": "1"
|
| 881 |
+
}
|
| 882 |
+
},
|
| 883 |
+
"node_modules/inherits": {
|
| 884 |
+
"version": "2.0.4",
|
| 885 |
+
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
| 886 |
+
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
| 887 |
+
"dev": true,
|
| 888 |
+
"license": "ISC",
|
| 889 |
+
"optional": true
|
| 890 |
+
},
|
| 891 |
+
"node_modules/is-core-module": {
|
| 892 |
+
"version": "2.15.1",
|
| 893 |
+
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz",
|
| 894 |
+
"integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==",
|
| 895 |
+
"dev": true,
|
| 896 |
+
"license": "MIT",
|
| 897 |
+
"dependencies": {
|
| 898 |
+
"hasown": "^2.0.2"
|
| 899 |
+
},
|
| 900 |
+
"engines": {
|
| 901 |
+
"node": ">= 0.4"
|
| 902 |
+
},
|
| 903 |
+
"funding": {
|
| 904 |
+
"url": "https://github.com/sponsors/ljharb"
|
| 905 |
+
}
|
| 906 |
+
},
|
| 907 |
+
"node_modules/is-fullwidth-code-point": {
|
| 908 |
+
"version": "3.0.0",
|
| 909 |
+
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
| 910 |
+
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
| 911 |
+
"dev": true,
|
| 912 |
+
"license": "MIT",
|
| 913 |
+
"optional": true,
|
| 914 |
+
"engines": {
|
| 915 |
+
"node": ">=8"
|
| 916 |
+
}
|
| 917 |
+
},
|
| 918 |
+
"node_modules/is-module": {
|
| 919 |
+
"version": "1.0.0",
|
| 920 |
+
"resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz",
|
| 921 |
+
"integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==",
|
| 922 |
+
"dev": true,
|
| 923 |
+
"license": "MIT"
|
| 924 |
+
},
|
| 925 |
+
"node_modules/jsonfile": {
|
| 926 |
+
"version": "6.1.0",
|
| 927 |
+
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
|
| 928 |
+
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
|
| 929 |
+
"dev": true,
|
| 930 |
+
"license": "MIT",
|
| 931 |
+
"dependencies": {
|
| 932 |
+
"universalify": "^2.0.0"
|
| 933 |
+
},
|
| 934 |
+
"optionalDependencies": {
|
| 935 |
+
"graceful-fs": "^4.1.6"
|
| 936 |
+
}
|
| 937 |
+
},
|
| 938 |
+
"node_modules/make-dir": {
|
| 939 |
+
"version": "3.1.0",
|
| 940 |
+
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
| 941 |
+
"integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
|
| 942 |
+
"dev": true,
|
| 943 |
+
"license": "MIT",
|
| 944 |
+
"optional": true,
|
| 945 |
+
"dependencies": {
|
| 946 |
+
"semver": "^6.0.0"
|
| 947 |
+
},
|
| 948 |
+
"engines": {
|
| 949 |
+
"node": ">=8"
|
| 950 |
+
},
|
| 951 |
+
"funding": {
|
| 952 |
+
"url": "https://github.com/sponsors/sindresorhus"
|
| 953 |
+
}
|
| 954 |
+
},
|
| 955 |
+
"node_modules/make-dir/node_modules/semver": {
|
| 956 |
+
"version": "6.3.1",
|
| 957 |
+
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
|
| 958 |
+
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
|
| 959 |
+
"dev": true,
|
| 960 |
+
"license": "ISC",
|
| 961 |
+
"optional": true,
|
| 962 |
+
"bin": {
|
| 963 |
+
"semver": "bin/semver.js"
|
| 964 |
+
}
|
| 965 |
+
},
|
| 966 |
+
"node_modules/mimic-response": {
|
| 967 |
+
"version": "2.1.0",
|
| 968 |
+
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-2.1.0.tgz",
|
| 969 |
+
"integrity": "sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==",
|
| 970 |
+
"dev": true,
|
| 971 |
+
"license": "MIT",
|
| 972 |
+
"optional": true,
|
| 973 |
+
"engines": {
|
| 974 |
+
"node": ">=8"
|
| 975 |
+
},
|
| 976 |
+
"funding": {
|
| 977 |
+
"url": "https://github.com/sponsors/sindresorhus"
|
| 978 |
+
}
|
| 979 |
+
},
|
| 980 |
+
"node_modules/minimatch": {
|
| 981 |
+
"version": "3.1.2",
|
| 982 |
+
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
|
| 983 |
+
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
| 984 |
+
"dev": true,
|
| 985 |
+
"license": "ISC",
|
| 986 |
+
"optional": true,
|
| 987 |
+
"dependencies": {
|
| 988 |
+
"brace-expansion": "^1.1.7"
|
| 989 |
+
},
|
| 990 |
+
"engines": {
|
| 991 |
+
"node": "*"
|
| 992 |
+
}
|
| 993 |
+
},
|
| 994 |
+
"node_modules/minipass": {
|
| 995 |
+
"version": "5.0.0",
|
| 996 |
+
"resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
|
| 997 |
+
"integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
|
| 998 |
+
"dev": true,
|
| 999 |
+
"license": "ISC",
|
| 1000 |
+
"optional": true,
|
| 1001 |
+
"engines": {
|
| 1002 |
+
"node": ">=8"
|
| 1003 |
+
}
|
| 1004 |
+
},
|
| 1005 |
+
"node_modules/minizlib": {
|
| 1006 |
+
"version": "2.1.2",
|
| 1007 |
+
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
|
| 1008 |
+
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
|
| 1009 |
+
"dev": true,
|
| 1010 |
+
"license": "MIT",
|
| 1011 |
+
"optional": true,
|
| 1012 |
+
"dependencies": {
|
| 1013 |
+
"minipass": "^3.0.0",
|
| 1014 |
+
"yallist": "^4.0.0"
|
| 1015 |
+
},
|
| 1016 |
+
"engines": {
|
| 1017 |
+
"node": ">= 8"
|
| 1018 |
+
}
|
| 1019 |
+
},
|
| 1020 |
+
"node_modules/minizlib/node_modules/minipass": {
|
| 1021 |
+
"version": "3.3.6",
|
| 1022 |
+
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
|
| 1023 |
+
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
|
| 1024 |
+
"dev": true,
|
| 1025 |
+
"license": "ISC",
|
| 1026 |
+
"optional": true,
|
| 1027 |
+
"dependencies": {
|
| 1028 |
+
"yallist": "^4.0.0"
|
| 1029 |
+
},
|
| 1030 |
+
"engines": {
|
| 1031 |
+
"node": ">=8"
|
| 1032 |
+
}
|
| 1033 |
+
},
|
| 1034 |
+
"node_modules/mkdirp": {
|
| 1035 |
+
"version": "1.0.4",
|
| 1036 |
+
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
|
| 1037 |
+
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
|
| 1038 |
+
"dev": true,
|
| 1039 |
+
"license": "MIT",
|
| 1040 |
+
"optional": true,
|
| 1041 |
+
"bin": {
|
| 1042 |
+
"mkdirp": "bin/cmd.js"
|
| 1043 |
+
},
|
| 1044 |
+
"engines": {
|
| 1045 |
+
"node": ">=10"
|
| 1046 |
+
}
|
| 1047 |
+
},
|
| 1048 |
+
"node_modules/ms": {
|
| 1049 |
+
"version": "2.1.3",
|
| 1050 |
+
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
| 1051 |
+
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
| 1052 |
+
"dev": true,
|
| 1053 |
+
"license": "MIT",
|
| 1054 |
+
"optional": true
|
| 1055 |
+
},
|
| 1056 |
+
"node_modules/nan": {
|
| 1057 |
+
"version": "2.22.0",
|
| 1058 |
+
"resolved": "https://registry.npmjs.org/nan/-/nan-2.22.0.tgz",
|
| 1059 |
+
"integrity": "sha512-nbajikzWTMwsW+eSsNm3QwlOs7het9gGJU5dDZzRTQGk03vyBOauxgI4VakDzE0PtsGTmXPsXTbbjVhRwR5mpw==",
|
| 1060 |
+
"dev": true,
|
| 1061 |
+
"license": "MIT",
|
| 1062 |
+
"optional": true
|
| 1063 |
+
},
|
| 1064 |
+
"node_modules/node-fetch": {
|
| 1065 |
+
"version": "2.7.0",
|
| 1066 |
+
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
| 1067 |
+
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
| 1068 |
+
"dev": true,
|
| 1069 |
+
"license": "MIT",
|
| 1070 |
+
"optional": true,
|
| 1071 |
+
"dependencies": {
|
| 1072 |
+
"whatwg-url": "^5.0.0"
|
| 1073 |
+
},
|
| 1074 |
+
"engines": {
|
| 1075 |
+
"node": "4.x || >=6.0.0"
|
| 1076 |
+
},
|
| 1077 |
+
"peerDependencies": {
|
| 1078 |
+
"encoding": "^0.1.0"
|
| 1079 |
+
},
|
| 1080 |
+
"peerDependenciesMeta": {
|
| 1081 |
+
"encoding": {
|
| 1082 |
+
"optional": true
|
| 1083 |
+
}
|
| 1084 |
+
}
|
| 1085 |
+
},
|
| 1086 |
+
"node_modules/nopt": {
|
| 1087 |
+
"version": "5.0.0",
|
| 1088 |
+
"resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
|
| 1089 |
+
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
|
| 1090 |
+
"dev": true,
|
| 1091 |
+
"license": "ISC",
|
| 1092 |
+
"optional": true,
|
| 1093 |
+
"dependencies": {
|
| 1094 |
+
"abbrev": "1"
|
| 1095 |
+
},
|
| 1096 |
+
"bin": {
|
| 1097 |
+
"nopt": "bin/nopt.js"
|
| 1098 |
+
},
|
| 1099 |
+
"engines": {
|
| 1100 |
+
"node": ">=6"
|
| 1101 |
+
}
|
| 1102 |
+
},
|
| 1103 |
+
"node_modules/npmlog": {
|
| 1104 |
+
"version": "5.0.1",
|
| 1105 |
+
"resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
|
| 1106 |
+
"integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
|
| 1107 |
+
"deprecated": "This package is no longer supported.",
|
| 1108 |
+
"dev": true,
|
| 1109 |
+
"license": "ISC",
|
| 1110 |
+
"optional": true,
|
| 1111 |
+
"dependencies": {
|
| 1112 |
+
"are-we-there-yet": "^2.0.0",
|
| 1113 |
+
"console-control-strings": "^1.1.0",
|
| 1114 |
+
"gauge": "^3.0.0",
|
| 1115 |
+
"set-blocking": "^2.0.0"
|
| 1116 |
+
}
|
| 1117 |
+
},
|
| 1118 |
+
"node_modules/object-assign": {
|
| 1119 |
+
"version": "4.1.1",
|
| 1120 |
+
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
| 1121 |
+
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
| 1122 |
+
"dev": true,
|
| 1123 |
+
"license": "MIT",
|
| 1124 |
+
"optional": true,
|
| 1125 |
+
"engines": {
|
| 1126 |
+
"node": ">=0.10.0"
|
| 1127 |
+
}
|
| 1128 |
+
},
|
| 1129 |
+
"node_modules/once": {
|
| 1130 |
+
"version": "1.4.0",
|
| 1131 |
+
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
| 1132 |
+
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
| 1133 |
+
"dev": true,
|
| 1134 |
+
"license": "ISC",
|
| 1135 |
+
"optional": true,
|
| 1136 |
+
"dependencies": {
|
| 1137 |
+
"wrappy": "1"
|
| 1138 |
+
}
|
| 1139 |
+
},
|
| 1140 |
+
"node_modules/path-is-absolute": {
|
| 1141 |
+
"version": "1.0.1",
|
| 1142 |
+
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
| 1143 |
+
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
|
| 1144 |
+
"dev": true,
|
| 1145 |
+
"license": "MIT",
|
| 1146 |
+
"optional": true,
|
| 1147 |
+
"engines": {
|
| 1148 |
+
"node": ">=0.10.0"
|
| 1149 |
+
}
|
| 1150 |
+
},
|
| 1151 |
+
"node_modules/path-parse": {
|
| 1152 |
+
"version": "1.0.7",
|
| 1153 |
+
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
|
| 1154 |
+
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
|
| 1155 |
+
"dev": true,
|
| 1156 |
+
"license": "MIT"
|
| 1157 |
+
},
|
| 1158 |
+
"node_modules/path2d": {
|
| 1159 |
+
"version": "0.2.1",
|
| 1160 |
+
"resolved": "https://registry.npmjs.org/path2d/-/path2d-0.2.1.tgz",
|
| 1161 |
+
"integrity": "sha512-Fl2z/BHvkTNvkuBzYTpTuirHZg6wW9z8+4SND/3mDTEcYbbNKWAy21dz9D3ePNNwrrK8pqZO5vLPZ1hLF6T7XA==",
|
| 1162 |
+
"dev": true,
|
| 1163 |
+
"license": "MIT",
|
| 1164 |
+
"optional": true,
|
| 1165 |
+
"engines": {
|
| 1166 |
+
"node": ">=6"
|
| 1167 |
+
}
|
| 1168 |
+
},
|
| 1169 |
+
"node_modules/pdfjs-dist": {
|
| 1170 |
+
"version": "4.7.76",
|
| 1171 |
+
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-4.7.76.tgz",
|
| 1172 |
+
"integrity": "sha512-8y6wUgC/Em35IumlGjaJOCm3wV4aY/6sqnIT3fVW/67mXsOZ9HWBn8GDKmJUK0GSzpbmX3gQqwfoFayp78Mtqw==",
|
| 1173 |
+
"dev": true,
|
| 1174 |
+
"license": "Apache-2.0",
|
| 1175 |
+
"engines": {
|
| 1176 |
+
"node": ">=18"
|
| 1177 |
+
},
|
| 1178 |
+
"optionalDependencies": {
|
| 1179 |
+
"canvas": "^2.11.2",
|
| 1180 |
+
"path2d": "^0.2.1"
|
| 1181 |
+
}
|
| 1182 |
+
},
|
| 1183 |
+
"node_modules/picomatch": {
|
| 1184 |
+
"version": "2.3.1",
|
| 1185 |
+
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
|
| 1186 |
+
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
|
| 1187 |
+
"dev": true,
|
| 1188 |
+
"license": "MIT",
|
| 1189 |
+
"engines": {
|
| 1190 |
+
"node": ">=8.6"
|
| 1191 |
+
},
|
| 1192 |
+
"funding": {
|
| 1193 |
+
"url": "https://github.com/sponsors/jonschlinkert"
|
| 1194 |
+
}
|
| 1195 |
+
},
|
| 1196 |
+
"node_modules/randombytes": {
|
| 1197 |
+
"version": "2.1.0",
|
| 1198 |
+
"resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
|
| 1199 |
+
"integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
|
| 1200 |
+
"dev": true,
|
| 1201 |
+
"license": "MIT",
|
| 1202 |
+
"dependencies": {
|
| 1203 |
+
"safe-buffer": "^5.1.0"
|
| 1204 |
+
}
|
| 1205 |
+
},
|
| 1206 |
+
"node_modules/readable-stream": {
|
| 1207 |
+
"version": "3.6.2",
|
| 1208 |
+
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
| 1209 |
+
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
| 1210 |
+
"dev": true,
|
| 1211 |
+
"license": "MIT",
|
| 1212 |
+
"optional": true,
|
| 1213 |
+
"dependencies": {
|
| 1214 |
+
"inherits": "^2.0.3",
|
| 1215 |
+
"string_decoder": "^1.1.1",
|
| 1216 |
+
"util-deprecate": "^1.0.1"
|
| 1217 |
+
},
|
| 1218 |
+
"engines": {
|
| 1219 |
+
"node": ">= 6"
|
| 1220 |
+
}
|
| 1221 |
+
},
|
| 1222 |
+
"node_modules/resolve": {
|
| 1223 |
+
"version": "1.22.8",
|
| 1224 |
+
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz",
|
| 1225 |
+
"integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==",
|
| 1226 |
+
"dev": true,
|
| 1227 |
+
"license": "MIT",
|
| 1228 |
+
"dependencies": {
|
| 1229 |
+
"is-core-module": "^2.13.0",
|
| 1230 |
+
"path-parse": "^1.0.7",
|
| 1231 |
+
"supports-preserve-symlinks-flag": "^1.0.0"
|
| 1232 |
+
},
|
| 1233 |
+
"bin": {
|
| 1234 |
+
"resolve": "bin/resolve"
|
| 1235 |
+
},
|
| 1236 |
+
"funding": {
|
| 1237 |
+
"url": "https://github.com/sponsors/ljharb"
|
| 1238 |
+
}
|
| 1239 |
+
},
|
| 1240 |
+
"node_modules/rimraf": {
|
| 1241 |
+
"version": "3.0.2",
|
| 1242 |
+
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
| 1243 |
+
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
|
| 1244 |
+
"deprecated": "Rimraf versions prior to v4 are no longer supported",
|
| 1245 |
+
"dev": true,
|
| 1246 |
+
"license": "ISC",
|
| 1247 |
+
"optional": true,
|
| 1248 |
+
"dependencies": {
|
| 1249 |
+
"glob": "^7.1.3"
|
| 1250 |
+
},
|
| 1251 |
+
"bin": {
|
| 1252 |
+
"rimraf": "bin.js"
|
| 1253 |
+
},
|
| 1254 |
+
"funding": {
|
| 1255 |
+
"url": "https://github.com/sponsors/isaacs"
|
| 1256 |
+
}
|
| 1257 |
+
},
|
| 1258 |
+
"node_modules/rollup": {
|
| 1259 |
+
"version": "4.24.0",
|
| 1260 |
+
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.24.0.tgz",
|
| 1261 |
+
"integrity": "sha512-DOmrlGSXNk1DM0ljiQA+i+o0rSLhtii1je5wgk60j49d1jHT5YYttBv1iWOnYSTG+fZZESUOSNiAl89SIet+Cg==",
|
| 1262 |
+
"dev": true,
|
| 1263 |
+
"license": "MIT",
|
| 1264 |
+
"dependencies": {
|
| 1265 |
+
"@types/estree": "1.0.6"
|
| 1266 |
+
},
|
| 1267 |
+
"bin": {
|
| 1268 |
+
"rollup": "dist/bin/rollup"
|
| 1269 |
+
},
|
| 1270 |
+
"engines": {
|
| 1271 |
+
"node": ">=18.0.0",
|
| 1272 |
+
"npm": ">=8.0.0"
|
| 1273 |
+
},
|
| 1274 |
+
"optionalDependencies": {
|
| 1275 |
+
"@rollup/rollup-android-arm-eabi": "4.24.0",
|
| 1276 |
+
"@rollup/rollup-android-arm64": "4.24.0",
|
| 1277 |
+
"@rollup/rollup-darwin-arm64": "4.24.0",
|
| 1278 |
+
"@rollup/rollup-darwin-x64": "4.24.0",
|
| 1279 |
+
"@rollup/rollup-linux-arm-gnueabihf": "4.24.0",
|
| 1280 |
+
"@rollup/rollup-linux-arm-musleabihf": "4.24.0",
|
| 1281 |
+
"@rollup/rollup-linux-arm64-gnu": "4.24.0",
|
| 1282 |
+
"@rollup/rollup-linux-arm64-musl": "4.24.0",
|
| 1283 |
+
"@rollup/rollup-linux-powerpc64le-gnu": "4.24.0",
|
| 1284 |
+
"@rollup/rollup-linux-riscv64-gnu": "4.24.0",
|
| 1285 |
+
"@rollup/rollup-linux-s390x-gnu": "4.24.0",
|
| 1286 |
+
"@rollup/rollup-linux-x64-gnu": "4.24.0",
|
| 1287 |
+
"@rollup/rollup-linux-x64-musl": "4.24.0",
|
| 1288 |
+
"@rollup/rollup-win32-arm64-msvc": "4.24.0",
|
| 1289 |
+
"@rollup/rollup-win32-ia32-msvc": "4.24.0",
|
| 1290 |
+
"@rollup/rollup-win32-x64-msvc": "4.24.0",
|
| 1291 |
+
"fsevents": "~2.3.2"
|
| 1292 |
+
}
|
| 1293 |
+
},
|
| 1294 |
+
"node_modules/safe-buffer": {
|
| 1295 |
+
"version": "5.2.1",
|
| 1296 |
+
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
| 1297 |
+
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
| 1298 |
+
"dev": true,
|
| 1299 |
+
"funding": [
|
| 1300 |
+
{
|
| 1301 |
+
"type": "github",
|
| 1302 |
+
"url": "https://github.com/sponsors/feross"
|
| 1303 |
+
},
|
| 1304 |
+
{
|
| 1305 |
+
"type": "patreon",
|
| 1306 |
+
"url": "https://www.patreon.com/feross"
|
| 1307 |
+
},
|
| 1308 |
+
{
|
| 1309 |
+
"type": "consulting",
|
| 1310 |
+
"url": "https://feross.org/support"
|
| 1311 |
+
}
|
| 1312 |
+
],
|
| 1313 |
+
"license": "MIT"
|
| 1314 |
+
},
|
| 1315 |
+
"node_modules/semver": {
|
| 1316 |
+
"version": "7.6.3",
|
| 1317 |
+
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
|
| 1318 |
+
"integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==",
|
| 1319 |
+
"dev": true,
|
| 1320 |
+
"license": "ISC",
|
| 1321 |
+
"optional": true,
|
| 1322 |
+
"bin": {
|
| 1323 |
+
"semver": "bin/semver.js"
|
| 1324 |
+
},
|
| 1325 |
+
"engines": {
|
| 1326 |
+
"node": ">=10"
|
| 1327 |
+
}
|
| 1328 |
+
},
|
| 1329 |
+
"node_modules/serialize-javascript": {
|
| 1330 |
+
"version": "6.0.2",
|
| 1331 |
+
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
|
| 1332 |
+
"integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
|
| 1333 |
+
"dev": true,
|
| 1334 |
+
"license": "BSD-3-Clause",
|
| 1335 |
+
"dependencies": {
|
| 1336 |
+
"randombytes": "^2.1.0"
|
| 1337 |
+
}
|
| 1338 |
+
},
|
| 1339 |
+
"node_modules/set-blocking": {
|
| 1340 |
+
"version": "2.0.0",
|
| 1341 |
+
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
| 1342 |
+
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
| 1343 |
+
"dev": true,
|
| 1344 |
+
"license": "ISC",
|
| 1345 |
+
"optional": true
|
| 1346 |
+
},
|
| 1347 |
+
"node_modules/signal-exit": {
|
| 1348 |
+
"version": "3.0.7",
|
| 1349 |
+
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
|
| 1350 |
+
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
|
| 1351 |
+
"dev": true,
|
| 1352 |
+
"license": "ISC",
|
| 1353 |
+
"optional": true
|
| 1354 |
+
},
|
| 1355 |
+
"node_modules/simple-concat": {
|
| 1356 |
+
"version": "1.0.1",
|
| 1357 |
+
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
|
| 1358 |
+
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
|
| 1359 |
+
"dev": true,
|
| 1360 |
+
"funding": [
|
| 1361 |
+
{
|
| 1362 |
+
"type": "github",
|
| 1363 |
+
"url": "https://github.com/sponsors/feross"
|
| 1364 |
+
},
|
| 1365 |
+
{
|
| 1366 |
+
"type": "patreon",
|
| 1367 |
+
"url": "https://www.patreon.com/feross"
|
| 1368 |
+
},
|
| 1369 |
+
{
|
| 1370 |
+
"type": "consulting",
|
| 1371 |
+
"url": "https://feross.org/support"
|
| 1372 |
+
}
|
| 1373 |
+
],
|
| 1374 |
+
"license": "MIT",
|
| 1375 |
+
"optional": true
|
| 1376 |
+
},
|
| 1377 |
+
"node_modules/simple-get": {
|
| 1378 |
+
"version": "3.1.1",
|
| 1379 |
+
"resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz",
|
| 1380 |
+
"integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==",
|
| 1381 |
+
"dev": true,
|
| 1382 |
+
"license": "MIT",
|
| 1383 |
+
"optional": true,
|
| 1384 |
+
"dependencies": {
|
| 1385 |
+
"decompress-response": "^4.2.0",
|
| 1386 |
+
"once": "^1.3.1",
|
| 1387 |
+
"simple-concat": "^1.0.0"
|
| 1388 |
+
}
|
| 1389 |
+
},
|
| 1390 |
+
"node_modules/smob": {
|
| 1391 |
+
"version": "1.5.0",
|
| 1392 |
+
"resolved": "https://registry.npmjs.org/smob/-/smob-1.5.0.tgz",
|
| 1393 |
+
"integrity": "sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==",
|
| 1394 |
+
"dev": true,
|
| 1395 |
+
"license": "MIT"
|
| 1396 |
+
},
|
| 1397 |
+
"node_modules/source-map": {
|
| 1398 |
+
"version": "0.6.1",
|
| 1399 |
+
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
| 1400 |
+
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
| 1401 |
+
"dev": true,
|
| 1402 |
+
"license": "BSD-3-Clause",
|
| 1403 |
+
"engines": {
|
| 1404 |
+
"node": ">=0.10.0"
|
| 1405 |
+
}
|
| 1406 |
+
},
|
| 1407 |
+
"node_modules/source-map-support": {
|
| 1408 |
+
"version": "0.5.21",
|
| 1409 |
+
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
|
| 1410 |
+
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
|
| 1411 |
+
"dev": true,
|
| 1412 |
+
"license": "MIT",
|
| 1413 |
+
"dependencies": {
|
| 1414 |
+
"buffer-from": "^1.0.0",
|
| 1415 |
+
"source-map": "^0.6.0"
|
| 1416 |
+
}
|
| 1417 |
+
},
|
| 1418 |
+
"node_modules/string_decoder": {
|
| 1419 |
+
"version": "1.3.0",
|
| 1420 |
+
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
| 1421 |
+
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
| 1422 |
+
"dev": true,
|
| 1423 |
+
"license": "MIT",
|
| 1424 |
+
"optional": true,
|
| 1425 |
+
"dependencies": {
|
| 1426 |
+
"safe-buffer": "~5.2.0"
|
| 1427 |
+
}
|
| 1428 |
+
},
|
| 1429 |
+
"node_modules/string-width": {
|
| 1430 |
+
"version": "4.2.3",
|
| 1431 |
+
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
| 1432 |
+
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
| 1433 |
+
"dev": true,
|
| 1434 |
+
"license": "MIT",
|
| 1435 |
+
"optional": true,
|
| 1436 |
+
"dependencies": {
|
| 1437 |
+
"emoji-regex": "^8.0.0",
|
| 1438 |
+
"is-fullwidth-code-point": "^3.0.0",
|
| 1439 |
+
"strip-ansi": "^6.0.1"
|
| 1440 |
+
},
|
| 1441 |
+
"engines": {
|
| 1442 |
+
"node": ">=8"
|
| 1443 |
+
}
|
| 1444 |
+
},
|
| 1445 |
+
"node_modules/strip-ansi": {
|
| 1446 |
+
"version": "6.0.1",
|
| 1447 |
+
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
| 1448 |
+
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
| 1449 |
+
"dev": true,
|
| 1450 |
+
"license": "MIT",
|
| 1451 |
+
"optional": true,
|
| 1452 |
+
"dependencies": {
|
| 1453 |
+
"ansi-regex": "^5.0.1"
|
| 1454 |
+
},
|
| 1455 |
+
"engines": {
|
| 1456 |
+
"node": ">=8"
|
| 1457 |
+
}
|
| 1458 |
+
},
|
| 1459 |
+
"node_modules/supports-preserve-symlinks-flag": {
|
| 1460 |
+
"version": "1.0.0",
|
| 1461 |
+
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
|
| 1462 |
+
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
|
| 1463 |
+
"dev": true,
|
| 1464 |
+
"license": "MIT",
|
| 1465 |
+
"engines": {
|
| 1466 |
+
"node": ">= 0.4"
|
| 1467 |
+
},
|
| 1468 |
+
"funding": {
|
| 1469 |
+
"url": "https://github.com/sponsors/ljharb"
|
| 1470 |
+
}
|
| 1471 |
+
},
|
| 1472 |
+
"node_modules/tar": {
|
| 1473 |
+
"version": "6.2.1",
|
| 1474 |
+
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
|
| 1475 |
+
"integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
|
| 1476 |
+
"dev": true,
|
| 1477 |
+
"license": "ISC",
|
| 1478 |
+
"optional": true,
|
| 1479 |
+
"dependencies": {
|
| 1480 |
+
"chownr": "^2.0.0",
|
| 1481 |
+
"fs-minipass": "^2.0.0",
|
| 1482 |
+
"minipass": "^5.0.0",
|
| 1483 |
+
"minizlib": "^2.1.1",
|
| 1484 |
+
"mkdirp": "^1.0.3",
|
| 1485 |
+
"yallist": "^4.0.0"
|
| 1486 |
+
},
|
| 1487 |
+
"engines": {
|
| 1488 |
+
"node": ">=10"
|
| 1489 |
+
}
|
| 1490 |
+
},
|
| 1491 |
+
"node_modules/terser": {
|
| 1492 |
+
"version": "5.34.1",
|
| 1493 |
+
"resolved": "https://registry.npmjs.org/terser/-/terser-5.34.1.tgz",
|
| 1494 |
+
"integrity": "sha512-FsJZ7iZLd/BXkz+4xrRTGJ26o/6VTjQytUk8b8OxkwcD2I+79VPJlz7qss1+zE7h8GNIScFqXcDyJ/KqBYZFVA==",
|
| 1495 |
+
"dev": true,
|
| 1496 |
+
"license": "BSD-2-Clause",
|
| 1497 |
+
"dependencies": {
|
| 1498 |
+
"@jridgewell/source-map": "^0.3.3",
|
| 1499 |
+
"acorn": "^8.8.2",
|
| 1500 |
+
"commander": "^2.20.0",
|
| 1501 |
+
"source-map-support": "~0.5.20"
|
| 1502 |
+
},
|
| 1503 |
+
"bin": {
|
| 1504 |
+
"terser": "bin/terser"
|
| 1505 |
+
},
|
| 1506 |
+
"engines": {
|
| 1507 |
+
"node": ">=10"
|
| 1508 |
+
}
|
| 1509 |
+
},
|
| 1510 |
+
"node_modules/tr46": {
|
| 1511 |
+
"version": "0.0.3",
|
| 1512 |
+
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
| 1513 |
+
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
| 1514 |
+
"dev": true,
|
| 1515 |
+
"license": "MIT",
|
| 1516 |
+
"optional": true
|
| 1517 |
+
},
|
| 1518 |
+
"node_modules/universalify": {
|
| 1519 |
+
"version": "2.0.1",
|
| 1520 |
+
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
| 1521 |
+
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
| 1522 |
+
"dev": true,
|
| 1523 |
+
"license": "MIT",
|
| 1524 |
+
"engines": {
|
| 1525 |
+
"node": ">= 10.0.0"
|
| 1526 |
+
}
|
| 1527 |
+
},
|
| 1528 |
+
"node_modules/util-deprecate": {
|
| 1529 |
+
"version": "1.0.2",
|
| 1530 |
+
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
| 1531 |
+
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
| 1532 |
+
"dev": true,
|
| 1533 |
+
"license": "MIT",
|
| 1534 |
+
"optional": true
|
| 1535 |
+
},
|
| 1536 |
+
"node_modules/webidl-conversions": {
|
| 1537 |
+
"version": "3.0.1",
|
| 1538 |
+
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
| 1539 |
+
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
| 1540 |
+
"dev": true,
|
| 1541 |
+
"license": "BSD-2-Clause",
|
| 1542 |
+
"optional": true
|
| 1543 |
+
},
|
| 1544 |
+
"node_modules/whatwg-url": {
|
| 1545 |
+
"version": "5.0.0",
|
| 1546 |
+
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
| 1547 |
+
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
| 1548 |
+
"dev": true,
|
| 1549 |
+
"license": "MIT",
|
| 1550 |
+
"optional": true,
|
| 1551 |
+
"dependencies": {
|
| 1552 |
+
"tr46": "~0.0.3",
|
| 1553 |
+
"webidl-conversions": "^3.0.0"
|
| 1554 |
+
}
|
| 1555 |
+
},
|
| 1556 |
+
"node_modules/wide-align": {
|
| 1557 |
+
"version": "1.1.5",
|
| 1558 |
+
"resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
|
| 1559 |
+
"integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
|
| 1560 |
+
"dev": true,
|
| 1561 |
+
"license": "ISC",
|
| 1562 |
+
"optional": true,
|
| 1563 |
+
"dependencies": {
|
| 1564 |
+
"string-width": "^1.0.2 || 2 || 3 || 4"
|
| 1565 |
+
}
|
| 1566 |
+
},
|
| 1567 |
+
"node_modules/wrappy": {
|
| 1568 |
+
"version": "1.0.2",
|
| 1569 |
+
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
| 1570 |
+
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
| 1571 |
+
"dev": true,
|
| 1572 |
+
"license": "ISC",
|
| 1573 |
+
"optional": true
|
| 1574 |
+
},
|
| 1575 |
+
"node_modules/yallist": {
|
| 1576 |
+
"version": "4.0.0",
|
| 1577 |
+
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
| 1578 |
+
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
| 1579 |
+
"dev": true,
|
| 1580 |
+
"license": "ISC",
|
| 1581 |
+
"optional": true
|
| 1582 |
+
}
|
| 1583 |
+
}
|
| 1584 |
+
}
|
packages/foliate-js/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "foliate-js",
|
| 3 |
+
"version": "0.0.0",
|
| 4 |
+
"description": "Render e-books in the browser",
|
| 5 |
+
"repository": {
|
| 6 |
+
"type": "git",
|
| 7 |
+
"url": "git+https://github.com/johnfactotum/foliate-js.git"
|
| 8 |
+
},
|
| 9 |
+
"bugs": {
|
| 10 |
+
"url": "https://github.com/johnfactotum/foliate-js/issues"
|
| 11 |
+
},
|
| 12 |
+
"homepage": "https://github.com/johnfactotum/foliate-js#readme",
|
| 13 |
+
"author": "John Factotum",
|
| 14 |
+
"license": "MIT",
|
| 15 |
+
"type": "module",
|
| 16 |
+
"exports": {
|
| 17 |
+
"./*.js": "./*.js"
|
| 18 |
+
},
|
| 19 |
+
"devDependencies": {
|
| 20 |
+
"@eslint/js": "^9.9.1",
|
| 21 |
+
"@rollup/plugin-node-resolve": "^15.2.3",
|
| 22 |
+
"@rollup/plugin-terser": "^0.4.4",
|
| 23 |
+
"@zip.js/zip.js": "^2.7.52",
|
| 24 |
+
"fflate": "^0.8.2",
|
| 25 |
+
"fs-extra": "^11.2.0",
|
| 26 |
+
"globals": "^15.9.0",
|
| 27 |
+
"pdfjs-dist": "^5.4.530",
|
| 28 |
+
"rollup": "^4.22.4"
|
| 29 |
+
},
|
| 30 |
+
"scripts": {
|
| 31 |
+
"build": "npx rollup -c"
|
| 32 |
+
},
|
| 33 |
+
"keywords": [
|
| 34 |
+
"ebook",
|
| 35 |
+
"reader",
|
| 36 |
+
"epub",
|
| 37 |
+
"cfi",
|
| 38 |
+
"mobi",
|
| 39 |
+
"azw",
|
| 40 |
+
"azw3",
|
| 41 |
+
"fb2",
|
| 42 |
+
"cbz",
|
| 43 |
+
"dictd",
|
| 44 |
+
"stardict",
|
| 45 |
+
"opds"
|
| 46 |
+
],
|
| 47 |
+
"dependencies": {
|
| 48 |
+
"construct-style-sheets-polyfill": "^3.1.0"
|
| 49 |
+
}
|
| 50 |
+
}
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
|
| 2 |
+
|
| 3 |
+
const debounce = (f, wait, immediate) => {
|
| 4 |
+
let timeout
|
| 5 |
+
return (...args) => {
|
| 6 |
+
const later = () => {
|
| 7 |
+
timeout = null
|
| 8 |
+
if (!immediate) f(...args)
|
| 9 |
+
}
|
| 10 |
+
const callNow = immediate && !timeout
|
| 11 |
+
if (timeout) clearTimeout(timeout)
|
| 12 |
+
timeout = setTimeout(later, wait)
|
| 13 |
+
if (callNow) f(...args)
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const lerp = (min, max, x) => x * (max - min) + min
|
| 18 |
+
const easeOutQuad = x => 1 - (1 - x) * (1 - x)
|
| 19 |
+
const animate = (a, b, duration, ease, render) => new Promise(resolve => {
|
| 20 |
+
let start
|
| 21 |
+
const step = now => {
|
| 22 |
+
if (document.hidden) {
|
| 23 |
+
render(lerp(a, b, 1))
|
| 24 |
+
return resolve()
|
| 25 |
+
}
|
| 26 |
+
start ??= now
|
| 27 |
+
const fraction = Math.min(1, (now - start) / duration)
|
| 28 |
+
render(lerp(a, b, ease(fraction)))
|
| 29 |
+
if (fraction < 1) requestAnimationFrame(step)
|
| 30 |
+
else resolve()
|
| 31 |
+
}
|
| 32 |
+
if (document.hidden) {
|
| 33 |
+
render(lerp(a, b, 1))
|
| 34 |
+
return resolve()
|
| 35 |
+
}
|
| 36 |
+
requestAnimationFrame(step)
|
| 37 |
+
})
|
| 38 |
+
|
| 39 |
+
// collapsed range doesn't return client rects sometimes (or always?)
|
| 40 |
+
// try make get a non-collapsed range or element
|
| 41 |
+
const uncollapse = range => {
|
| 42 |
+
if (!range?.collapsed) return range
|
| 43 |
+
const { endOffset, endContainer } = range
|
| 44 |
+
if (endContainer.nodeType === 1) {
|
| 45 |
+
const node = endContainer.childNodes[endOffset]
|
| 46 |
+
if (node?.nodeType === 1) return node
|
| 47 |
+
return endContainer
|
| 48 |
+
}
|
| 49 |
+
if (endOffset + 1 < endContainer.length) range.setEnd(endContainer, endOffset + 1)
|
| 50 |
+
else if (endOffset > 1) range.setStart(endContainer, endOffset - 1)
|
| 51 |
+
else return endContainer.parentNode
|
| 52 |
+
return range
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
const makeRange = (doc, node, start, end = start) => {
|
| 56 |
+
const range = doc.createRange()
|
| 57 |
+
range.setStart(node, start)
|
| 58 |
+
range.setEnd(node, end)
|
| 59 |
+
return range
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// use binary search to find an offset value in a text node
|
| 63 |
+
const bisectNode = (doc, node, cb, start = 0, end = node.nodeValue.length) => {
|
| 64 |
+
if (end - start === 1) {
|
| 65 |
+
const result = cb(makeRange(doc, node, start), makeRange(doc, node, end))
|
| 66 |
+
return result < 0 ? start : end
|
| 67 |
+
}
|
| 68 |
+
const mid = Math.floor(start + (end - start) / 2)
|
| 69 |
+
const result = cb(makeRange(doc, node, start, mid), makeRange(doc, node, mid, end))
|
| 70 |
+
return result < 0 ? bisectNode(doc, node, cb, start, mid)
|
| 71 |
+
: result > 0 ? bisectNode(doc, node, cb, mid, end) : mid
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
const { SHOW_ELEMENT, SHOW_TEXT, SHOW_CDATA_SECTION,
|
| 75 |
+
FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP } = NodeFilter
|
| 76 |
+
|
| 77 |
+
const filter = SHOW_ELEMENT | SHOW_TEXT | SHOW_CDATA_SECTION
|
| 78 |
+
|
| 79 |
+
// needed cause there seems to be a bug in `getBoundingClientRect()` in Firefox
|
| 80 |
+
// where it fails to include rects that have zero width and non-zero height
|
| 81 |
+
// (CSSOM spec says "rectangles [...] of which the height or width is not zero")
|
| 82 |
+
// which makes the visible range include an extra space at column boundaries
|
| 83 |
+
const getBoundingClientRect = target => {
|
| 84 |
+
let top = Infinity, right = -Infinity, left = Infinity, bottom = -Infinity
|
| 85 |
+
for (const rect of target.getClientRects()) {
|
| 86 |
+
left = Math.min(left, rect.left)
|
| 87 |
+
top = Math.min(top, rect.top)
|
| 88 |
+
right = Math.max(right, rect.right)
|
| 89 |
+
bottom = Math.max(bottom, rect.bottom)
|
| 90 |
+
}
|
| 91 |
+
return new DOMRect(left, top, right - left, bottom - top)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
const getVisibleRange = (doc, start, end, mapRect) => {
|
| 95 |
+
// first get all visible nodes
|
| 96 |
+
const acceptNode = node => {
|
| 97 |
+
const name = node.localName?.toLowerCase()
|
| 98 |
+
// ignore all scripts, styles, and their children
|
| 99 |
+
if (name === 'script' || name === 'style') return FILTER_REJECT
|
| 100 |
+
if (node.nodeType === 1) {
|
| 101 |
+
const { left, right } = mapRect(node.getBoundingClientRect())
|
| 102 |
+
// no need to check child nodes if it's completely out of view
|
| 103 |
+
if (right < start || left > end) return FILTER_REJECT
|
| 104 |
+
// elements must be completely in view to be considered visible
|
| 105 |
+
// because you can't specify offsets for elements
|
| 106 |
+
if (left >= start && right <= end) return FILTER_ACCEPT
|
| 107 |
+
// TODO: it should probably allow elements that do not contain text
|
| 108 |
+
// because they can exceed the whole viewport in both directions
|
| 109 |
+
// especially in scrolled mode
|
| 110 |
+
} else {
|
| 111 |
+
// ignore empty text nodes
|
| 112 |
+
if (!node.nodeValue?.trim()) return FILTER_SKIP
|
| 113 |
+
// create range to get rect
|
| 114 |
+
const range = doc.createRange()
|
| 115 |
+
range.selectNodeContents(node)
|
| 116 |
+
const { left, right } = mapRect(range.getBoundingClientRect())
|
| 117 |
+
// it's visible if any part of it is in view
|
| 118 |
+
if (right >= start && left <= end) return FILTER_ACCEPT
|
| 119 |
+
}
|
| 120 |
+
return FILTER_SKIP
|
| 121 |
+
}
|
| 122 |
+
const walker = doc.createTreeWalker(doc.body, filter, { acceptNode })
|
| 123 |
+
const nodes = []
|
| 124 |
+
for (let node = walker.nextNode(); node; node = walker.nextNode())
|
| 125 |
+
nodes.push(node)
|
| 126 |
+
|
| 127 |
+
// we're only interested in the first and last visible nodes
|
| 128 |
+
const from = nodes[0] ?? doc.body
|
| 129 |
+
const to = nodes[nodes.length - 1] ?? from
|
| 130 |
+
|
| 131 |
+
// find the offset at which visibility changes
|
| 132 |
+
const startOffset = from.nodeType === 1 ? 0
|
| 133 |
+
: bisectNode(doc, from, (a, b) => {
|
| 134 |
+
const p = mapRect(getBoundingClientRect(a))
|
| 135 |
+
const q = mapRect(getBoundingClientRect(b))
|
| 136 |
+
if (p.right < start && q.left > start) return 0
|
| 137 |
+
return q.left > start ? -1 : 1
|
| 138 |
+
})
|
| 139 |
+
const endOffset = to.nodeType === 1 ? 0
|
| 140 |
+
: bisectNode(doc, to, (a, b) => {
|
| 141 |
+
const p = mapRect(getBoundingClientRect(a))
|
| 142 |
+
const q = mapRect(getBoundingClientRect(b))
|
| 143 |
+
if (p.right < end && q.left > end) return 0
|
| 144 |
+
return q.left > end ? -1 : 1
|
| 145 |
+
})
|
| 146 |
+
|
| 147 |
+
const range = doc.createRange()
|
| 148 |
+
range.setStart(from, startOffset)
|
| 149 |
+
range.setEnd(to, endOffset)
|
| 150 |
+
return range
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
const selectionIsBackward = sel => {
|
| 154 |
+
const range = document.createRange()
|
| 155 |
+
range.setStart(sel.anchorNode, sel.anchorOffset)
|
| 156 |
+
range.setEnd(sel.focusNode, sel.focusOffset)
|
| 157 |
+
return range.collapsed
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
const setSelectionTo = (target, collapse) => {
|
| 161 |
+
let range
|
| 162 |
+
if (target.startContainer) range = target.cloneRange()
|
| 163 |
+
else if (target.nodeType) {
|
| 164 |
+
range = document.createRange()
|
| 165 |
+
range.selectNode(target)
|
| 166 |
+
}
|
| 167 |
+
if (range) {
|
| 168 |
+
const sel = range.startContainer.ownerDocument?.defaultView.getSelection()
|
| 169 |
+
if (sel) {
|
| 170 |
+
sel.removeAllRanges()
|
| 171 |
+
if (collapse === -1) range.collapse(true)
|
| 172 |
+
else if (collapse === 1) range.collapse()
|
| 173 |
+
sel.addRange(range)
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
const getDirection = doc => {
|
| 179 |
+
const { defaultView } = doc
|
| 180 |
+
const { writingMode, direction } = defaultView.getComputedStyle(doc.body)
|
| 181 |
+
const vertical = writingMode === 'vertical-rl'
|
| 182 |
+
|| writingMode === 'vertical-lr'
|
| 183 |
+
const rtl = doc.body.dir === 'rtl'
|
| 184 |
+
|| direction === 'rtl'
|
| 185 |
+
|| doc.documentElement.dir === 'rtl'
|
| 186 |
+
return { vertical, rtl }
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
const getBackground = doc => {
|
| 190 |
+
const bodyStyle = doc.defaultView.getComputedStyle(doc.body)
|
| 191 |
+
return bodyStyle.backgroundColor === 'rgba(0, 0, 0, 0)'
|
| 192 |
+
&& bodyStyle.backgroundImage === 'none'
|
| 193 |
+
? doc.defaultView.getComputedStyle(doc.documentElement).background
|
| 194 |
+
: bodyStyle.background
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
const makeMarginals = (length, part) => Array.from({ length }, () => {
|
| 198 |
+
const div = document.createElement('div')
|
| 199 |
+
const child = document.createElement('div')
|
| 200 |
+
div.append(child)
|
| 201 |
+
child.setAttribute('part', part)
|
| 202 |
+
return div
|
| 203 |
+
})
|
| 204 |
+
|
| 205 |
+
const setStyles = (el, styles) => {
|
| 206 |
+
const { style } = el
|
| 207 |
+
for (const [k, v] of Object.entries(styles)) style.setProperty(k, v)
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
const setStylesImportant = (el, styles) => {
|
| 211 |
+
const { style } = el
|
| 212 |
+
for (const [k, v] of Object.entries(styles)) style.setProperty(k, v, 'important')
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
class View {
|
| 216 |
+
#observer = new ResizeObserver(() => this.expand())
|
| 217 |
+
#element = document.createElement('div')
|
| 218 |
+
#iframe = document.createElement('iframe')
|
| 219 |
+
#contentRange = document.createRange()
|
| 220 |
+
#overlayer
|
| 221 |
+
#vertical = false
|
| 222 |
+
#rtl = false
|
| 223 |
+
#column = true
|
| 224 |
+
#size
|
| 225 |
+
#layout = {}
|
| 226 |
+
constructor({ container, onExpand }) {
|
| 227 |
+
this.container = container
|
| 228 |
+
this.onExpand = onExpand
|
| 229 |
+
this.#iframe.setAttribute('part', 'filter')
|
| 230 |
+
this.#element.append(this.#iframe)
|
| 231 |
+
Object.assign(this.#element.style, {
|
| 232 |
+
boxSizing: 'content-box',
|
| 233 |
+
position: 'relative',
|
| 234 |
+
overflow: 'hidden',
|
| 235 |
+
flex: '0 0 auto',
|
| 236 |
+
width: '100%', height: '100%',
|
| 237 |
+
display: 'flex',
|
| 238 |
+
justifyContent: 'center',
|
| 239 |
+
alignItems: 'center',
|
| 240 |
+
})
|
| 241 |
+
Object.assign(this.#iframe.style, {
|
| 242 |
+
overflow: 'hidden',
|
| 243 |
+
border: '0',
|
| 244 |
+
display: 'none',
|
| 245 |
+
width: '100%', height: '100%',
|
| 246 |
+
})
|
| 247 |
+
// `allow-scripts` is needed for events because of WebKit bug
|
| 248 |
+
// https://bugs.webkit.org/show_bug.cgi?id=218086
|
| 249 |
+
this.#iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
|
| 250 |
+
this.#iframe.setAttribute('scrolling', 'no')
|
| 251 |
+
}
|
| 252 |
+
get element() {
|
| 253 |
+
return this.#element
|
| 254 |
+
}
|
| 255 |
+
get document() {
|
| 256 |
+
return this.#iframe.contentDocument
|
| 257 |
+
}
|
| 258 |
+
async load(src, data, afterLoad, beforeRender) {
|
| 259 |
+
if (typeof src !== 'string') throw new Error(`${src} is not string`)
|
| 260 |
+
return new Promise(resolve => {
|
| 261 |
+
this.#iframe.addEventListener('load', () => {
|
| 262 |
+
const doc = this.document
|
| 263 |
+
afterLoad?.(doc)
|
| 264 |
+
|
| 265 |
+
this.#iframe.setAttribute('aria-label', doc.title)
|
| 266 |
+
// it needs to be visible for Firefox to get computed style
|
| 267 |
+
this.#iframe.style.display = 'block'
|
| 268 |
+
const { vertical, rtl } = getDirection(doc)
|
| 269 |
+
this.docBackground = getBackground(doc)
|
| 270 |
+
doc.body.style.background = 'none'
|
| 271 |
+
const background = this.docBackground
|
| 272 |
+
this.#iframe.style.display = 'none'
|
| 273 |
+
|
| 274 |
+
this.#vertical = vertical
|
| 275 |
+
this.#rtl = rtl
|
| 276 |
+
|
| 277 |
+
this.#contentRange.selectNodeContents(doc.body)
|
| 278 |
+
const layout = beforeRender?.({ vertical, rtl, background })
|
| 279 |
+
this.#iframe.style.display = 'block'
|
| 280 |
+
this.render(layout)
|
| 281 |
+
this.#observer.observe(doc.body)
|
| 282 |
+
|
| 283 |
+
// the resize observer above doesn't work in Firefox
|
| 284 |
+
// (see https://bugzilla.mozilla.org/show_bug.cgi?id=1832939)
|
| 285 |
+
// until the bug is fixed we can at least account for font load
|
| 286 |
+
doc.fonts.ready.then(() => this.expand())
|
| 287 |
+
|
| 288 |
+
resolve()
|
| 289 |
+
}, { once: true })
|
| 290 |
+
if (data) {
|
| 291 |
+
this.#iframe.srcdoc = data
|
| 292 |
+
} else {
|
| 293 |
+
this.#iframe.src = src
|
| 294 |
+
}
|
| 295 |
+
})
|
| 296 |
+
}
|
| 297 |
+
render(layout) {
|
| 298 |
+
if (!layout || !this.document) return
|
| 299 |
+
this.#column = layout.flow !== 'scrolled'
|
| 300 |
+
this.#layout = layout
|
| 301 |
+
if (this.#column) this.columnize(layout)
|
| 302 |
+
else this.scrolled(layout)
|
| 303 |
+
}
|
| 304 |
+
scrolled({ marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }) {
|
| 305 |
+
const vertical = this.#vertical
|
| 306 |
+
const doc = this.document
|
| 307 |
+
setStylesImportant(doc.documentElement, {
|
| 308 |
+
'box-sizing': 'border-box',
|
| 309 |
+
'padding': vertical
|
| 310 |
+
? `${marginTop * 1.5}px ${marginRight}px ${marginBottom * 1.5}px ${marginLeft}px`
|
| 311 |
+
: `${marginTop}px ${gap / 2 + marginRight / 2}px ${marginBottom}px ${gap / 2 + marginLeft / 2}px`,
|
| 312 |
+
'column-width': 'auto',
|
| 313 |
+
'height': 'auto',
|
| 314 |
+
'width': 'auto',
|
| 315 |
+
})
|
| 316 |
+
setStyles(doc.documentElement, {
|
| 317 |
+
'--page-margin-top': `${vertical ? marginTop * 1.5 : marginTop}px`,
|
| 318 |
+
'--page-margin-right': `${vertical ? marginRight : marginRight + gap /2}px`,
|
| 319 |
+
'--page-margin-bottom': `${vertical ? marginBottom * 1.5 : marginBottom}px`,
|
| 320 |
+
'--page-margin-left': `${vertical ? marginLeft : marginLeft + gap / 2}px`,
|
| 321 |
+
'--full-width': `${Math.trunc(window.innerWidth)}`,
|
| 322 |
+
'--full-height': `${Math.trunc(window.innerHeight)}`,
|
| 323 |
+
'--available-width': `${Math.trunc(Math.min(window.innerWidth, columnWidth) - marginLeft - marginRight - gap - 60)}`,
|
| 324 |
+
'--available-height': `${Math.trunc(window.innerHeight - marginTop - marginBottom)}`,
|
| 325 |
+
})
|
| 326 |
+
setStylesImportant(doc.body, {
|
| 327 |
+
[vertical ? 'max-height' : 'max-width']: `${columnWidth}px`,
|
| 328 |
+
'margin': 'auto',
|
| 329 |
+
})
|
| 330 |
+
this.setImageSize()
|
| 331 |
+
this.expand()
|
| 332 |
+
}
|
| 333 |
+
columnize({ width, height, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }) {
|
| 334 |
+
const vertical = this.#vertical
|
| 335 |
+
this.#size = vertical ? height : width
|
| 336 |
+
|
| 337 |
+
const doc = this.document
|
| 338 |
+
setStylesImportant(doc.documentElement, {
|
| 339 |
+
'box-sizing': 'border-box',
|
| 340 |
+
'column-width': `${Math.trunc(columnWidth)}px`,
|
| 341 |
+
'column-gap': vertical ? `${(marginTop + marginBottom) * 1.5}px` : `${gap + marginRight / 2 + marginLeft / 2}px`,
|
| 342 |
+
'column-fill': 'auto',
|
| 343 |
+
...(vertical
|
| 344 |
+
? { 'width': `${width}px` }
|
| 345 |
+
: { 'height': `${height}px` }),
|
| 346 |
+
'padding': vertical
|
| 347 |
+
? `${marginTop * 1.5}px ${marginRight}px ${marginBottom * 1.5}px ${marginLeft}px`
|
| 348 |
+
: `${marginTop}px ${gap / 2 + marginRight / 2}px ${marginBottom}px ${gap / 2 + marginLeft / 2}px`,
|
| 349 |
+
'overflow': 'hidden',
|
| 350 |
+
// force wrap long words
|
| 351 |
+
'overflow-wrap': 'break-word',
|
| 352 |
+
// reset some potentially problematic props
|
| 353 |
+
'position': 'static', 'border': '0', 'margin': '0',
|
| 354 |
+
'max-height': 'none', 'max-width': 'none',
|
| 355 |
+
'min-height': 'none', 'min-width': 'none',
|
| 356 |
+
// fix glyph clipping in WebKit
|
| 357 |
+
'-webkit-line-box-contain': 'block glyphs replaced',
|
| 358 |
+
})
|
| 359 |
+
setStyles(doc.documentElement, {
|
| 360 |
+
'--page-margin-top': `${vertical ? marginTop * 1.5 : marginTop}px`,
|
| 361 |
+
'--page-margin-right': `${vertical ? marginRight : marginRight / 2 + gap /2}px`,
|
| 362 |
+
'--page-margin-bottom': `${vertical ? marginBottom * 1.5 : marginBottom}px`,
|
| 363 |
+
'--page-margin-left': `${vertical ? marginLeft : marginLeft / 2 + gap / 2}px`,
|
| 364 |
+
'--full-width': `${Math.trunc(window.innerWidth)}`,
|
| 365 |
+
'--full-height': `${Math.trunc(window.innerHeight)}`,
|
| 366 |
+
'--available-width': `${Math.trunc(columnWidth - marginLeft - marginRight - gap)}`,
|
| 367 |
+
'--available-height': `${Math.trunc(height - marginTop - marginBottom)}`,
|
| 368 |
+
})
|
| 369 |
+
setStylesImportant(doc.body, {
|
| 370 |
+
'max-height': 'none',
|
| 371 |
+
'max-width': 'none',
|
| 372 |
+
'margin': '0',
|
| 373 |
+
})
|
| 374 |
+
this.setImageSize()
|
| 375 |
+
this.expand()
|
| 376 |
+
}
|
| 377 |
+
setImageSize() {
|
| 378 |
+
const { width, height, marginTop, marginRight, marginBottom, marginLeft } = this.#layout
|
| 379 |
+
const vertical = this.#vertical
|
| 380 |
+
const doc = this.document
|
| 381 |
+
for (const el of doc.body.querySelectorAll('img, svg, video')) {
|
| 382 |
+
// preserve max size if they are already set
|
| 383 |
+
const { maxHeight, maxWidth } = doc.defaultView.getComputedStyle(el)
|
| 384 |
+
setStylesImportant(el, {
|
| 385 |
+
'max-height': vertical
|
| 386 |
+
? (maxHeight !== 'none' && maxHeight !== '0px' ? maxHeight : '100%')
|
| 387 |
+
: `${height - marginTop - marginBottom }px`,
|
| 388 |
+
'max-width': vertical
|
| 389 |
+
? `${width - marginLeft - marginRight }px`
|
| 390 |
+
: (maxWidth !== 'none' && maxWidth !== '0px' ? maxWidth : '100%'),
|
| 391 |
+
'object-fit': 'contain',
|
| 392 |
+
'page-break-inside': 'avoid',
|
| 393 |
+
'break-inside': 'avoid',
|
| 394 |
+
'box-sizing': 'border-box',
|
| 395 |
+
})
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
get #zoom() {
|
| 399 |
+
// Safari does not zoom the client rects, while Chrome, Edge and Firefox does
|
| 400 |
+
if (/^((?!chrome|android).)*AppleWebKit/i.test(navigator.userAgent) && !window.chrome) {
|
| 401 |
+
return window.getComputedStyle(this.document.body).zoom || 1.0
|
| 402 |
+
}
|
| 403 |
+
return 1.0
|
| 404 |
+
}
|
| 405 |
+
expand() {
|
| 406 |
+
if (!this.document) return
|
| 407 |
+
const { documentElement } = this.document
|
| 408 |
+
if (this.#column) {
|
| 409 |
+
const side = this.#vertical ? 'height' : 'width'
|
| 410 |
+
const otherSide = this.#vertical ? 'width' : 'height'
|
| 411 |
+
const contentRect = this.#contentRange.getBoundingClientRect()
|
| 412 |
+
const rootRect = documentElement.getBoundingClientRect()
|
| 413 |
+
// offset caused by column break at the start of the page
|
| 414 |
+
// which seem to be supported only by WebKit and only for horizontal writing
|
| 415 |
+
const contentStart = this.#vertical ? 0
|
| 416 |
+
: this.#rtl ? rootRect.right - contentRect.right : contentRect.left - rootRect.left
|
| 417 |
+
const contentSize = (contentStart + contentRect[side]) * this.#zoom
|
| 418 |
+
const pageCount = Math.ceil(contentSize / this.#size)
|
| 419 |
+
const expandedSize = pageCount * this.#size
|
| 420 |
+
this.#element.style.padding = '0'
|
| 421 |
+
this.#iframe.style[side] = `${expandedSize}px`
|
| 422 |
+
this.#element.style[side] = `${expandedSize + this.#size * 2}px`
|
| 423 |
+
this.#iframe.style[otherSide] = '100%'
|
| 424 |
+
this.#element.style[otherSide] = '100%'
|
| 425 |
+
documentElement.style[side] = `${this.#size}px`
|
| 426 |
+
if (this.#overlayer) {
|
| 427 |
+
this.#overlayer.element.style.margin = '0'
|
| 428 |
+
this.#overlayer.element.style.left = this.#vertical ? '0' : `${this.#size}px`
|
| 429 |
+
this.#overlayer.element.style.top = this.#vertical ? `${this.#size}px` : '0'
|
| 430 |
+
this.#overlayer.element.style[side] = `${expandedSize}px`
|
| 431 |
+
this.#overlayer.redraw()
|
| 432 |
+
}
|
| 433 |
+
} else {
|
| 434 |
+
const side = this.#vertical ? 'width' : 'height'
|
| 435 |
+
const otherSide = this.#vertical ? 'height' : 'width'
|
| 436 |
+
const contentSize = documentElement.getBoundingClientRect()[side]
|
| 437 |
+
const expandedSize = contentSize
|
| 438 |
+
this.#element.style.padding = '0'
|
| 439 |
+
this.#iframe.style[side] = `${expandedSize}px`
|
| 440 |
+
this.#element.style[side] = `${expandedSize}px`
|
| 441 |
+
this.#iframe.style[otherSide] = '100%'
|
| 442 |
+
this.#element.style[otherSide] = '100%'
|
| 443 |
+
if (this.#overlayer) {
|
| 444 |
+
this.#overlayer.element.style.margin = '0'
|
| 445 |
+
this.#overlayer.element.style.left = '0'
|
| 446 |
+
this.#overlayer.element.style.top = '0'
|
| 447 |
+
this.#overlayer.element.style[side] = `${expandedSize}px`
|
| 448 |
+
this.#overlayer.redraw()
|
| 449 |
+
}
|
| 450 |
+
}
|
| 451 |
+
this.onExpand()
|
| 452 |
+
}
|
| 453 |
+
set overlayer(overlayer) {
|
| 454 |
+
this.#overlayer = overlayer
|
| 455 |
+
this.#element.append(overlayer.element)
|
| 456 |
+
}
|
| 457 |
+
get overlayer() {
|
| 458 |
+
return this.#overlayer
|
| 459 |
+
}
|
| 460 |
+
#loupeEl = null
|
| 461 |
+
#loupeScaler = null
|
| 462 |
+
#loupeCursor = null
|
| 463 |
+
// Show a magnifier loupe inside the iframe document.
|
| 464 |
+
// winX/winY are in main-window (screen) coordinates.
|
| 465 |
+
showLoupe(winX, winY, { isVertical, color, radius }) {
|
| 466 |
+
const doc = this.document
|
| 467 |
+
if (!doc) return
|
| 468 |
+
|
| 469 |
+
const frameRect = this.#iframe.getBoundingClientRect()
|
| 470 |
+
// Cursor in iframe-viewport coordinates.
|
| 471 |
+
const vpX = winX - frameRect.left
|
| 472 |
+
const vpY = winY - frameRect.top
|
| 473 |
+
|
| 474 |
+
// Cursor in document coordinates (accounts for scroll).
|
| 475 |
+
const scrollX = doc.scrollingElement?.scrollLeft ?? 0
|
| 476 |
+
const scrollY = doc.scrollingElement?.scrollTop ?? 0
|
| 477 |
+
const docX = vpX + scrollX
|
| 478 |
+
const docY = vpY + scrollY
|
| 479 |
+
|
| 480 |
+
const MAGNIFICATION = 1.2
|
| 481 |
+
const diameter = radius * 2
|
| 482 |
+
const MARGIN = 8
|
| 483 |
+
|
| 484 |
+
// Position loupe above the cursor (or to the left for vertical text).
|
| 485 |
+
const loupeOffset = radius + 16
|
| 486 |
+
let loupeLeft = isVertical ? vpX - loupeOffset - diameter : vpX - radius
|
| 487 |
+
let loupeTop = isVertical ? vpY - radius : vpY - loupeOffset - diameter
|
| 488 |
+
loupeLeft = Math.max(MARGIN, Math.min(loupeLeft, frameRect.width - diameter - MARGIN))
|
| 489 |
+
loupeTop = Math.max(MARGIN, Math.min(loupeTop, frameRect.height - diameter - MARGIN))
|
| 490 |
+
|
| 491 |
+
// CSS-transform math: map document point (docX, docY) to loupe centre (radius, radius).
|
| 492 |
+
// visual_pos = offset + coord × MAGNIFICATION = radius
|
| 493 |
+
// ⟹ offset = radius − coord × MAGNIFICATION
|
| 494 |
+
const offsetX = radius - docX * MAGNIFICATION
|
| 495 |
+
const offsetY = radius - docY * MAGNIFICATION
|
| 496 |
+
|
| 497 |
+
// Build loupe DOM structure once; subsequent calls only update positions.
|
| 498 |
+
if (!this.#loupeEl || !this.#loupeEl.isConnected) {
|
| 499 |
+
this.#loupeEl = doc.createElement('div')
|
| 500 |
+
|
| 501 |
+
// Clone the live body once — inside the iframe the epub's CSS
|
| 502 |
+
// variables, @font-face fonts, and styles apply automatically.
|
| 503 |
+
const bodyClone = doc.body.cloneNode(true)
|
| 504 |
+
|
| 505 |
+
// Wrap the clone in a div that replicates documentElement's inline
|
| 506 |
+
// styles (column-width, column-gap, padding, height, etc.) so text
|
| 507 |
+
// flows with the same column layout as the original document.
|
| 508 |
+
const htmlWrapper = doc.createElement('div')
|
| 509 |
+
htmlWrapper.style.cssText = doc.documentElement.style.cssText
|
| 510 |
+
// expand() constrains documentElement's page-axis dimension to one
|
| 511 |
+
// page size (width for horizontal, height for vertical). Override
|
| 512 |
+
// with the full scroll dimension so all columns are rendered.
|
| 513 |
+
if (this.#vertical)
|
| 514 |
+
htmlWrapper.style.height = `${doc.documentElement.scrollHeight}px`
|
| 515 |
+
else
|
| 516 |
+
htmlWrapper.style.width = `${doc.documentElement.scrollWidth}px`
|
| 517 |
+
htmlWrapper.appendChild(bodyClone)
|
| 518 |
+
|
| 519 |
+
this.#loupeScaler = doc.createElement('div')
|
| 520 |
+
this.#loupeScaler.appendChild(htmlWrapper)
|
| 521 |
+
|
| 522 |
+
const cursorLen = Math.round(diameter * 0.24)
|
| 523 |
+
this.#loupeCursor = doc.createElement('div')
|
| 524 |
+
this.#loupeCursor.style.cssText = isVertical
|
| 525 |
+
? `position:absolute;left:calc(50% - ${cursorLen / 2}px);top:50%;`
|
| 526 |
+
+ `margin-top:-1px;width:${cursorLen}px;height:2px;background:${color};pointer-events:none;z-index:1;box-sizing:border-box;`
|
| 527 |
+
: `position:absolute;left:50%;top:calc(50% - ${cursorLen / 2}px);`
|
| 528 |
+
+ `margin-left:-1px;width:2px;height:${cursorLen}px;background:${color};pointer-events:none;z-index:1;box-sizing:border-box;`
|
| 529 |
+
|
| 530 |
+
this.#loupeEl.appendChild(this.#loupeScaler)
|
| 531 |
+
this.#loupeEl.appendChild(this.#loupeCursor)
|
| 532 |
+
doc.documentElement.appendChild(this.#loupeEl)
|
| 533 |
+
|
| 534 |
+
// Static loupe shell styles (set once).
|
| 535 |
+
this.#loupeEl.style.cssText = `
|
| 536 |
+
position: absolute;
|
| 537 |
+
width: ${diameter}px;
|
| 538 |
+
height: ${diameter}px;
|
| 539 |
+
border-radius: 50%;
|
| 540 |
+
overflow: hidden;
|
| 541 |
+
border: 2.5px solid ${color};
|
| 542 |
+
box-shadow: 0 6px 24px rgba(0,0,0,0.28);
|
| 543 |
+
background-color: var(--theme-bg-color);
|
| 544 |
+
z-index: 9999;
|
| 545 |
+
pointer-events: none;
|
| 546 |
+
user-select: none;
|
| 547 |
+
box-sizing: border-box;
|
| 548 |
+
`
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
// Update only the dynamic position values (fast path on every move).
|
| 552 |
+
this.#loupeScaler.style.cssText = `
|
| 553 |
+
position: absolute;
|
| 554 |
+
left: ${offsetX}px;
|
| 555 |
+
top: ${offsetY}px;
|
| 556 |
+
width: ${doc.documentElement.scrollWidth}px;
|
| 557 |
+
height: ${doc.documentElement.scrollHeight}px;
|
| 558 |
+
transform: scale(${MAGNIFICATION});
|
| 559 |
+
transform-origin: 0 0;
|
| 560 |
+
pointer-events: none;
|
| 561 |
+
`
|
| 562 |
+
this.#loupeEl.style.left = `${loupeLeft + scrollX}px`
|
| 563 |
+
this.#loupeEl.style.top = `${loupeTop + scrollY}px`
|
| 564 |
+
|
| 565 |
+
// Cut a circular hole in the overlayer so highlights don't paint
|
| 566 |
+
// over the loupe.
|
| 567 |
+
if (this.#overlayer) {
|
| 568 |
+
const overlayerRect = this.#overlayer.element.getBoundingClientRect()
|
| 569 |
+
const dx = frameRect.left - overlayerRect.left
|
| 570 |
+
const dy = frameRect.top - overlayerRect.top
|
| 571 |
+
|
| 572 |
+
const cx = loupeLeft + radius + dx
|
| 573 |
+
const cy = loupeTop + radius + dy
|
| 574 |
+
const maskRadius = radius + 3
|
| 575 |
+
|
| 576 |
+
this.#overlayer.setHole(cx, cy, maskRadius)
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
hideLoupe() {
|
| 580 |
+
if (this.#loupeEl) {
|
| 581 |
+
this.#loupeEl.remove()
|
| 582 |
+
this.#loupeEl = null
|
| 583 |
+
this.#loupeScaler = null
|
| 584 |
+
this.#loupeCursor = null
|
| 585 |
+
}
|
| 586 |
+
if (this.#overlayer)
|
| 587 |
+
this.#overlayer.clearHole()
|
| 588 |
+
}
|
| 589 |
+
destroy() {
|
| 590 |
+
if (this.document) this.#observer.unobserve(this.document.body)
|
| 591 |
+
}
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
// NOTE: everything here assumes the so-called "negative scroll type" for RTL
|
| 595 |
+
export class Paginator extends HTMLElement {
|
| 596 |
+
static observedAttributes = [
|
| 597 |
+
'flow', 'gap', 'margin-top', 'margin-bottom', 'margin-left', 'margin-right',
|
| 598 |
+
'max-inline-size', 'max-block-size', 'max-column-count',
|
| 599 |
+
]
|
| 600 |
+
#root = this.attachShadow({ mode: 'open' })
|
| 601 |
+
#observer = new ResizeObserver(() => this.render())
|
| 602 |
+
#top
|
| 603 |
+
#background
|
| 604 |
+
#container
|
| 605 |
+
#header
|
| 606 |
+
#footer
|
| 607 |
+
#view
|
| 608 |
+
#vertical = false
|
| 609 |
+
#rtl = false
|
| 610 |
+
#marginTop = 0
|
| 611 |
+
#marginBottom = 0
|
| 612 |
+
#index = -1
|
| 613 |
+
#anchor = 0 // anchor view to a fraction (0-1), Range, or Element
|
| 614 |
+
#justAnchored = false
|
| 615 |
+
#locked = false // while true, prevent any further navigation
|
| 616 |
+
#styles
|
| 617 |
+
#styleMap = new WeakMap()
|
| 618 |
+
#mediaQuery = matchMedia('(prefers-color-scheme: dark)')
|
| 619 |
+
#mediaQueryListener
|
| 620 |
+
#scrollBounds
|
| 621 |
+
#touchState
|
| 622 |
+
#touchScrolled
|
| 623 |
+
#lastVisibleRange
|
| 624 |
+
#scrollLocked = false
|
| 625 |
+
constructor() {
|
| 626 |
+
super()
|
| 627 |
+
this.#root.innerHTML = `<style>
|
| 628 |
+
:host {
|
| 629 |
+
display: block;
|
| 630 |
+
container-type: size;
|
| 631 |
+
}
|
| 632 |
+
:host, #top {
|
| 633 |
+
box-sizing: border-box;
|
| 634 |
+
position: relative;
|
| 635 |
+
overflow: hidden;
|
| 636 |
+
width: 100%;
|
| 637 |
+
height: 100%;
|
| 638 |
+
}
|
| 639 |
+
#top {
|
| 640 |
+
--_gap: 7%;
|
| 641 |
+
--_margin-top: 48px;
|
| 642 |
+
--_margin-right: 48px;
|
| 643 |
+
--_margin-bottom: 48px;
|
| 644 |
+
--_margin-left: 48px;
|
| 645 |
+
--_max-inline-size: 720px;
|
| 646 |
+
--_max-block-size: 1440px;
|
| 647 |
+
--_max-column-count: 2;
|
| 648 |
+
--_max-column-count-portrait: var(--_max-column-count);
|
| 649 |
+
--_max-column-count-spread: var(--_max-column-count);
|
| 650 |
+
--_half-gap: calc(var(--_gap) / 2);
|
| 651 |
+
--_half-margin-left: calc(var(--_margin-left) / 2);
|
| 652 |
+
--_half-margin-right: calc(var(--_margin-right) / 2);
|
| 653 |
+
--_max-width: calc(var(--_max-inline-size) * var(--_max-column-count-spread));
|
| 654 |
+
--_max-height: var(--_max-block-size);
|
| 655 |
+
display: grid;
|
| 656 |
+
grid-template-columns:
|
| 657 |
+
minmax(0, 1fr)
|
| 658 |
+
var(--_margin-left)
|
| 659 |
+
minmax(0, calc(var(--_max-width) - var(--_gap)))
|
| 660 |
+
var(--_margin-right)
|
| 661 |
+
minmax(0, 1fr);
|
| 662 |
+
grid-template-rows:
|
| 663 |
+
minmax(var(--_margin-top), 1fr)
|
| 664 |
+
minmax(0, var(--_max-height))
|
| 665 |
+
minmax(var(--_margin-bottom), 1fr);
|
| 666 |
+
&.vertical {
|
| 667 |
+
--_max-column-count-spread: var(--_max-column-count-portrait);
|
| 668 |
+
--_max-width: var(--_max-block-size);
|
| 669 |
+
--_max-height: calc(var(--_max-inline-size) * var(--_max-column-count-spread));
|
| 670 |
+
}
|
| 671 |
+
@container (orientation: portrait) {
|
| 672 |
+
& {
|
| 673 |
+
--_max-column-count-spread: var(--_max-column-count-portrait);
|
| 674 |
+
}
|
| 675 |
+
&.vertical {
|
| 676 |
+
--_max-column-count-spread: var(--_max-column-count);
|
| 677 |
+
}
|
| 678 |
+
}
|
| 679 |
+
}
|
| 680 |
+
#background {
|
| 681 |
+
grid-column: 1 / -1;
|
| 682 |
+
grid-row: 1 / -1;
|
| 683 |
+
}
|
| 684 |
+
#container {
|
| 685 |
+
grid-column: 2 / 5;
|
| 686 |
+
grid-row: 1 / -1;
|
| 687 |
+
overflow: hidden;
|
| 688 |
+
}
|
| 689 |
+
:host([flow="scrolled"]) #container {
|
| 690 |
+
grid-column: 2 / 5;
|
| 691 |
+
grid-row: 1 / -1;
|
| 692 |
+
overflow: auto;
|
| 693 |
+
}
|
| 694 |
+
#header {
|
| 695 |
+
grid-column: 3 / 4;
|
| 696 |
+
grid-row: 1;
|
| 697 |
+
}
|
| 698 |
+
#footer {
|
| 699 |
+
grid-column: 3 / 4;
|
| 700 |
+
grid-row: 3;
|
| 701 |
+
align-self: end;
|
| 702 |
+
}
|
| 703 |
+
#header {
|
| 704 |
+
display: grid;
|
| 705 |
+
height: var(--_margin-top);
|
| 706 |
+
}
|
| 707 |
+
#footer {
|
| 708 |
+
display: grid;
|
| 709 |
+
height: var(--_margin-bottom);
|
| 710 |
+
}
|
| 711 |
+
:is(#header, #footer) > * {
|
| 712 |
+
display: flex;
|
| 713 |
+
align-items: center;
|
| 714 |
+
min-width: 0;
|
| 715 |
+
}
|
| 716 |
+
:is(#header, #footer) > * > * {
|
| 717 |
+
width: 100%;
|
| 718 |
+
overflow: hidden;
|
| 719 |
+
white-space: nowrap;
|
| 720 |
+
text-overflow: ellipsis;
|
| 721 |
+
text-align: center;
|
| 722 |
+
font-size: .75em;
|
| 723 |
+
opacity: .6;
|
| 724 |
+
}
|
| 725 |
+
</style>
|
| 726 |
+
<div id="top">
|
| 727 |
+
<div id="background" part="filter"></div>
|
| 728 |
+
<div id="header"></div>
|
| 729 |
+
<div id="container" part="container"></div>
|
| 730 |
+
<div id="footer"></div>
|
| 731 |
+
</div>
|
| 732 |
+
`
|
| 733 |
+
|
| 734 |
+
this.#top = this.#root.getElementById('top')
|
| 735 |
+
this.#background = this.#root.getElementById('background')
|
| 736 |
+
this.#container = this.#root.getElementById('container')
|
| 737 |
+
this.#header = this.#root.getElementById('header')
|
| 738 |
+
this.#footer = this.#root.getElementById('footer')
|
| 739 |
+
|
| 740 |
+
this.#observer.observe(this.#container)
|
| 741 |
+
this.#container.addEventListener('scroll', () => this.dispatchEvent(new Event('scroll')))
|
| 742 |
+
this.#container.addEventListener('scroll', debounce(() => {
|
| 743 |
+
if (this.scrolled) {
|
| 744 |
+
if (this.#justAnchored) this.#justAnchored = false
|
| 745 |
+
else this.#afterScroll('scroll')
|
| 746 |
+
}
|
| 747 |
+
}, 250))
|
| 748 |
+
|
| 749 |
+
const opts = { passive: false }
|
| 750 |
+
this.addEventListener('touchstart', this.#onTouchStart.bind(this), opts)
|
| 751 |
+
this.addEventListener('touchmove', this.#onTouchMove.bind(this), opts)
|
| 752 |
+
this.addEventListener('touchend', this.#onTouchEnd.bind(this))
|
| 753 |
+
this.addEventListener('load', ({ detail: { doc } }) => {
|
| 754 |
+
doc.addEventListener('touchstart', this.#onTouchStart.bind(this), opts)
|
| 755 |
+
doc.addEventListener('touchmove', this.#onTouchMove.bind(this), opts)
|
| 756 |
+
doc.addEventListener('touchend', this.#onTouchEnd.bind(this))
|
| 757 |
+
})
|
| 758 |
+
|
| 759 |
+
this.addEventListener('relocate', ({ detail }) => {
|
| 760 |
+
if (detail.reason === 'selection') setSelectionTo(this.#anchor, 0)
|
| 761 |
+
else if (detail.reason === 'navigation') {
|
| 762 |
+
if (this.#anchor === 1) setSelectionTo(detail.range, 1)
|
| 763 |
+
else if (typeof this.#anchor === 'number')
|
| 764 |
+
setSelectionTo(detail.range, -1)
|
| 765 |
+
else setSelectionTo(this.#anchor, -1)
|
| 766 |
+
}
|
| 767 |
+
})
|
| 768 |
+
const checkPointerSelection = debounce((range, sel) => {
|
| 769 |
+
if (!sel.rangeCount) return
|
| 770 |
+
const selRange = sel.getRangeAt(0)
|
| 771 |
+
const backward = selectionIsBackward(sel)
|
| 772 |
+
if (backward && selRange.compareBoundaryPoints(Range.START_TO_START, range) < 0)
|
| 773 |
+
this.prev()
|
| 774 |
+
else if (!backward && selRange.compareBoundaryPoints(Range.END_TO_END, range) > 0)
|
| 775 |
+
this.next()
|
| 776 |
+
}, 700)
|
| 777 |
+
this.addEventListener('load', ({ detail: { doc } }) => {
|
| 778 |
+
let isPointerSelecting = false
|
| 779 |
+
doc.addEventListener('pointerdown', () => isPointerSelecting = true)
|
| 780 |
+
doc.addEventListener('pointerup', () => isPointerSelecting = false)
|
| 781 |
+
let isKeyboardSelecting = false
|
| 782 |
+
doc.addEventListener('keydown', () => isKeyboardSelecting = true)
|
| 783 |
+
doc.addEventListener('keyup', () => isKeyboardSelecting = false)
|
| 784 |
+
doc.addEventListener('selectionchange', () => {
|
| 785 |
+
if (this.scrolled) return
|
| 786 |
+
const range = this.#lastVisibleRange
|
| 787 |
+
if (!range) return
|
| 788 |
+
const sel = doc.getSelection()
|
| 789 |
+
if (!sel.rangeCount) return
|
| 790 |
+
// FIXME: this won't work on Android WebView, disable for now
|
| 791 |
+
if (!isPointerSelecting && isPointerSelecting && sel.type === 'Range')
|
| 792 |
+
checkPointerSelection(range, sel)
|
| 793 |
+
else if (isKeyboardSelecting) {
|
| 794 |
+
const selRange = sel.getRangeAt(0).cloneRange()
|
| 795 |
+
const backward = selectionIsBackward(sel)
|
| 796 |
+
if (!backward) selRange.collapse()
|
| 797 |
+
this.#scrollToAnchor(selRange)
|
| 798 |
+
}
|
| 799 |
+
})
|
| 800 |
+
doc.addEventListener('focusin', e => {
|
| 801 |
+
if (this.scrolled) return null
|
| 802 |
+
if (this.#container && this.#container.contains(e.target)) {
|
| 803 |
+
// NOTE: `requestAnimationFrame` is needed in WebKit
|
| 804 |
+
requestAnimationFrame(() => this.#scrollToAnchor(e.target))
|
| 805 |
+
}
|
| 806 |
+
})
|
| 807 |
+
})
|
| 808 |
+
|
| 809 |
+
this.#mediaQueryListener = () => {
|
| 810 |
+
if (!this.#view) return
|
| 811 |
+
this.#replaceBackground(this.#view.docBackground, this.columnCount)
|
| 812 |
+
}
|
| 813 |
+
this.#mediaQuery.addEventListener('change', this.#mediaQueryListener)
|
| 814 |
+
}
|
| 815 |
+
attributeChangedCallback(name, _, value) {
|
| 816 |
+
switch (name) {
|
| 817 |
+
case 'flow':
|
| 818 |
+
this.render()
|
| 819 |
+
break
|
| 820 |
+
case 'gap':
|
| 821 |
+
case 'margin-top':
|
| 822 |
+
case 'margin-bottom':
|
| 823 |
+
case 'margin-left':
|
| 824 |
+
case 'margin-right':
|
| 825 |
+
case 'max-block-size':
|
| 826 |
+
case 'max-column-count':
|
| 827 |
+
this.#top.style.setProperty('--_' + name, value)
|
| 828 |
+
this.render()
|
| 829 |
+
break
|
| 830 |
+
case 'max-inline-size':
|
| 831 |
+
// needs explicit `render()` as it doesn't necessarily resize
|
| 832 |
+
this.#top.style.setProperty('--_' + name, value)
|
| 833 |
+
this.render()
|
| 834 |
+
break
|
| 835 |
+
}
|
| 836 |
+
}
|
| 837 |
+
open(book) {
|
| 838 |
+
this.bookDir = book.dir
|
| 839 |
+
this.sections = book.sections
|
| 840 |
+
book.transformTarget?.addEventListener('data', ({ detail }) => {
|
| 841 |
+
if (detail.type !== 'text/css') return
|
| 842 |
+
detail.data = Promise.resolve(detail.data).then(data => data
|
| 843 |
+
// unprefix as most of the props are (only) supported unprefixed
|
| 844 |
+
.replace(/([{\s;])-epub-/gi, '$1')
|
| 845 |
+
// `page-break-*` unsupported in columns; replace with `column-break-*`
|
| 846 |
+
.replace(/page-break-(after|before|inside)\s*:/gi, (_, x) =>
|
| 847 |
+
`-webkit-column-break-${x}:`)
|
| 848 |
+
.replace(/break-(after|before|inside)\s*:\s*(avoid-)?page/gi, (_, x, y) =>
|
| 849 |
+
`break-${x}: ${y ?? ''}column`))
|
| 850 |
+
})
|
| 851 |
+
}
|
| 852 |
+
#createView() {
|
| 853 |
+
if (this.#view) {
|
| 854 |
+
this.#view.destroy()
|
| 855 |
+
this.#container.removeChild(this.#view.element)
|
| 856 |
+
}
|
| 857 |
+
this.#view = new View({
|
| 858 |
+
container: this,
|
| 859 |
+
onExpand: () => this.#scrollToAnchor(this.#anchor),
|
| 860 |
+
})
|
| 861 |
+
this.#container.append(this.#view.element)
|
| 862 |
+
return this.#view
|
| 863 |
+
}
|
| 864 |
+
#replaceBackground(background, columnCount) {
|
| 865 |
+
const doc = this.#view?.document
|
| 866 |
+
if (!doc) return
|
| 867 |
+
const htmlStyle = doc.defaultView.getComputedStyle(doc.documentElement)
|
| 868 |
+
const themeBgColor = htmlStyle.getPropertyValue('--theme-bg-color')
|
| 869 |
+
const overrideColor = htmlStyle.getPropertyValue('--override-color') === 'true'
|
| 870 |
+
const bgTextureId = htmlStyle.getPropertyValue('--bg-texture-id')
|
| 871 |
+
const isDarkMode = htmlStyle.getPropertyValue('color-scheme') === 'dark'
|
| 872 |
+
if (background && themeBgColor) {
|
| 873 |
+
const parsedBackground = background.split(/\s(?=(?:url|rgb|hsl|#[0-9a-fA-F]{3,6}))/)
|
| 874 |
+
if ((isDarkMode || overrideColor) && (bgTextureId === 'none' || !bgTextureId)) {
|
| 875 |
+
parsedBackground[0] = themeBgColor
|
| 876 |
+
}
|
| 877 |
+
background = parsedBackground.join(' ')
|
| 878 |
+
}
|
| 879 |
+
this.#background.innerHTML = ''
|
| 880 |
+
this.#background.style.display = 'grid'
|
| 881 |
+
this.#background.style.gridTemplateColumns = `repeat(${columnCount}, 1fr)`
|
| 882 |
+
for (let i = 0; i < columnCount; i++) {
|
| 883 |
+
const column = document.createElement('div')
|
| 884 |
+
column.style.background = background
|
| 885 |
+
column.style.width = '100%'
|
| 886 |
+
column.style.height = '100%'
|
| 887 |
+
this.#background.appendChild(column)
|
| 888 |
+
}
|
| 889 |
+
}
|
| 890 |
+
#beforeRender({ vertical, rtl, background }) {
|
| 891 |
+
this.#vertical = vertical
|
| 892 |
+
this.#rtl = rtl
|
| 893 |
+
this.#top.classList.toggle('vertical', vertical)
|
| 894 |
+
|
| 895 |
+
const { width, height } = this.#container.getBoundingClientRect()
|
| 896 |
+
const size = vertical ? height : width
|
| 897 |
+
|
| 898 |
+
const style = getComputedStyle(this.#top)
|
| 899 |
+
const maxInlineSize = parseFloat(style.getPropertyValue('--_max-inline-size'))
|
| 900 |
+
const maxColumnCount = parseInt(style.getPropertyValue('--_max-column-count-spread'))
|
| 901 |
+
const marginTop = parseFloat(style.getPropertyValue('--_margin-top'))
|
| 902 |
+
const marginRight = parseFloat(style.getPropertyValue('--_margin-right'))
|
| 903 |
+
const marginBottom = parseFloat(style.getPropertyValue('--_margin-bottom'))
|
| 904 |
+
const marginLeft = parseFloat(style.getPropertyValue('--_margin-left'))
|
| 905 |
+
this.#marginTop = marginTop
|
| 906 |
+
this.#marginBottom = marginBottom
|
| 907 |
+
|
| 908 |
+
const g = parseFloat(style.getPropertyValue('--_gap')) / 100
|
| 909 |
+
// The gap will be a percentage of the #container, not the whole view.
|
| 910 |
+
// This means the outer padding will be bigger than the column gap. Let
|
| 911 |
+
// `a` be the gap percentage. The actual percentage for the column gap
|
| 912 |
+
// will be (1 - a) * a. Let us call this `b`.
|
| 913 |
+
//
|
| 914 |
+
// To make them the same, we start by shrinking the outer padding
|
| 915 |
+
// setting to `b`, but keep the column gap setting the same at `a`. Then
|
| 916 |
+
// the actual size for the column gap will be (1 - b) * a. Repeating the
|
| 917 |
+
// process again and again, we get the sequence
|
| 918 |
+
// x₁ = (1 - b) * a
|
| 919 |
+
// x₂ = (1 - x₁) * a
|
| 920 |
+
// ...
|
| 921 |
+
// which converges to x = (1 - x) * a. Solving for x, x = a / (1 + a).
|
| 922 |
+
// So to make the spacing even, we must shrink the outer padding with
|
| 923 |
+
// f(x) = x / (1 + x).
|
| 924 |
+
// But we want to keep the outer padding, and make the inner gap bigger.
|
| 925 |
+
// So we apply the inverse, f⁻¹ = -x / (x - 1) to the column gap.
|
| 926 |
+
const gap = -g / (g - 1) * size
|
| 927 |
+
|
| 928 |
+
const flow = this.getAttribute('flow')
|
| 929 |
+
if (flow === 'scrolled') {
|
| 930 |
+
// FIXME: vertical-rl only, not -lr
|
| 931 |
+
this.setAttribute('dir', vertical ? 'rtl' : 'ltr')
|
| 932 |
+
this.#top.style.padding = '0'
|
| 933 |
+
const columnWidth = maxInlineSize
|
| 934 |
+
|
| 935 |
+
this.heads = null
|
| 936 |
+
this.feet = null
|
| 937 |
+
this.#header.replaceChildren()
|
| 938 |
+
this.#footer.replaceChildren()
|
| 939 |
+
|
| 940 |
+
this.columnCount = 1
|
| 941 |
+
this.#replaceBackground(background, this.columnCount)
|
| 942 |
+
|
| 943 |
+
return { flow, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
const divisor = Math.min(maxColumnCount + (vertical ? 1 : 0), Math.ceil(Math.floor(size) / Math.floor(maxInlineSize)))
|
| 947 |
+
const columnWidth = vertical
|
| 948 |
+
? (size / divisor - marginTop * 1.5 - marginBottom * 1.5)
|
| 949 |
+
: (size / divisor - gap - marginRight / 2 - marginLeft / 2)
|
| 950 |
+
this.setAttribute('dir', rtl ? 'rtl' : 'ltr')
|
| 951 |
+
|
| 952 |
+
// set background to `doc` background
|
| 953 |
+
// this is needed because the iframe does not fill the whole element
|
| 954 |
+
this.columnCount = divisor
|
| 955 |
+
this.#replaceBackground(background, this.columnCount)
|
| 956 |
+
|
| 957 |
+
const marginalDivisor = vertical
|
| 958 |
+
? Math.min(2, Math.ceil(Math.floor(width) / Math.floor(maxInlineSize)))
|
| 959 |
+
: divisor
|
| 960 |
+
const marginalStyle = {
|
| 961 |
+
gridTemplateColumns: `repeat(${marginalDivisor}, 1fr)`,
|
| 962 |
+
gap: `${gap}px`,
|
| 963 |
+
direction: this.bookDir === 'rtl' ? 'rtl' : 'ltr',
|
| 964 |
+
}
|
| 965 |
+
Object.assign(this.#header.style, marginalStyle)
|
| 966 |
+
Object.assign(this.#footer.style, marginalStyle)
|
| 967 |
+
const heads = makeMarginals(marginalDivisor, 'head')
|
| 968 |
+
const feet = makeMarginals(marginalDivisor, 'foot')
|
| 969 |
+
this.heads = heads.map(el => el.children[0])
|
| 970 |
+
this.feet = feet.map(el => el.children[0])
|
| 971 |
+
this.#header.replaceChildren(...heads)
|
| 972 |
+
this.#footer.replaceChildren(...feet)
|
| 973 |
+
|
| 974 |
+
return { height, width, marginTop, marginRight, marginBottom, marginLeft, gap, columnWidth }
|
| 975 |
+
}
|
| 976 |
+
render() {
|
| 977 |
+
if (!this.#view) return
|
| 978 |
+
this.#view.render(this.#beforeRender({
|
| 979 |
+
vertical: this.#vertical,
|
| 980 |
+
rtl: this.#rtl,
|
| 981 |
+
background: this.#view.docBackground,
|
| 982 |
+
}))
|
| 983 |
+
this.#scrollToAnchor(this.#anchor)
|
| 984 |
+
}
|
| 985 |
+
get scrolled() {
|
| 986 |
+
return this.getAttribute('flow') === 'scrolled'
|
| 987 |
+
}
|
| 988 |
+
get scrollProp() {
|
| 989 |
+
const { scrolled } = this
|
| 990 |
+
return this.#vertical ? (scrolled ? 'scrollLeft' : 'scrollTop')
|
| 991 |
+
: scrolled ? 'scrollTop' : 'scrollLeft'
|
| 992 |
+
}
|
| 993 |
+
get sideProp() {
|
| 994 |
+
const { scrolled } = this
|
| 995 |
+
return this.#vertical ? (scrolled ? 'width' : 'height')
|
| 996 |
+
: scrolled ? 'height' : 'width'
|
| 997 |
+
}
|
| 998 |
+
get size() {
|
| 999 |
+
return this.#container.getBoundingClientRect()[this.sideProp]
|
| 1000 |
+
}
|
| 1001 |
+
get viewSize() {
|
| 1002 |
+
if (!this.#view || !this.#view.element) return 0
|
| 1003 |
+
return this.#view.element.getBoundingClientRect()[this.sideProp]
|
| 1004 |
+
}
|
| 1005 |
+
get start() {
|
| 1006 |
+
return Math.abs(this.#container[this.scrollProp])
|
| 1007 |
+
}
|
| 1008 |
+
get end() {
|
| 1009 |
+
return this.start + this.size
|
| 1010 |
+
}
|
| 1011 |
+
get page() {
|
| 1012 |
+
return Math.floor(((this.start + this.end) / 2) / this.size)
|
| 1013 |
+
}
|
| 1014 |
+
get pages() {
|
| 1015 |
+
return Math.round(this.viewSize / this.size)
|
| 1016 |
+
}
|
| 1017 |
+
get containerPosition() {
|
| 1018 |
+
return this.#container[this.scrollProp]
|
| 1019 |
+
}
|
| 1020 |
+
get isOverflowX() {
|
| 1021 |
+
return false
|
| 1022 |
+
}
|
| 1023 |
+
get isOverflowY() {
|
| 1024 |
+
return false
|
| 1025 |
+
}
|
| 1026 |
+
set containerPosition(newVal) {
|
| 1027 |
+
this.#container[this.scrollProp] = newVal
|
| 1028 |
+
}
|
| 1029 |
+
set scrollLocked(value) {
|
| 1030 |
+
this.#scrollLocked = value
|
| 1031 |
+
}
|
| 1032 |
+
|
| 1033 |
+
scrollBy(dx, dy) {
|
| 1034 |
+
const delta = this.#vertical ? dy : dx
|
| 1035 |
+
const [offset, a, b] = this.#scrollBounds
|
| 1036 |
+
const rtl = this.#rtl
|
| 1037 |
+
const min = rtl ? offset - b : offset - a
|
| 1038 |
+
const max = rtl ? offset + a : offset + b
|
| 1039 |
+
this.containerPosition = Math.max(min, Math.min(max,
|
| 1040 |
+
this.containerPosition + delta))
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
snap(vx, vy) {
|
| 1044 |
+
const velocity = this.#vertical ? vy : vx
|
| 1045 |
+
const horizontal = Math.abs(vx) * 2 > Math.abs(vy)
|
| 1046 |
+
const orthogonal = this.#vertical ? !horizontal : horizontal
|
| 1047 |
+
const [offset, a, b] = this.#scrollBounds
|
| 1048 |
+
const { start, end, pages, size } = this
|
| 1049 |
+
const min = Math.abs(offset) - a
|
| 1050 |
+
const max = Math.abs(offset) + b
|
| 1051 |
+
const d = velocity * (this.#rtl ? -size : size) * (orthogonal ? 1 : 0)
|
| 1052 |
+
const page = Math.floor(
|
| 1053 |
+
Math.max(min, Math.min(max, (start + end) / 2
|
| 1054 |
+
+ (isNaN(d) ? 0 : d * 2))) / size)
|
| 1055 |
+
|
| 1056 |
+
this.#scrollToPage(page, 'snap').then(() => {
|
| 1057 |
+
const dir = page <= 0 ? -1 : page >= pages - 1 ? 1 : null
|
| 1058 |
+
if (dir) return this.#goTo({
|
| 1059 |
+
index: this.#adjacentIndex(dir),
|
| 1060 |
+
anchor: dir < 0 ? () => 1 : () => 0,
|
| 1061 |
+
})
|
| 1062 |
+
})
|
| 1063 |
+
}
|
| 1064 |
+
#onTouchStart(e) {
|
| 1065 |
+
const touch = e.changedTouches[0]
|
| 1066 |
+
this.#touchState = {
|
| 1067 |
+
x: touch?.screenX, y: touch?.screenY,
|
| 1068 |
+
t: e.timeStamp,
|
| 1069 |
+
vx: 0, xy: 0,
|
| 1070 |
+
dx: 0, dy: 0,
|
| 1071 |
+
}
|
| 1072 |
+
}
|
| 1073 |
+
#onTouchMove(e) {
|
| 1074 |
+
const state = this.#touchState
|
| 1075 |
+
if (state.pinched) return
|
| 1076 |
+
state.pinched = globalThis.visualViewport.scale > 1
|
| 1077 |
+
if (this.scrolled || state.pinched) return
|
| 1078 |
+
if (e.touches.length > 1) {
|
| 1079 |
+
if (this.#touchScrolled) e.preventDefault()
|
| 1080 |
+
return
|
| 1081 |
+
}
|
| 1082 |
+
const doc = this.#view?.document
|
| 1083 |
+
const selection = doc?.getSelection()
|
| 1084 |
+
if (selection && selection.rangeCount > 0 && !selection.isCollapsed) {
|
| 1085 |
+
return
|
| 1086 |
+
}
|
| 1087 |
+
const touch = e.changedTouches[0]
|
| 1088 |
+
const isStylus = touch.touchType === 'stylus'
|
| 1089 |
+
if (!isStylus) e.preventDefault()
|
| 1090 |
+
if (this.#scrollLocked) return
|
| 1091 |
+
const x = touch.screenX, y = touch.screenY
|
| 1092 |
+
const dx = state.x - x, dy = state.y - y
|
| 1093 |
+
const dt = e.timeStamp - state.t
|
| 1094 |
+
state.x = x
|
| 1095 |
+
state.y = y
|
| 1096 |
+
state.t = e.timeStamp
|
| 1097 |
+
state.vx = dx / dt
|
| 1098 |
+
state.vy = dy / dt
|
| 1099 |
+
state.dx += dx
|
| 1100 |
+
state.dy += dy
|
| 1101 |
+
this.#touchScrolled = true
|
| 1102 |
+
if (!this.hasAttribute('animated') || this.hasAttribute('eink')) return
|
| 1103 |
+
if (!this.#vertical && Math.abs(state.dx) >= Math.abs(state.dy) && !this.hasAttribute('eink') && (!isStylus || Math.abs(dx) > 1)) {
|
| 1104 |
+
this.scrollBy(dx, 0)
|
| 1105 |
+
} else if (this.#vertical && Math.abs(state.dx) < Math.abs(state.dy) && !this.hasAttribute('eink') && (!isStylus || Math.abs(dy) > 1)) {
|
| 1106 |
+
this.scrollBy(0, dy)
|
| 1107 |
+
}
|
| 1108 |
+
}
|
| 1109 |
+
#onTouchEnd() {
|
| 1110 |
+
if (!this.#touchScrolled) return
|
| 1111 |
+
this.#touchScrolled = false
|
| 1112 |
+
if (this.scrolled) return
|
| 1113 |
+
|
| 1114 |
+
// XXX: Firefox seems to report scale as 1... sometimes...?
|
| 1115 |
+
// at this point I'm basically throwing `requestAnimationFrame` at
|
| 1116 |
+
// anything that doesn't work
|
| 1117 |
+
requestAnimationFrame(() => {
|
| 1118 |
+
if (globalThis.visualViewport.scale === 1)
|
| 1119 |
+
this.snap(this.#touchState.vx, this.#touchState.vy)
|
| 1120 |
+
})
|
| 1121 |
+
}
|
| 1122 |
+
// allows one to process rects as if they were LTR and horizontal
|
| 1123 |
+
#getRectMapper() {
|
| 1124 |
+
if (this.scrolled) {
|
| 1125 |
+
const size = this.viewSize
|
| 1126 |
+
const marginTop = this.#marginTop
|
| 1127 |
+
const marginBottom = this.#marginBottom
|
| 1128 |
+
return this.#vertical
|
| 1129 |
+
? ({ left, right }) =>
|
| 1130 |
+
({ left: size - right - marginTop, right: size - left - marginBottom })
|
| 1131 |
+
: ({ top, bottom }) => ({ left: top - marginTop, right: bottom - marginBottom })
|
| 1132 |
+
}
|
| 1133 |
+
const pxSize = this.pages * this.size
|
| 1134 |
+
return this.#rtl
|
| 1135 |
+
? ({ left, right }) =>
|
| 1136 |
+
({ left: pxSize - right, right: pxSize - left })
|
| 1137 |
+
: this.#vertical
|
| 1138 |
+
? ({ top, bottom }) => ({ left: top, right: bottom })
|
| 1139 |
+
: f => f
|
| 1140 |
+
}
|
| 1141 |
+
async #scrollToRect(rect, reason) {
|
| 1142 |
+
if (this.scrolled) {
|
| 1143 |
+
const offset = this.#getRectMapper()(rect).left - 4
|
| 1144 |
+
return this.#scrollTo(offset, reason)
|
| 1145 |
+
}
|
| 1146 |
+
const offset = this.#getRectMapper()(rect).left
|
| 1147 |
+
return this.#scrollToPage(Math.floor(offset / this.size) + (this.#rtl ? -1 : 1), reason)
|
| 1148 |
+
}
|
| 1149 |
+
async #scrollTo(offset, reason, smooth) {
|
| 1150 |
+
const { size } = this
|
| 1151 |
+
if (this.containerPosition === offset) {
|
| 1152 |
+
this.#scrollBounds = [offset, this.atStart ? 0 : size, this.atEnd ? 0 : size]
|
| 1153 |
+
this.#afterScroll(reason)
|
| 1154 |
+
return
|
| 1155 |
+
}
|
| 1156 |
+
// FIXME: vertical-rl only, not -lr
|
| 1157 |
+
if (this.scrolled && this.#vertical) offset = -offset
|
| 1158 |
+
if ((reason === 'snap' || smooth) && this.hasAttribute('animated') && !this.hasAttribute('eink')) return animate(
|
| 1159 |
+
this.containerPosition, offset, 300, easeOutQuad,
|
| 1160 |
+
x => this.containerPosition = x,
|
| 1161 |
+
).then(() => {
|
| 1162 |
+
this.#scrollBounds = [offset, this.atStart ? 0 : size, this.atEnd ? 0 : size]
|
| 1163 |
+
this.#afterScroll(reason)
|
| 1164 |
+
})
|
| 1165 |
+
else {
|
| 1166 |
+
this.containerPosition = offset
|
| 1167 |
+
this.#scrollBounds = [offset, this.atStart ? 0 : size, this.atEnd ? 0 : size]
|
| 1168 |
+
this.#afterScroll(reason)
|
| 1169 |
+
}
|
| 1170 |
+
}
|
| 1171 |
+
async #scrollToPage(page, reason, smooth) {
|
| 1172 |
+
const offset = this.size * (this.#rtl ? -page : page)
|
| 1173 |
+
return this.#scrollTo(offset, reason, smooth)
|
| 1174 |
+
}
|
| 1175 |
+
async scrollToAnchor(anchor, select) {
|
| 1176 |
+
return this.#scrollToAnchor(anchor, select ? 'selection' : 'navigation')
|
| 1177 |
+
}
|
| 1178 |
+
async #scrollToAnchor(anchor, reason = 'anchor') {
|
| 1179 |
+
this.#anchor = anchor
|
| 1180 |
+
const rects = uncollapse(anchor)?.getClientRects?.()
|
| 1181 |
+
// if anchor is an element or a range
|
| 1182 |
+
if (rects) {
|
| 1183 |
+
// when the start of the range is immediately after a hyphen in the
|
| 1184 |
+
// previous column, there is an extra zero width rect in that column
|
| 1185 |
+
const rect = Array.from(rects)
|
| 1186 |
+
.find(r => r.width > 0 && r.height > 0 && r.x >= 0 && r.y >= 0) || rects[0]
|
| 1187 |
+
if (!rect) return
|
| 1188 |
+
await this.#scrollToRect(rect, reason)
|
| 1189 |
+
// focus the element when navigating with keyboard or screen reader
|
| 1190 |
+
if (reason === 'navigation') {
|
| 1191 |
+
let node = anchor.focus ? anchor : undefined
|
| 1192 |
+
if (!node && anchor.startContainer) {
|
| 1193 |
+
node = anchor.startContainer
|
| 1194 |
+
if (node.nodeType === Node.TEXT_NODE) {
|
| 1195 |
+
node = node.parentElement
|
| 1196 |
+
}
|
| 1197 |
+
}
|
| 1198 |
+
if (node && node.focus) {
|
| 1199 |
+
node.tabIndex = -1
|
| 1200 |
+
node.style.outline = 'none'
|
| 1201 |
+
node.focus({ preventScroll: true })
|
| 1202 |
+
}
|
| 1203 |
+
}
|
| 1204 |
+
return
|
| 1205 |
+
}
|
| 1206 |
+
// if anchor is a fraction
|
| 1207 |
+
if (this.scrolled) {
|
| 1208 |
+
await this.#scrollTo(anchor * this.viewSize, reason)
|
| 1209 |
+
return
|
| 1210 |
+
}
|
| 1211 |
+
const { pages } = this
|
| 1212 |
+
if (!pages) return
|
| 1213 |
+
const textPages = pages - 2
|
| 1214 |
+
const newPage = Math.round(anchor * (textPages - 1))
|
| 1215 |
+
await this.#scrollToPage(newPage + 1, reason)
|
| 1216 |
+
}
|
| 1217 |
+
#getVisibleRange() {
|
| 1218 |
+
if (this.scrolled) return getVisibleRange(this.#view.document,
|
| 1219 |
+
this.start, this.end, this.#getRectMapper())
|
| 1220 |
+
const size = this.#rtl ? -this.size : this.size
|
| 1221 |
+
return getVisibleRange(this.#view.document,
|
| 1222 |
+
this.start - size, this.end - size, this.#getRectMapper())
|
| 1223 |
+
}
|
| 1224 |
+
#afterScroll(reason) {
|
| 1225 |
+
const range = this.#getVisibleRange()
|
| 1226 |
+
this.#lastVisibleRange = range
|
| 1227 |
+
// don't set new anchor if relocation was to scroll to anchor
|
| 1228 |
+
if (reason !== 'selection' && reason !== 'navigation' && reason !== 'anchor')
|
| 1229 |
+
this.#anchor = range
|
| 1230 |
+
else this.#justAnchored = true
|
| 1231 |
+
|
| 1232 |
+
const index = this.#index
|
| 1233 |
+
const detail = { reason, range, index }
|
| 1234 |
+
if (this.scrolled) detail.fraction = this.start / this.viewSize
|
| 1235 |
+
else if (this.pages > 0) {
|
| 1236 |
+
const { page, pages } = this
|
| 1237 |
+
this.#header.style.visibility = page > 1 ? 'visible' : 'hidden'
|
| 1238 |
+
detail.fraction = (page - 1) / (pages - 2)
|
| 1239 |
+
detail.size = 1 / (pages - 2)
|
| 1240 |
+
}
|
| 1241 |
+
this.dispatchEvent(new CustomEvent('relocate', { detail }))
|
| 1242 |
+
}
|
| 1243 |
+
async #display(promise) {
|
| 1244 |
+
const { index, src, data, anchor, onLoad, select } = await promise
|
| 1245 |
+
this.#index = index
|
| 1246 |
+
const hasFocus = this.#view?.document?.hasFocus()
|
| 1247 |
+
if (src) {
|
| 1248 |
+
const view = this.#createView()
|
| 1249 |
+
const afterLoad = doc => {
|
| 1250 |
+
if (doc.head) {
|
| 1251 |
+
const $styleBefore = doc.createElement('style')
|
| 1252 |
+
doc.head.prepend($styleBefore)
|
| 1253 |
+
const $style = doc.createElement('style')
|
| 1254 |
+
doc.head.append($style)
|
| 1255 |
+
this.#styleMap.set(doc, [$styleBefore, $style])
|
| 1256 |
+
}
|
| 1257 |
+
onLoad?.({ doc, index })
|
| 1258 |
+
}
|
| 1259 |
+
const beforeRender = this.#beforeRender.bind(this)
|
| 1260 |
+
await view.load(src, data, afterLoad, beforeRender)
|
| 1261 |
+
this.dispatchEvent(new CustomEvent('create-overlayer', {
|
| 1262 |
+
detail: {
|
| 1263 |
+
doc: view.document, index,
|
| 1264 |
+
attach: overlayer => view.overlayer = overlayer,
|
| 1265 |
+
},
|
| 1266 |
+
}))
|
| 1267 |
+
this.#view = view
|
| 1268 |
+
}
|
| 1269 |
+
await this.scrollToAnchor((typeof anchor === 'function'
|
| 1270 |
+
? anchor(this.#view.document) : anchor) ?? 0, select)
|
| 1271 |
+
if (hasFocus) this.focusView()
|
| 1272 |
+
}
|
| 1273 |
+
#canGoToIndex(index) {
|
| 1274 |
+
return index >= 0 && index <= this.sections.length - 1
|
| 1275 |
+
}
|
| 1276 |
+
async #goTo({ index, anchor, select }) {
|
| 1277 |
+
if (index === this.#index) await this.#display({ index, anchor, select })
|
| 1278 |
+
else {
|
| 1279 |
+
const oldIndex = this.#index
|
| 1280 |
+
const onLoad = detail => {
|
| 1281 |
+
this.sections[oldIndex]?.unload?.()
|
| 1282 |
+
this.setStyles(this.#styles)
|
| 1283 |
+
this.dispatchEvent(new CustomEvent('load', { detail }))
|
| 1284 |
+
}
|
| 1285 |
+
await this.#display(Promise.resolve(this.sections[index].load())
|
| 1286 |
+
.then(async src => {
|
| 1287 |
+
const data = await this.sections[index].loadContent?.()
|
| 1288 |
+
return { index, src, data, anchor, onLoad, select }
|
| 1289 |
+
}).catch(e => {
|
| 1290 |
+
console.warn(e)
|
| 1291 |
+
console.warn(new Error(`Failed to load section ${index}`))
|
| 1292 |
+
return {}
|
| 1293 |
+
}))
|
| 1294 |
+
}
|
| 1295 |
+
}
|
| 1296 |
+
async goTo(target) {
|
| 1297 |
+
if (this.#locked) return
|
| 1298 |
+
const resolved = await target
|
| 1299 |
+
if (this.#canGoToIndex(resolved.index)) return this.#goTo(resolved)
|
| 1300 |
+
}
|
| 1301 |
+
#scrollPrev(distance) {
|
| 1302 |
+
if (!this.#view) return true
|
| 1303 |
+
if (this.scrolled) {
|
| 1304 |
+
if (this.start > 0) return this.#scrollTo(
|
| 1305 |
+
Math.max(0, this.start - (distance ?? this.size)), null, true)
|
| 1306 |
+
return !this.atStart
|
| 1307 |
+
}
|
| 1308 |
+
if (this.atStart) return
|
| 1309 |
+
const page = this.page - 1
|
| 1310 |
+
return this.#scrollToPage(page, 'page', true).then(() => page <= 0)
|
| 1311 |
+
}
|
| 1312 |
+
#scrollNext(distance) {
|
| 1313 |
+
if (!this.#view) return true
|
| 1314 |
+
if (this.scrolled) {
|
| 1315 |
+
if (this.viewSize - this.end > 2) return this.#scrollTo(
|
| 1316 |
+
Math.min(this.viewSize, distance ? this.start + distance : this.end), null, true)
|
| 1317 |
+
return !this.atEnd
|
| 1318 |
+
}
|
| 1319 |
+
if (this.atEnd) return
|
| 1320 |
+
const page = this.page + 1
|
| 1321 |
+
const pages = this.pages
|
| 1322 |
+
return this.#scrollToPage(page, 'page', true).then(() => page >= pages - 1)
|
| 1323 |
+
}
|
| 1324 |
+
get atStart() {
|
| 1325 |
+
return this.#adjacentIndex(-1) == null && this.page <= 1
|
| 1326 |
+
}
|
| 1327 |
+
get atEnd() {
|
| 1328 |
+
return this.#adjacentIndex(1) == null && this.page >= this.pages - 2
|
| 1329 |
+
}
|
| 1330 |
+
#adjacentIndex(dir) {
|
| 1331 |
+
for (let index = this.#index + dir; this.#canGoToIndex(index); index += dir)
|
| 1332 |
+
if (this.sections[index]?.linear !== 'no') return index
|
| 1333 |
+
}
|
| 1334 |
+
async #turnPage(dir, distance) {
|
| 1335 |
+
if (this.#locked) return
|
| 1336 |
+
this.#locked = true
|
| 1337 |
+
const prev = dir === -1
|
| 1338 |
+
const shouldGo = await (prev ? this.#scrollPrev(distance) : this.#scrollNext(distance))
|
| 1339 |
+
if (shouldGo) await this.#goTo({
|
| 1340 |
+
index: this.#adjacentIndex(dir),
|
| 1341 |
+
anchor: prev ? () => 1 : () => 0,
|
| 1342 |
+
})
|
| 1343 |
+
if (shouldGo || !this.hasAttribute('animated')) await wait(100)
|
| 1344 |
+
this.#locked = false
|
| 1345 |
+
}
|
| 1346 |
+
async prev(distance) {
|
| 1347 |
+
return await this.#turnPage(-1, distance)
|
| 1348 |
+
}
|
| 1349 |
+
async next(distance) {
|
| 1350 |
+
return await this.#turnPage(1, distance)
|
| 1351 |
+
}
|
| 1352 |
+
async pan(dx, dy) {
|
| 1353 |
+
if (this.#locked) return
|
| 1354 |
+
this.#locked = true
|
| 1355 |
+
this.scrollBy(dx, dy)
|
| 1356 |
+
this.#locked = false
|
| 1357 |
+
}
|
| 1358 |
+
prevSection() {
|
| 1359 |
+
return this.goTo({ index: this.#adjacentIndex(-1) })
|
| 1360 |
+
}
|
| 1361 |
+
nextSection() {
|
| 1362 |
+
return this.goTo({ index: this.#adjacentIndex(1) })
|
| 1363 |
+
}
|
| 1364 |
+
firstSection() {
|
| 1365 |
+
const index = this.sections.findIndex(section => section.linear !== 'no')
|
| 1366 |
+
return this.goTo({ index })
|
| 1367 |
+
}
|
| 1368 |
+
lastSection() {
|
| 1369 |
+
const index = this.sections.findLastIndex(section => section.linear !== 'no')
|
| 1370 |
+
return this.goTo({ index })
|
| 1371 |
+
}
|
| 1372 |
+
getContents() {
|
| 1373 |
+
if (this.#view) return [{
|
| 1374 |
+
index: this.#index,
|
| 1375 |
+
overlayer: this.#view.overlayer,
|
| 1376 |
+
doc: this.#view.document,
|
| 1377 |
+
}]
|
| 1378 |
+
return []
|
| 1379 |
+
}
|
| 1380 |
+
setStyles(styles) {
|
| 1381 |
+
this.#styles = styles
|
| 1382 |
+
const $$styles = this.#styleMap.get(this.#view?.document)
|
| 1383 |
+
if (!$$styles) return
|
| 1384 |
+
const [$beforeStyle, $style] = $$styles
|
| 1385 |
+
if (Array.isArray(styles)) {
|
| 1386 |
+
const [beforeStyle, style] = styles
|
| 1387 |
+
$beforeStyle.textContent = beforeStyle
|
| 1388 |
+
$style.textContent = style
|
| 1389 |
+
} else $style.textContent = styles
|
| 1390 |
+
|
| 1391 |
+
// NOTE: needs `requestAnimationFrame` in Chromium
|
| 1392 |
+
requestAnimationFrame(() => {
|
| 1393 |
+
this.#replaceBackground(this.#view.docBackground, this.columnCount)
|
| 1394 |
+
})
|
| 1395 |
+
|
| 1396 |
+
// needed because the resize observer doesn't work in Firefox
|
| 1397 |
+
this.#view?.document?.fonts?.ready?.then(() => this.#view.expand())
|
| 1398 |
+
}
|
| 1399 |
+
focusView() {
|
| 1400 |
+
this.#view.document.defaultView.focus()
|
| 1401 |
+
}
|
| 1402 |
+
showLoupe(winX, winY, { isVertical, color, radius }) {
|
| 1403 |
+
this.#view?.showLoupe(winX, winY, { isVertical, color, radius })
|
| 1404 |
+
}
|
| 1405 |
+
hideLoupe() {
|
| 1406 |
+
this.#view?.hideLoupe()
|
| 1407 |
+
}
|
| 1408 |
+
destroy() {
|
| 1409 |
+
this.#observer.unobserve(this)
|
| 1410 |
+
this.#view.destroy()
|
| 1411 |
+
this.#view = null
|
| 1412 |
+
this.sections[this.#index]?.unload?.()
|
| 1413 |
+
this.#mediaQuery.removeEventListener('change', this.#mediaQueryListener)
|
| 1414 |
+
}
|
| 1415 |
+
}
|
| 1416 |
+
|
| 1417 |
+
customElements.define('foliate-paginator', Paginator)
|
packages/foliate-js/pdf.js
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const pdfjsPath = path => `/vendor/pdfjs/${path}`
|
| 2 |
+
|
| 3 |
+
import '@pdfjs/pdf.min.mjs'
|
| 4 |
+
const pdfjsLib = globalThis.pdfjsLib
|
| 5 |
+
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsPath('pdf.worker.min.mjs')
|
| 6 |
+
|
| 7 |
+
const fetchText = async url => await (await fetch(url)).text()
|
| 8 |
+
|
| 9 |
+
let textLayerBuilderCSS = null
|
| 10 |
+
let annotationLayerBuilderCSS = null
|
| 11 |
+
|
| 12 |
+
const render = async (page, doc, zoom) => {
|
| 13 |
+
if (!doc) return
|
| 14 |
+
const scale = zoom * devicePixelRatio
|
| 15 |
+
doc.documentElement.style.transform = `scale(${1 / devicePixelRatio})`
|
| 16 |
+
doc.documentElement.style.transformOrigin = 'top left'
|
| 17 |
+
doc.documentElement.style.setProperty('--total-scale-factor', scale)
|
| 18 |
+
doc.documentElement.style.setProperty('--user-unit', '1')
|
| 19 |
+
doc.documentElement.style.setProperty('--scale-round-x', '1px')
|
| 20 |
+
doc.documentElement.style.setProperty('--scale-round-y', '1px')
|
| 21 |
+
const viewport = page.getViewport({ scale })
|
| 22 |
+
|
| 23 |
+
// the canvas must be in the `PDFDocument`'s `ownerDocument`
|
| 24 |
+
// (`globalThis.document` by default); that's where the fonts are loaded
|
| 25 |
+
const canvas = document.createElement('canvas')
|
| 26 |
+
canvas.height = viewport.height
|
| 27 |
+
canvas.width = viewport.width
|
| 28 |
+
const canvasContext = canvas.getContext('2d')
|
| 29 |
+
await page.render({ canvasContext, viewport }).promise
|
| 30 |
+
const canvasElement = doc.querySelector('#canvas')
|
| 31 |
+
if (!canvasElement) return
|
| 32 |
+
canvasElement.replaceChildren(doc.adoptNode(canvas))
|
| 33 |
+
|
| 34 |
+
const container = doc.querySelector('.textLayer')
|
| 35 |
+
const textLayer = new pdfjsLib.TextLayer({
|
| 36 |
+
textContentSource: await page.streamTextContent(),
|
| 37 |
+
container, viewport,
|
| 38 |
+
})
|
| 39 |
+
await textLayer.render()
|
| 40 |
+
|
| 41 |
+
// hide "offscreen" canvases appended to document when rendering text layer
|
| 42 |
+
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/pdf_viewer.css#L51-L58
|
| 43 |
+
for (const canvas of document.querySelectorAll('.hiddenCanvasElement'))
|
| 44 |
+
Object.assign(canvas.style, {
|
| 45 |
+
position: 'absolute',
|
| 46 |
+
top: '0',
|
| 47 |
+
left: '0',
|
| 48 |
+
width: '0',
|
| 49 |
+
height: '0',
|
| 50 |
+
display: 'none',
|
| 51 |
+
})
|
| 52 |
+
|
| 53 |
+
// fix text selection
|
| 54 |
+
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.js#L105-L107
|
| 55 |
+
const endOfContent = document.createElement('div')
|
| 56 |
+
endOfContent.className = 'endOfContent'
|
| 57 |
+
container.append(endOfContent)
|
| 58 |
+
|
| 59 |
+
let isPanning = false
|
| 60 |
+
let startX = 0
|
| 61 |
+
let startY = 0
|
| 62 |
+
let scrollLeft = 0
|
| 63 |
+
let scrollTop = 0
|
| 64 |
+
let scrollParent = null
|
| 65 |
+
|
| 66 |
+
const findScrollableParent = (element) => {
|
| 67 |
+
let current = element
|
| 68 |
+
while (current) {
|
| 69 |
+
if (current !== document.body && current.nodeType === 1) {
|
| 70 |
+
const style = window.getComputedStyle(current)
|
| 71 |
+
const overflow = style.overflow + style.overflowY + style.overflowX
|
| 72 |
+
if (/(auto|scroll)/.test(overflow)) {
|
| 73 |
+
if (current.scrollHeight > current.clientHeight ||
|
| 74 |
+
current.scrollWidth > current.clientWidth) {
|
| 75 |
+
return current
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
if (current.parentElement) {
|
| 80 |
+
current = current.parentElement
|
| 81 |
+
} else if (current.parentNode && current.parentNode.host) {
|
| 82 |
+
current = current.parentNode.host
|
| 83 |
+
} else {
|
| 84 |
+
break
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
return window
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
container.onpointerdown = (e) => {
|
| 91 |
+
const selection = doc.getSelection()
|
| 92 |
+
const hasTextSelection = selection && selection.toString().length > 0
|
| 93 |
+
|
| 94 |
+
const elementUnderCursor = doc.elementFromPoint(e.clientX, e.clientY)
|
| 95 |
+
const hasTextUnderneath = elementUnderCursor &&
|
| 96 |
+
(elementUnderCursor.tagName === 'SPAN' || elementUnderCursor.tagName === 'P') &&
|
| 97 |
+
elementUnderCursor.textContent.trim().length > 0
|
| 98 |
+
|
| 99 |
+
if (!hasTextUnderneath && !hasTextSelection) {
|
| 100 |
+
isPanning = true
|
| 101 |
+
startX = e.screenX
|
| 102 |
+
startY = e.screenY
|
| 103 |
+
|
| 104 |
+
const iframe = doc.defaultView.frameElement
|
| 105 |
+
if (iframe) {
|
| 106 |
+
scrollParent = findScrollableParent(iframe)
|
| 107 |
+
if (scrollParent === window) {
|
| 108 |
+
scrollLeft = window.scrollX || window.pageXOffset
|
| 109 |
+
scrollTop = window.scrollY || window.pageYOffset
|
| 110 |
+
} else {
|
| 111 |
+
scrollLeft = scrollParent.scrollLeft
|
| 112 |
+
scrollTop = scrollParent.scrollTop
|
| 113 |
+
}
|
| 114 |
+
container.style.cursor = 'grabbing'
|
| 115 |
+
}
|
| 116 |
+
} else {
|
| 117 |
+
container.classList.add('selecting')
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
container.onpointermove = (e) => {
|
| 122 |
+
if (isPanning && scrollParent) {
|
| 123 |
+
e.preventDefault()
|
| 124 |
+
|
| 125 |
+
const dx = e.screenX - startX
|
| 126 |
+
const dy = e.screenY - startY
|
| 127 |
+
|
| 128 |
+
if (scrollParent === window) {
|
| 129 |
+
window.scrollTo(scrollLeft - dx, scrollTop - dy)
|
| 130 |
+
} else {
|
| 131 |
+
scrollParent.scrollLeft = scrollLeft - dx
|
| 132 |
+
scrollParent.scrollTop = scrollTop - dy
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
container.onpointerup = () => {
|
| 138 |
+
if (isPanning) {
|
| 139 |
+
isPanning = false
|
| 140 |
+
scrollParent = null
|
| 141 |
+
container.style.cursor = 'grab'
|
| 142 |
+
} else {
|
| 143 |
+
container.classList.remove('selecting')
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
container.onpointerleave = () => {
|
| 148 |
+
if (isPanning) {
|
| 149 |
+
isPanning = false
|
| 150 |
+
scrollParent = null
|
| 151 |
+
container.style.cursor = 'grab'
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
doc.addEventListener('selectionchange', () => {
|
| 156 |
+
const selection = doc.getSelection()
|
| 157 |
+
if (selection && selection.toString().length > 0) {
|
| 158 |
+
container.style.cursor = 'text'
|
| 159 |
+
} else if (!isPanning) {
|
| 160 |
+
container.style.cursor = 'grab'
|
| 161 |
+
}
|
| 162 |
+
})
|
| 163 |
+
|
| 164 |
+
container.style.cursor = 'grab'
|
| 165 |
+
|
| 166 |
+
const div = doc.querySelector('.annotationLayer')
|
| 167 |
+
const linkService = {
|
| 168 |
+
goToDestination: () => {},
|
| 169 |
+
getDestinationHash: dest => JSON.stringify(dest),
|
| 170 |
+
addLinkAttributes: (link, url) => link.href = url,
|
| 171 |
+
}
|
| 172 |
+
await new pdfjsLib.AnnotationLayer({ page, viewport, div, linkService }).render({
|
| 173 |
+
annotations: await page.getAnnotations(),
|
| 174 |
+
})
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
const renderPage = async (page, getImageBlob) => {
|
| 178 |
+
const viewport = page.getViewport({ scale: 1 })
|
| 179 |
+
if (getImageBlob) {
|
| 180 |
+
const canvas = document.createElement('canvas')
|
| 181 |
+
canvas.height = viewport.height
|
| 182 |
+
canvas.width = viewport.width
|
| 183 |
+
const canvasContext = canvas.getContext('2d')
|
| 184 |
+
await page.render({ canvasContext, viewport }).promise
|
| 185 |
+
return new Promise(resolve => canvas.toBlob(resolve))
|
| 186 |
+
}
|
| 187 |
+
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/text_layer_builder.css
|
| 188 |
+
if (textLayerBuilderCSS == null) {
|
| 189 |
+
textLayerBuilderCSS = await fetchText(pdfjsPath('text_layer_builder.css'))
|
| 190 |
+
}
|
| 191 |
+
// https://github.com/mozilla/pdf.js/blob/642b9a5ae67ef642b9a8808fd9efd447e8c350e2/web/annotation_layer_builder.css
|
| 192 |
+
if (annotationLayerBuilderCSS == null) {
|
| 193 |
+
annotationLayerBuilderCSS = await fetchText(pdfjsPath('annotation_layer_builder.css'))
|
| 194 |
+
}
|
| 195 |
+
const data = `
|
| 196 |
+
<!DOCTYPE html>
|
| 197 |
+
<html lang="en">
|
| 198 |
+
<meta charset="utf-8">
|
| 199 |
+
<meta name="viewport" content="width=${viewport.width}, height=${viewport.height}">
|
| 200 |
+
<style>
|
| 201 |
+
html, body {
|
| 202 |
+
margin: 0;
|
| 203 |
+
padding: 0;
|
| 204 |
+
}
|
| 205 |
+
${textLayerBuilderCSS}
|
| 206 |
+
${annotationLayerBuilderCSS}
|
| 207 |
+
</style>
|
| 208 |
+
<div id="canvas"></div>
|
| 209 |
+
<div class="textLayer"></div>
|
| 210 |
+
<div class="annotationLayer"></div>
|
| 211 |
+
`
|
| 212 |
+
const src = URL.createObjectURL(new Blob([data], { type: 'text/html' }))
|
| 213 |
+
const onZoom = ({ doc, scale }) => render(page, doc, scale)
|
| 214 |
+
return { src, data, onZoom }
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
const makeTOCItem = async (item, pdf) => {
|
| 218 |
+
let pageIndex = undefined
|
| 219 |
+
|
| 220 |
+
if (item.dest) {
|
| 221 |
+
try {
|
| 222 |
+
const dest = typeof item.dest === 'string'
|
| 223 |
+
? await pdf.getDestination(item.dest)
|
| 224 |
+
: item.dest
|
| 225 |
+
if (dest?.[0]) {
|
| 226 |
+
pageIndex = await pdf.getPageIndex(dest[0])
|
| 227 |
+
}
|
| 228 |
+
} catch (e) {
|
| 229 |
+
console.warn('Failed to get page index for TOC item:', item.title, e)
|
| 230 |
+
}
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
return {
|
| 234 |
+
label: item.title,
|
| 235 |
+
href: item.dest ? JSON.stringify(item.dest) : '',
|
| 236 |
+
index: pageIndex,
|
| 237 |
+
subitems: item.items?.length
|
| 238 |
+
? await Promise.all(item.items.map(i => makeTOCItem(i, pdf)))
|
| 239 |
+
: null,
|
| 240 |
+
}
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
export const makePDF = async file => {
|
| 244 |
+
const transport = new pdfjsLib.PDFDataRangeTransport(file.size, [])
|
| 245 |
+
transport.requestDataRange = (begin, end) => {
|
| 246 |
+
file.slice(begin, end).arrayBuffer().then(chunk => {
|
| 247 |
+
transport.onDataRange(begin, chunk)
|
| 248 |
+
})
|
| 249 |
+
}
|
| 250 |
+
const pdf = await pdfjsLib.getDocument({
|
| 251 |
+
range: transport,
|
| 252 |
+
wasmUrl: pdfjsPath(''),
|
| 253 |
+
cMapUrl: pdfjsPath('cmaps/'),
|
| 254 |
+
standardFontDataUrl: pdfjsPath('standard_fonts/'),
|
| 255 |
+
isEvalSupported: false,
|
| 256 |
+
}).promise
|
| 257 |
+
|
| 258 |
+
const book = { rendition: { layout: 'pre-paginated' } }
|
| 259 |
+
|
| 260 |
+
const { metadata, info } = await pdf.getMetadata() ?? {}
|
| 261 |
+
// TODO: for better results, parse `metadata.getRaw()`
|
| 262 |
+
book.metadata = {
|
| 263 |
+
title: metadata?.get('dc:title') ?? info?.Title,
|
| 264 |
+
author: metadata?.get('dc:creator') ?? info?.Author,
|
| 265 |
+
contributor: metadata?.get('dc:contributor'),
|
| 266 |
+
description: metadata?.get('dc:description') ?? info?.Subject,
|
| 267 |
+
language: metadata?.get('dc:language'),
|
| 268 |
+
publisher: metadata?.get('dc:publisher'),
|
| 269 |
+
subject: metadata?.get('dc:subject'),
|
| 270 |
+
identifier: metadata?.get('dc:identifier'),
|
| 271 |
+
source: metadata?.get('dc:source'),
|
| 272 |
+
rights: metadata?.get('dc:rights'),
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
const outline = await pdf.getOutline()
|
| 276 |
+
book.toc = outline ? await Promise.all(outline.map(item => makeTOCItem(item, pdf))) : null
|
| 277 |
+
|
| 278 |
+
const cache = new Map()
|
| 279 |
+
book.sections = Array.from({ length: pdf.numPages }).map((_, i) => ({
|
| 280 |
+
id: i,
|
| 281 |
+
load: async () => {
|
| 282 |
+
const cached = cache.get(i)
|
| 283 |
+
if (cached) return cached
|
| 284 |
+
const url = await renderPage(await pdf.getPage(i + 1))
|
| 285 |
+
cache.set(i, url)
|
| 286 |
+
return url
|
| 287 |
+
},
|
| 288 |
+
size: 1000,
|
| 289 |
+
}))
|
| 290 |
+
book.isExternal = uri => /^\w+:/i.test(uri)
|
| 291 |
+
book.resolveHref = async href => {
|
| 292 |
+
const parsed = JSON.parse(href)
|
| 293 |
+
const dest = typeof parsed === 'string'
|
| 294 |
+
? await pdf.getDestination(parsed) : parsed
|
| 295 |
+
const index = await pdf.getPageIndex(dest[0])
|
| 296 |
+
return { index }
|
| 297 |
+
}
|
| 298 |
+
book.splitTOCHref = async href => {
|
| 299 |
+
if (!href) return [null, null]
|
| 300 |
+
const parsed = JSON.parse(href)
|
| 301 |
+
const dest = typeof parsed === 'string'
|
| 302 |
+
? await pdf.getDestination(parsed) : parsed
|
| 303 |
+
try {
|
| 304 |
+
const index = await pdf.getPageIndex(dest[0])
|
| 305 |
+
return [index, null]
|
| 306 |
+
} catch (e) {
|
| 307 |
+
console.warn('Error getting page index for href', href)
|
| 308 |
+
return [null, null]
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
book.getTOCFragment = doc => doc.documentElement
|
| 312 |
+
book.getCover = async () => renderPage(await pdf.getPage(1), true)
|
| 313 |
+
book.destroy = () => pdf.destroy()
|
| 314 |
+
return book
|
| 315 |
+
}
|
packages/foliate-js/progress.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// assign a unique ID for each TOC item
|
| 2 |
+
const assignIDs = toc => {
|
| 3 |
+
let id = 0
|
| 4 |
+
const assignID = item => {
|
| 5 |
+
item.id = id++
|
| 6 |
+
if (item.subitems) for (const subitem of item.subitems) assignID(subitem)
|
| 7 |
+
}
|
| 8 |
+
for (const item of toc) assignID(item)
|
| 9 |
+
return toc
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
const flatten = items => items
|
| 13 |
+
.map(item => item.subitems?.length
|
| 14 |
+
? [item, flatten(item.subitems)].flat()
|
| 15 |
+
: item)
|
| 16 |
+
.flat()
|
| 17 |
+
|
| 18 |
+
export class TOCProgress {
|
| 19 |
+
async init({ toc, ids, splitHref, getFragment }) {
|
| 20 |
+
assignIDs(toc)
|
| 21 |
+
const items = flatten(toc)
|
| 22 |
+
const grouped = new Map()
|
| 23 |
+
for (const [i, item] of items.entries()) {
|
| 24 |
+
const [id, fragment] = await splitHref(item?.href) ?? []
|
| 25 |
+
const value = { fragment, item }
|
| 26 |
+
if (grouped.has(id)) grouped.get(id).items.push(value)
|
| 27 |
+
else grouped.set(id, { prev: items[i - 1], items: [value] })
|
| 28 |
+
}
|
| 29 |
+
const map = new Map()
|
| 30 |
+
for (const [i, id] of ids.entries()) {
|
| 31 |
+
if (grouped.has(id)) map.set(id, grouped.get(id))
|
| 32 |
+
else map.set(id, map.get(ids[i - 1]))
|
| 33 |
+
}
|
| 34 |
+
this.ids = ids
|
| 35 |
+
this.map = map
|
| 36 |
+
this.getFragment = getFragment
|
| 37 |
+
}
|
| 38 |
+
getProgress(index, range) {
|
| 39 |
+
if (!this.ids) return
|
| 40 |
+
const id = this.ids[index]
|
| 41 |
+
const obj = this.map.get(id)
|
| 42 |
+
if (!obj) return null
|
| 43 |
+
const { prev, items } = obj
|
| 44 |
+
if (!items) return prev
|
| 45 |
+
if (!range || items.length === 1 && !items[0].fragment) return items[0].item
|
| 46 |
+
|
| 47 |
+
const doc = range.startContainer.getRootNode()
|
| 48 |
+
for (const [i, { fragment }] of items.entries()) {
|
| 49 |
+
const el = this.getFragment(doc, fragment)
|
| 50 |
+
if (!el) continue
|
| 51 |
+
if (range.comparePoint(el, 0) > 0)
|
| 52 |
+
return (items[i - 1]?.item ?? prev)
|
| 53 |
+
}
|
| 54 |
+
return items[items.length - 1].item
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
export class SectionProgress {
|
| 59 |
+
constructor(sections, sizePerLoc, sizePerTimeUnit) {
|
| 60 |
+
this.sizes = sections.map(s => s.linear != 'no' && s.size > 0 ? s.size : 0)
|
| 61 |
+
this.sizePerLoc = sizePerLoc
|
| 62 |
+
this.sizePerTimeUnit = sizePerTimeUnit
|
| 63 |
+
this.sizeTotal = this.sizes.reduce((a, b) => a + b, 0)
|
| 64 |
+
this.sectionFractions = this.#getSectionFractions()
|
| 65 |
+
}
|
| 66 |
+
#getSectionFractions() {
|
| 67 |
+
const { sizeTotal } = this
|
| 68 |
+
const results = [0]
|
| 69 |
+
let sum = 0
|
| 70 |
+
for (const size of this.sizes) results.push((sum += size) / sizeTotal)
|
| 71 |
+
return results
|
| 72 |
+
}
|
| 73 |
+
// get progress given index of and fractions within a section
|
| 74 |
+
getProgress(index, fractionInSection, pageFraction = 0) {
|
| 75 |
+
const { sizes, sizePerLoc, sizePerTimeUnit, sizeTotal } = this
|
| 76 |
+
const sizeInSection = sizes[index] ?? 0
|
| 77 |
+
const sizeBefore = sizes.slice(0, index).reduce((a, b) => a + b, 0)
|
| 78 |
+
const size = sizeBefore + fractionInSection * sizeInSection
|
| 79 |
+
const nextSize = size + pageFraction * sizeInSection
|
| 80 |
+
const remainingTotal = sizeTotal - size
|
| 81 |
+
const remainingSection = (1 - fractionInSection) * sizeInSection
|
| 82 |
+
return {
|
| 83 |
+
fraction: nextSize / sizeTotal,
|
| 84 |
+
section: {
|
| 85 |
+
current: index,
|
| 86 |
+
total: sizes.length,
|
| 87 |
+
},
|
| 88 |
+
location: {
|
| 89 |
+
current: Math.floor(size / sizePerLoc),
|
| 90 |
+
next: Math.floor(nextSize / sizePerLoc),
|
| 91 |
+
total: Math.ceil(sizeTotal / sizePerLoc),
|
| 92 |
+
},
|
| 93 |
+
time: {
|
| 94 |
+
section: remainingSection / sizePerTimeUnit,
|
| 95 |
+
total: remainingTotal / sizePerTimeUnit,
|
| 96 |
+
},
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
// the inverse of `getProgress`
|
| 100 |
+
// get index of and fraction in section based on total fraction
|
| 101 |
+
getSection(fraction) {
|
| 102 |
+
if (fraction <= 0) return [0, 0]
|
| 103 |
+
if (fraction >= 1) return [this.sizes.length - 1, 1]
|
| 104 |
+
fraction = fraction + Number.EPSILON
|
| 105 |
+
const { sizeTotal } = this
|
| 106 |
+
let index = this.sectionFractions.findIndex(x => x > fraction) - 1
|
| 107 |
+
if (index < 0) return [0, 0]
|
| 108 |
+
while (!this.sizes[index]) index++
|
| 109 |
+
const fractionInSection = (fraction - this.sectionFractions[index])
|
| 110 |
+
/ (this.sizes[index] / sizeTotal)
|
| 111 |
+
return [index, fractionInSection]
|
| 112 |
+
}
|
| 113 |
+
}
|
packages/foliate-js/quote-image.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const SVG_NS = 'http://www.w3.org/2000/svg'
|
| 2 |
+
|
| 3 |
+
// bisect
|
| 4 |
+
const fit = (el, a = 1, b = 50) => {
|
| 5 |
+
const c = Math.floor(a + (b - a) / 2)
|
| 6 |
+
el.style.fontSize = `${c}px`
|
| 7 |
+
if (b - a === 1) return
|
| 8 |
+
if (el.scrollHeight > el.clientHeight
|
| 9 |
+
|| el.scrollWidth > el.clientWidth) fit(el, a, c)
|
| 10 |
+
else fit(el, c, b)
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
const width = 540
|
| 14 |
+
const height = 540
|
| 15 |
+
const pixelRatio = 2
|
| 16 |
+
|
| 17 |
+
const html = `<style>
|
| 18 |
+
:host {
|
| 19 |
+
position: absolute;
|
| 20 |
+
width: 0;
|
| 21 |
+
height: 0;
|
| 22 |
+
overflow: hidden;
|
| 23 |
+
visibility: hidden;
|
| 24 |
+
}
|
| 25 |
+
</style>
|
| 26 |
+
<main style="width: ${width}px; height: ${height}px; overflow: hidden; display: flex; flex-direction: column; justify-content: center; text-align: center; background: #fff; color: #000; font: 16pt serif">
|
| 27 |
+
<style>
|
| 28 |
+
.ellipsis {
|
| 29 |
+
overflow: hidden;
|
| 30 |
+
display: -webkit-box;
|
| 31 |
+
-webkit-box-orient: vertical;
|
| 32 |
+
-webkit-line-clamp: 2;
|
| 33 |
+
text-overflow: ellipsis;
|
| 34 |
+
}
|
| 35 |
+
</style>
|
| 36 |
+
<div style="font-size: min(4em, 8rem); line-height: 1; margin-bottom: -.5em">“</div>
|
| 37 |
+
<div id="text" style="margin: 1em; text-wrap: balance"></div>
|
| 38 |
+
<div style="margin: 0 1em">
|
| 39 |
+
<div style="font-size: min(.8em, 1.25rem); font-family: sans-serif">
|
| 40 |
+
<div style="display: block; font-weight: bold; margin-bottom: .25em">
|
| 41 |
+
<span id="author" class="ellipsis"></span>
|
| 42 |
+
</div>
|
| 43 |
+
<div style="display: block; text-wrap: balance">
|
| 44 |
+
<cite id="title" class="ellipsis"></cite>
|
| 45 |
+
</div>
|
| 46 |
+
</div>
|
| 47 |
+
</div>
|
| 48 |
+
<div style="height: 1em"> </div>
|
| 49 |
+
</main>`
|
| 50 |
+
|
| 51 |
+
// TODO: lang, vertical writing
|
| 52 |
+
customElements.define('foliate-quoteimage', class extends HTMLElement {
|
| 53 |
+
#root = this.attachShadow({ mode: 'closed' })
|
| 54 |
+
constructor() {
|
| 55 |
+
super()
|
| 56 |
+
this.#root.innerHTML = html
|
| 57 |
+
}
|
| 58 |
+
async getBlob({ title, author, text }) {
|
| 59 |
+
this.#root.querySelector('#title').textContent = title
|
| 60 |
+
this.#root.querySelector('#author').textContent = author
|
| 61 |
+
this.#root.querySelector('#text').innerText = text
|
| 62 |
+
|
| 63 |
+
fit(this.#root.querySelector('main'))
|
| 64 |
+
|
| 65 |
+
const img = document.createElement('img')
|
| 66 |
+
return new Promise(resolve => {
|
| 67 |
+
img.onload = () => {
|
| 68 |
+
const canvas = document.createElement('canvas')
|
| 69 |
+
canvas.width = pixelRatio * width
|
| 70 |
+
canvas.height = pixelRatio * height
|
| 71 |
+
const ctx = canvas.getContext('2d')
|
| 72 |
+
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
|
| 73 |
+
canvas.toBlob(resolve)
|
| 74 |
+
}
|
| 75 |
+
const doc = document.implementation.createDocument(SVG_NS, 'svg')
|
| 76 |
+
doc.documentElement.setAttribute('viewBox', `0 0 ${width} ${height}`)
|
| 77 |
+
const obj = doc.createElementNS(SVG_NS, 'foreignObject')
|
| 78 |
+
obj.setAttribute('width', width)
|
| 79 |
+
obj.setAttribute('height', height)
|
| 80 |
+
obj.append(doc.importNode(this.#root.querySelector('main'), true))
|
| 81 |
+
doc.documentElement.append(obj)
|
| 82 |
+
img.src = 'data:image/svg+xml;charset=utf-8,'
|
| 83 |
+
+ new XMLSerializer().serializeToString(doc)
|
| 84 |
+
})
|
| 85 |
+
}
|
| 86 |
+
})
|
packages/foliate-js/reader.html
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<meta charset="utf-8">
|
| 3 |
+
<meta name="color-scheme" content="light dark">
|
| 4 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 5 |
+
<meta http-equiv="Content-Security-Policy" content="default-src 'self' blob:; script-src 'self'; style-src 'self' blob: 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self' blob: data: *; frame-src blob: data:; object-src blob: data:; form-action 'none';">
|
| 6 |
+
<title>E-Book Reader</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root {
|
| 9 |
+
--active-bg: rgba(0, 0, 0, .05);
|
| 10 |
+
}
|
| 11 |
+
@supports (color-scheme: light dark) {
|
| 12 |
+
@media (prefers-color-scheme: dark) {
|
| 13 |
+
:root {
|
| 14 |
+
--active-bg: rgba(255, 255, 255, .1);
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
html {
|
| 19 |
+
height: 100%;
|
| 20 |
+
}
|
| 21 |
+
body {
|
| 22 |
+
margin: 0 auto;
|
| 23 |
+
height: 100%;
|
| 24 |
+
font: menu;
|
| 25 |
+
font-family: system-ui, sans-serif;
|
| 26 |
+
}
|
| 27 |
+
#drop-target {
|
| 28 |
+
height: 100vh;
|
| 29 |
+
display: flex;
|
| 30 |
+
align-items: center;
|
| 31 |
+
justify-content: center;
|
| 32 |
+
text-align: center;
|
| 33 |
+
visibility: hidden;
|
| 34 |
+
}
|
| 35 |
+
#drop-target h1 {
|
| 36 |
+
font-weight: 900;
|
| 37 |
+
}
|
| 38 |
+
#file-button {
|
| 39 |
+
font: inherit;
|
| 40 |
+
background: none;
|
| 41 |
+
border: 0;
|
| 42 |
+
padding: 0;
|
| 43 |
+
text-decoration: underline;
|
| 44 |
+
cursor: pointer;
|
| 45 |
+
}
|
| 46 |
+
.icon {
|
| 47 |
+
display: block;
|
| 48 |
+
fill: none;
|
| 49 |
+
stroke: currentcolor;
|
| 50 |
+
stroke-width: 2px;
|
| 51 |
+
}
|
| 52 |
+
.empty-state-icon {
|
| 53 |
+
margin: auto;
|
| 54 |
+
}
|
| 55 |
+
.toolbar {
|
| 56 |
+
box-sizing: border-box;
|
| 57 |
+
position: absolute;
|
| 58 |
+
z-index: 1;
|
| 59 |
+
display: flex;
|
| 60 |
+
align-items: center;
|
| 61 |
+
justify-content: space-between;
|
| 62 |
+
width: 100%;
|
| 63 |
+
height: 48px;
|
| 64 |
+
padding: 6px;
|
| 65 |
+
transition: opacity 250ms ease;
|
| 66 |
+
visibility: hidden;
|
| 67 |
+
}
|
| 68 |
+
.toolbar button {
|
| 69 |
+
padding: 3px;
|
| 70 |
+
border-radius: 6px;
|
| 71 |
+
background: none;
|
| 72 |
+
border: 0;
|
| 73 |
+
color: GrayText;
|
| 74 |
+
}
|
| 75 |
+
.toolbar button:hover {
|
| 76 |
+
background: rgba(0, 0, 0, .1);
|
| 77 |
+
color: currentcolor;
|
| 78 |
+
}
|
| 79 |
+
#header-bar {
|
| 80 |
+
top: 0;
|
| 81 |
+
}
|
| 82 |
+
#nav-bar {
|
| 83 |
+
bottom: 0;
|
| 84 |
+
}
|
| 85 |
+
#progress-slider {
|
| 86 |
+
flex-grow: 1;
|
| 87 |
+
margin: 0 12px;
|
| 88 |
+
visibility: hidden;
|
| 89 |
+
}
|
| 90 |
+
#side-bar {
|
| 91 |
+
visibility: hidden;
|
| 92 |
+
box-sizing: border-box;
|
| 93 |
+
position: absolute;
|
| 94 |
+
z-index: 2;
|
| 95 |
+
top: 0;
|
| 96 |
+
left: 0;
|
| 97 |
+
height: 100%;
|
| 98 |
+
width: 320px;
|
| 99 |
+
transform: translateX(-320px);
|
| 100 |
+
display: flex;
|
| 101 |
+
flex-direction: column;
|
| 102 |
+
background: Canvas;
|
| 103 |
+
color: CanvasText;
|
| 104 |
+
box-shadow: 0 0 0 1px rgba(0, 0, 0, .2), 0 0 40px rgba(0, 0, 0, .2);
|
| 105 |
+
transition: visibility 0s linear 300ms, transform 300ms ease;
|
| 106 |
+
}
|
| 107 |
+
#side-bar.show {
|
| 108 |
+
visibility: visible;
|
| 109 |
+
transform: translateX(0);
|
| 110 |
+
transition-delay: 0s;
|
| 111 |
+
}
|
| 112 |
+
#dimming-overlay {
|
| 113 |
+
visibility: hidden;
|
| 114 |
+
position: fixed;
|
| 115 |
+
z-index: 2;
|
| 116 |
+
top: 0;
|
| 117 |
+
left: 0;
|
| 118 |
+
width: 100%;
|
| 119 |
+
height: 100%;
|
| 120 |
+
background: rgba(0, 0, 0, .2);
|
| 121 |
+
opacity: 0;
|
| 122 |
+
transition: visibility 0s linear 300ms, opacity 300ms ease;
|
| 123 |
+
}
|
| 124 |
+
#dimming-overlay.show {
|
| 125 |
+
visibility: visible;
|
| 126 |
+
opacity: 1;
|
| 127 |
+
transition-delay: 0s;
|
| 128 |
+
}
|
| 129 |
+
#side-bar-header {
|
| 130 |
+
padding: 1rem;
|
| 131 |
+
display: flex;
|
| 132 |
+
border-bottom: 1px solid rgba(0, 0, 0, .1);
|
| 133 |
+
align-items: center;
|
| 134 |
+
}
|
| 135 |
+
#side-bar-cover {
|
| 136 |
+
height: 10vh;
|
| 137 |
+
min-height: 60px;
|
| 138 |
+
max-height: 180px;
|
| 139 |
+
border-radius: 3px;
|
| 140 |
+
border: 0;
|
| 141 |
+
background: lightgray;
|
| 142 |
+
box-shadow: 0 0 1px rgba(0, 0, 0, .1), 0 0 16px rgba(0, 0, 0, .1);
|
| 143 |
+
margin-inline-end: 1rem;
|
| 144 |
+
}
|
| 145 |
+
#side-bar-cover:not([src]) {
|
| 146 |
+
display: none;
|
| 147 |
+
}
|
| 148 |
+
#side-bar-title {
|
| 149 |
+
margin: .5rem 0;
|
| 150 |
+
font-size: inherit;
|
| 151 |
+
}
|
| 152 |
+
#side-bar-author {
|
| 153 |
+
margin: .5rem 0;
|
| 154 |
+
font-size: small;
|
| 155 |
+
color: GrayText;
|
| 156 |
+
}
|
| 157 |
+
#toc-view {
|
| 158 |
+
padding: .5rem;
|
| 159 |
+
overflow-y: scroll;
|
| 160 |
+
}
|
| 161 |
+
#toc-view li, #toc-view ol {
|
| 162 |
+
margin: 0;
|
| 163 |
+
padding: 0;
|
| 164 |
+
list-style: none;
|
| 165 |
+
}
|
| 166 |
+
#toc-view a, #toc-view span {
|
| 167 |
+
display: block;
|
| 168 |
+
border-radius: 6px;
|
| 169 |
+
padding: 8px;
|
| 170 |
+
margin: 2px 0;
|
| 171 |
+
}
|
| 172 |
+
#toc-view a {
|
| 173 |
+
color: CanvasText;
|
| 174 |
+
text-decoration: none;
|
| 175 |
+
}
|
| 176 |
+
#toc-view a:hover {
|
| 177 |
+
background: var(--active-bg);
|
| 178 |
+
}
|
| 179 |
+
#toc-view span {
|
| 180 |
+
color: GrayText;
|
| 181 |
+
}
|
| 182 |
+
#toc-view svg {
|
| 183 |
+
margin-inline-start: -24px;
|
| 184 |
+
padding-inline-start: 5px;
|
| 185 |
+
padding-inline-end: 6px;
|
| 186 |
+
fill: CanvasText;
|
| 187 |
+
cursor: default;
|
| 188 |
+
transition: transform .2s ease;
|
| 189 |
+
opacity: .5;
|
| 190 |
+
}
|
| 191 |
+
#toc-view svg:hover {
|
| 192 |
+
opacity: 1;
|
| 193 |
+
}
|
| 194 |
+
#toc-view [aria-current] {
|
| 195 |
+
font-weight: bold;
|
| 196 |
+
background: var(--active-bg);
|
| 197 |
+
}
|
| 198 |
+
#toc-view [aria-expanded="false"] svg {
|
| 199 |
+
transform: rotate(-90deg);
|
| 200 |
+
}
|
| 201 |
+
#toc-view [aria-expanded="false"] + [role="group"] {
|
| 202 |
+
display: none;
|
| 203 |
+
}
|
| 204 |
+
.menu-container {
|
| 205 |
+
position: relative;
|
| 206 |
+
}
|
| 207 |
+
.menu, .menu ul {
|
| 208 |
+
list-style: none;
|
| 209 |
+
padding: 0;
|
| 210 |
+
margin: 0;
|
| 211 |
+
}
|
| 212 |
+
.menu {
|
| 213 |
+
visibility: hidden;
|
| 214 |
+
position: absolute;
|
| 215 |
+
right: 0;
|
| 216 |
+
background: Canvas;
|
| 217 |
+
color: CanvasText;
|
| 218 |
+
border-radius: 6px;
|
| 219 |
+
box-shadow: 0 0 0 1px rgba(0, 0, 0, .2), 0 0 16px rgba(0, 0, 0, .1);
|
| 220 |
+
padding: 6px;
|
| 221 |
+
cursor: default;
|
| 222 |
+
}
|
| 223 |
+
.menu.show {
|
| 224 |
+
visibility: visible;
|
| 225 |
+
}
|
| 226 |
+
.menu li {
|
| 227 |
+
padding: 6px 12px;
|
| 228 |
+
padding-left: 24px;
|
| 229 |
+
border-radius: 6px;
|
| 230 |
+
}
|
| 231 |
+
.menu li:hover {
|
| 232 |
+
background: var(--active-bg);
|
| 233 |
+
}
|
| 234 |
+
.menu li[aria-checked="true"] {
|
| 235 |
+
background-position: center left;
|
| 236 |
+
background-repeat: no-repeat;
|
| 237 |
+
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%223%22%2F%3E%3C%2Fsvg%3E');
|
| 238 |
+
}
|
| 239 |
+
.popover {
|
| 240 |
+
background: Canvas;
|
| 241 |
+
color: CanvasText;
|
| 242 |
+
border-radius: 6px;
|
| 243 |
+
box-shadow: 0 0 0 1px rgba(0, 0, 0, .2), 0 0 16px rgba(0, 0, 0, .1), 0 0 32px rgba(0, 0, 0, .1);
|
| 244 |
+
}
|
| 245 |
+
.popover-arrow-down {
|
| 246 |
+
fill: Canvas;
|
| 247 |
+
filter: drop-shadow(0 -1px 0 rgba(0, 0, 0, .2));
|
| 248 |
+
}
|
| 249 |
+
.popover-arrow-up {
|
| 250 |
+
fill: Canvas;
|
| 251 |
+
filter: drop-shadow(0 1px 0 rgba(0, 0, 0, .2));
|
| 252 |
+
}
|
| 253 |
+
</style>
|
| 254 |
+
<input type="file" id="file-input" hidden>
|
| 255 |
+
<div id="drop-target" class="filter">
|
| 256 |
+
<div>
|
| 257 |
+
<svg class="icon empty-state-icon" width="72" height="72" aria-hidden="true">
|
| 258 |
+
<path d="M36 18s-6-6-12-6-15 6-15 6v42s9-6 15-6 12 6 12 6c4-4 8-6 12-6s12 2 15 6V18c-6-4-12-6-15-6-4 0-8 2-12 6m0 0v42"/>
|
| 259 |
+
</svg>
|
| 260 |
+
<h1>Drop a book here!</h1>
|
| 261 |
+
<p>Or <button id="file-button">choose a file</button> to open it.</p>
|
| 262 |
+
</div>
|
| 263 |
+
</div>
|
| 264 |
+
<div id="dimming-overlay" aria-hidden="true"></div>
|
| 265 |
+
<div id="side-bar">
|
| 266 |
+
<div id="side-bar-header">
|
| 267 |
+
<img id="side-bar-cover">
|
| 268 |
+
<div>
|
| 269 |
+
<h1 id="side-bar-title"></h1>
|
| 270 |
+
<p id="side-bar-author"></p>
|
| 271 |
+
</div>
|
| 272 |
+
</div>
|
| 273 |
+
<div id="toc-view"></div>
|
| 274 |
+
</div>
|
| 275 |
+
<div id="header-bar" class="toolbar">
|
| 276 |
+
<button id="side-bar-button" aria-label="Show sidebar">
|
| 277 |
+
<svg class="icon" width="24" height="24" aria-hidden="true">
|
| 278 |
+
<path d="M 4 6 h 16 M 4 12 h 16 M 4 18 h 16"/>
|
| 279 |
+
</svg>
|
| 280 |
+
</button>
|
| 281 |
+
<div id="menu-button" class="menu-container">
|
| 282 |
+
<button aria-label="Show settings" aria-haspopup="true">
|
| 283 |
+
<svg class="icon" width="24" height="24" aria-hidden="true">
|
| 284 |
+
<path d="M5 12.7a7 7 0 0 1 0-1.4l-1.8-2 2-3.5 2.7.5a7 7 0 0 1 1.2-.7L10 3h4l.9 2.6 1.2.7 2.7-.5 2 3.4-1.8 2a7 7 0 0 1 0 1.5l1.8 2-2 3.5-2.7-.5a7 7 0 0 1-1.2.7L14 21h-4l-.9-2.6a7 7 0 0 1-1.2-.7l-2.7.5-2-3.4 1.8-2Z"/>
|
| 285 |
+
<circle cx="12" cy="12" r="3"/>
|
| 286 |
+
</svg>
|
| 287 |
+
</button>
|
| 288 |
+
</div>
|
| 289 |
+
</div>
|
| 290 |
+
<div id="nav-bar" class="toolbar">
|
| 291 |
+
<button id="left-button" aria-label="Go left">
|
| 292 |
+
<svg class="icon" width="24" height="24" aria-hidden="true">
|
| 293 |
+
<path d="M 15 6 L 9 12 L 15 18"/>
|
| 294 |
+
</svg>
|
| 295 |
+
</button>
|
| 296 |
+
<input id="progress-slider" type="range" min="0" max="1" step="any" list="tick-marks">
|
| 297 |
+
<datalist id="tick-marks"></datalist>
|
| 298 |
+
<button id="right-button" aria-label="Go right">
|
| 299 |
+
<svg class="icon" width="24" height="24" aria-hidden="true">
|
| 300 |
+
<path d="M 9 6 L 15 12 L 9 18"/>
|
| 301 |
+
</svg>
|
| 302 |
+
</button>
|
| 303 |
+
</div>
|
| 304 |
+
<script src="reader.js" type="module"></script>
|
packages/foliate-js/reader.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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createTOCView } from './ui/tree.js'
|
| 3 |
+
import { createMenu } from './ui/menu.js'
|
| 4 |
+
import { Overlayer } from './overlayer.js'
|
| 5 |
+
|
| 6 |
+
const getCSS = ({ spacing, justify, hyphenate }) => `
|
| 7 |
+
@namespace epub "http://www.idpf.org/2007/ops";
|
| 8 |
+
html {
|
| 9 |
+
color-scheme: light dark;
|
| 10 |
+
}
|
| 11 |
+
/* https://github.com/whatwg/html/issues/5426 */
|
| 12 |
+
@media (prefers-color-scheme: dark) {
|
| 13 |
+
a:link {
|
| 14 |
+
color: lightblue;
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
p, li, blockquote, dd {
|
| 18 |
+
line-height: ${spacing};
|
| 19 |
+
text-align: ${justify ? 'justify' : 'start'};
|
| 20 |
+
-webkit-hyphens: ${hyphenate ? 'auto' : 'manual'};
|
| 21 |
+
hyphens: ${hyphenate ? 'auto' : 'manual'};
|
| 22 |
+
-webkit-hyphenate-limit-before: 3;
|
| 23 |
+
-webkit-hyphenate-limit-after: 2;
|
| 24 |
+
-webkit-hyphenate-limit-lines: 2;
|
| 25 |
+
hanging-punctuation: allow-end last;
|
| 26 |
+
widows: 2;
|
| 27 |
+
}
|
| 28 |
+
/* prevent the above from overriding the align attribute */
|
| 29 |
+
[align="left"] { text-align: left; }
|
| 30 |
+
[align="right"] { text-align: right; }
|
| 31 |
+
[align="center"] { text-align: center; }
|
| 32 |
+
[align="justify"] { text-align: justify; }
|
| 33 |
+
|
| 34 |
+
pre {
|
| 35 |
+
white-space: pre-wrap !important;
|
| 36 |
+
}
|
| 37 |
+
aside[epub|type~="endnote"],
|
| 38 |
+
aside[epub|type~="footnote"],
|
| 39 |
+
aside[epub|type~="note"],
|
| 40 |
+
aside[epub|type~="rearnote"] {
|
| 41 |
+
display: none;
|
| 42 |
+
}
|
| 43 |
+
`
|
| 44 |
+
|
| 45 |
+
const $ = document.querySelector.bind(document)
|
| 46 |
+
|
| 47 |
+
const locales = 'en'
|
| 48 |
+
const percentFormat = new Intl.NumberFormat(locales, { style: 'percent' })
|
| 49 |
+
const listFormat = new Intl.ListFormat(locales, { style: 'short', type: 'conjunction' })
|
| 50 |
+
|
| 51 |
+
const formatLanguageMap = x => {
|
| 52 |
+
if (!x) return ''
|
| 53 |
+
if (typeof x === 'string') return x
|
| 54 |
+
const keys = Object.keys(x)
|
| 55 |
+
return x[keys[0]]
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
const formatOneContributor = contributor => typeof contributor === 'string'
|
| 59 |
+
? contributor : formatLanguageMap(contributor?.name)
|
| 60 |
+
|
| 61 |
+
const formatContributor = contributor => Array.isArray(contributor)
|
| 62 |
+
? listFormat.format(contributor.map(formatOneContributor))
|
| 63 |
+
: formatOneContributor(contributor)
|
| 64 |
+
|
| 65 |
+
class Reader {
|
| 66 |
+
#tocView
|
| 67 |
+
style = {
|
| 68 |
+
spacing: 1.4,
|
| 69 |
+
justify: true,
|
| 70 |
+
hyphenate: true,
|
| 71 |
+
}
|
| 72 |
+
annotations = new Map()
|
| 73 |
+
annotationsByValue = new Map()
|
| 74 |
+
closeSideBar() {
|
| 75 |
+
$('#dimming-overlay').classList.remove('show')
|
| 76 |
+
$('#side-bar').classList.remove('show')
|
| 77 |
+
}
|
| 78 |
+
constructor() {
|
| 79 |
+
$('#side-bar-button').addEventListener('click', () => {
|
| 80 |
+
$('#dimming-overlay').classList.add('show')
|
| 81 |
+
$('#side-bar').classList.add('show')
|
| 82 |
+
})
|
| 83 |
+
$('#dimming-overlay').addEventListener('click', () => this.closeSideBar())
|
| 84 |
+
|
| 85 |
+
const menu = createMenu([
|
| 86 |
+
{
|
| 87 |
+
name: 'layout',
|
| 88 |
+
label: 'Layout',
|
| 89 |
+
type: 'radio',
|
| 90 |
+
items: [
|
| 91 |
+
['Paginated', 'paginated'],
|
| 92 |
+
['Scrolled', 'scrolled'],
|
| 93 |
+
],
|
| 94 |
+
onclick: value => {
|
| 95 |
+
this.view?.renderer.setAttribute('flow', value)
|
| 96 |
+
},
|
| 97 |
+
},
|
| 98 |
+
])
|
| 99 |
+
menu.element.classList.add('menu')
|
| 100 |
+
|
| 101 |
+
$('#menu-button').append(menu.element)
|
| 102 |
+
$('#menu-button > button').addEventListener('click', () =>
|
| 103 |
+
menu.element.classList.toggle('show'))
|
| 104 |
+
menu.groups.layout.select('paginated')
|
| 105 |
+
}
|
| 106 |
+
async open(file) {
|
| 107 |
+
this.view = document.createElement('foliate-view')
|
| 108 |
+
document.body.append(this.view)
|
| 109 |
+
await this.view.open(file)
|
| 110 |
+
this.view.addEventListener('load', this.#onLoad.bind(this))
|
| 111 |
+
this.view.addEventListener('relocate', this.#onRelocate.bind(this))
|
| 112 |
+
|
| 113 |
+
const { book } = this.view
|
| 114 |
+
book.transformTarget?.addEventListener('data', ({ detail }) => {
|
| 115 |
+
detail.data = Promise.resolve(detail.data).catch(e => {
|
| 116 |
+
console.error(new Error(`Failed to load ${detail.name}`, { cause: e }))
|
| 117 |
+
return ''
|
| 118 |
+
})
|
| 119 |
+
})
|
| 120 |
+
this.view.renderer.setStyles?.(getCSS(this.style))
|
| 121 |
+
this.view.renderer.next()
|
| 122 |
+
|
| 123 |
+
$('#header-bar').style.visibility = 'visible'
|
| 124 |
+
$('#nav-bar').style.visibility = 'visible'
|
| 125 |
+
$('#left-button').addEventListener('click', () => this.view.goLeft())
|
| 126 |
+
$('#right-button').addEventListener('click', () => this.view.goRight())
|
| 127 |
+
|
| 128 |
+
const slider = $('#progress-slider')
|
| 129 |
+
slider.dir = book.dir
|
| 130 |
+
slider.addEventListener('input', e =>
|
| 131 |
+
this.view.goToFraction(parseFloat(e.target.value)))
|
| 132 |
+
for (const fraction of this.view.getSectionFractions()) {
|
| 133 |
+
const option = document.createElement('option')
|
| 134 |
+
option.value = fraction
|
| 135 |
+
$('#tick-marks').append(option)
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
document.addEventListener('keydown', this.#handleKeydown.bind(this))
|
| 139 |
+
|
| 140 |
+
const title = formatLanguageMap(book.metadata?.title) || 'Untitled Book'
|
| 141 |
+
document.title = title
|
| 142 |
+
$('#side-bar-title').innerText = title
|
| 143 |
+
$('#side-bar-author').innerText = formatContributor(book.metadata?.author)
|
| 144 |
+
Promise.resolve(book.getCover?.())?.then(blob =>
|
| 145 |
+
blob ? $('#side-bar-cover').src = URL.createObjectURL(blob) : null)
|
| 146 |
+
|
| 147 |
+
const toc = book.toc
|
| 148 |
+
if (toc) {
|
| 149 |
+
this.#tocView = createTOCView(toc, href => {
|
| 150 |
+
this.view.goTo(href).catch(e => console.error(e))
|
| 151 |
+
this.closeSideBar()
|
| 152 |
+
})
|
| 153 |
+
$('#toc-view').append(this.#tocView.element)
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
// load and show highlights embedded in the file by Calibre
|
| 157 |
+
const bookmarks = await book.getCalibreBookmarks?.()
|
| 158 |
+
if (bookmarks) {
|
| 159 |
+
const { fromCalibreHighlight } = await import('./epubcfi.js')
|
| 160 |
+
for (const obj of bookmarks) {
|
| 161 |
+
if (obj.type === 'highlight') {
|
| 162 |
+
const value = fromCalibreHighlight(obj)
|
| 163 |
+
const color = obj.style.which
|
| 164 |
+
const note = obj.notes
|
| 165 |
+
const annotation = { value, color, note }
|
| 166 |
+
const list = this.annotations.get(obj.spine_index)
|
| 167 |
+
if (list) list.push(annotation)
|
| 168 |
+
else this.annotations.set(obj.spine_index, [annotation])
|
| 169 |
+
this.annotationsByValue.set(value, annotation)
|
| 170 |
+
}
|
| 171 |
+
}
|
| 172 |
+
this.view.addEventListener('create-overlay', e => {
|
| 173 |
+
const { index } = e.detail
|
| 174 |
+
const list = this.annotations.get(index)
|
| 175 |
+
if (list) for (const annotation of list)
|
| 176 |
+
this.view.addAnnotation(annotation)
|
| 177 |
+
})
|
| 178 |
+
this.view.addEventListener('draw-annotation', e => {
|
| 179 |
+
const { draw, annotation } = e.detail
|
| 180 |
+
const { color } = annotation
|
| 181 |
+
draw(Overlayer.highlight, { color })
|
| 182 |
+
})
|
| 183 |
+
this.view.addEventListener('show-annotation', e => {
|
| 184 |
+
const annotation = this.annotationsByValue.get(e.detail.value)
|
| 185 |
+
if (annotation.note) alert(annotation.note)
|
| 186 |
+
})
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
#handleKeydown(event) {
|
| 190 |
+
const k = event.key
|
| 191 |
+
if (k === 'ArrowLeft' || k === 'h') this.view.goLeft()
|
| 192 |
+
else if(k === 'ArrowRight' || k === 'l') this.view.goRight()
|
| 193 |
+
}
|
| 194 |
+
#onLoad({ detail: { doc } }) {
|
| 195 |
+
doc.addEventListener('keydown', this.#handleKeydown.bind(this))
|
| 196 |
+
}
|
| 197 |
+
#onRelocate({ detail }) {
|
| 198 |
+
const { fraction, location, tocItem, pageItem } = detail
|
| 199 |
+
const percent = percentFormat.format(fraction)
|
| 200 |
+
const loc = pageItem
|
| 201 |
+
? `Page ${pageItem.label}`
|
| 202 |
+
: `Loc ${location.current}`
|
| 203 |
+
const slider = $('#progress-slider')
|
| 204 |
+
slider.style.visibility = 'visible'
|
| 205 |
+
slider.value = fraction
|
| 206 |
+
slider.title = `${percent} · ${loc}`
|
| 207 |
+
if (tocItem?.href) this.#tocView?.setCurrentHref?.(tocItem.href)
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
const open = async file => {
|
| 212 |
+
document.body.removeChild($('#drop-target'))
|
| 213 |
+
const reader = new Reader()
|
| 214 |
+
globalThis.reader = reader
|
| 215 |
+
await reader.open(file)
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
const dragOverHandler = e => e.preventDefault()
|
| 219 |
+
const dropHandler = e => {
|
| 220 |
+
e.preventDefault()
|
| 221 |
+
const item = Array.from(e.dataTransfer.items)
|
| 222 |
+
.find(item => item.kind === 'file')
|
| 223 |
+
if (item) {
|
| 224 |
+
const entry = item.webkitGetAsEntry()
|
| 225 |
+
open(entry.isFile ? item.getAsFile() : entry).catch(e => console.error(e))
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
const dropTarget = $('#drop-target')
|
| 229 |
+
dropTarget.addEventListener('drop', dropHandler)
|
| 230 |
+
dropTarget.addEventListener('dragover', dragOverHandler)
|
| 231 |
+
|
| 232 |
+
$('#file-input').addEventListener('change', e =>
|
| 233 |
+
open(e.target.files[0]).catch(e => console.error(e)))
|
| 234 |
+
$('#file-button').addEventListener('click', () => $('#file-input').click())
|
| 235 |
+
|
| 236 |
+
const params = new URLSearchParams(location.search)
|
| 237 |
+
const url = params.get('url')
|
| 238 |
+
if (url) open(url).catch(e => console.error(e))
|
| 239 |
+
else dropTarget.style.visibility = 'visible'
|
packages/foliate-js/rollup.config.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { nodeResolve } from '@rollup/plugin-node-resolve'
|
| 2 |
+
import terser from '@rollup/plugin-terser'
|
| 3 |
+
import { copy } from 'fs-extra'
|
| 4 |
+
|
| 5 |
+
const copyPDFJS = () => ({
|
| 6 |
+
name: 'copy-pdfjs',
|
| 7 |
+
async writeBundle() {
|
| 8 |
+
await copy('node_modules/pdfjs-dist/build/pdf.mjs', 'vendor/pdfjs/pdf.mjs')
|
| 9 |
+
await copy('node_modules/pdfjs-dist/build/pdf.mjs.map', 'vendor/pdfjs/pdf.mjs.map')
|
| 10 |
+
await copy('node_modules/pdfjs-dist/build/pdf.worker.mjs', 'vendor/pdfjs/pdf.worker.mjs')
|
| 11 |
+
await copy('node_modules/pdfjs-dist/build/pdf.worker.mjs.map', 'vendor/pdfjs/pdf.worker.mjs.map')
|
| 12 |
+
await copy('node_modules/pdfjs-dist/cmaps', 'vendor/pdfjs/cmaps')
|
| 13 |
+
await copy('node_modules/pdfjs-dist/standard_fonts', 'vendor/pdfjs/standard_fonts')
|
| 14 |
+
},
|
| 15 |
+
})
|
| 16 |
+
|
| 17 |
+
export default [{
|
| 18 |
+
input: 'rollup/fflate.js',
|
| 19 |
+
output: {
|
| 20 |
+
dir: 'vendor/',
|
| 21 |
+
format: 'esm',
|
| 22 |
+
},
|
| 23 |
+
plugins: [nodeResolve(), terser()],
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
input: 'rollup/zip.js',
|
| 27 |
+
output: {
|
| 28 |
+
dir: 'vendor/',
|
| 29 |
+
format: 'esm',
|
| 30 |
+
},
|
| 31 |
+
plugins: [nodeResolve(), terser(), copyPDFJS()],
|
| 32 |
+
}]
|
packages/foliate-js/rollup/fflate.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export { unzlibSync } from 'fflate'
|
packages/foliate-js/rollup/zip.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
export { configure, ZipReader, BlobReader, TextWriter, BlobWriter } from '../node_modules/@zip.js/zip.js/lib/zip-no-worker-inflate.js'
|
packages/foliate-js/search.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// length for context in excerpts
|
| 2 |
+
const CONTEXT_LENGTH = 50
|
| 3 |
+
|
| 4 |
+
const normalizeWhitespace = str => str.replace(/\s+/g, ' ')
|
| 5 |
+
|
| 6 |
+
const makeExcerpt = (strs, { startIndex, startOffset, endIndex, endOffset }) => {
|
| 7 |
+
const start = strs[startIndex]
|
| 8 |
+
const end = strs[endIndex]
|
| 9 |
+
const match = start === end
|
| 10 |
+
? start.slice(startOffset, endOffset)
|
| 11 |
+
: start.slice(startOffset)
|
| 12 |
+
+ strs.slice(start + 1, end).join('')
|
| 13 |
+
+ end.slice(0, endOffset)
|
| 14 |
+
const trimmedStart = normalizeWhitespace(start.slice(0, startOffset)).trimStart()
|
| 15 |
+
const trimmedEnd = normalizeWhitespace(end.slice(endOffset)).trimEnd()
|
| 16 |
+
const ellipsisPre = trimmedStart.length < CONTEXT_LENGTH ? '' : '…'
|
| 17 |
+
const ellipsisPost = trimmedEnd.length < CONTEXT_LENGTH ? '' : '…'
|
| 18 |
+
const pre = `${ellipsisPre}${trimmedStart.slice(-CONTEXT_LENGTH)}`
|
| 19 |
+
const post = `${trimmedEnd.slice(0, CONTEXT_LENGTH)}${ellipsisPost}`
|
| 20 |
+
return { pre, match, post }
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
const simpleSearch = function* (strs, query, options = {}) {
|
| 24 |
+
const { locales = 'en', sensitivity } = options
|
| 25 |
+
const matchCase = sensitivity === 'variant'
|
| 26 |
+
const haystack = strs.join('')
|
| 27 |
+
const lowerHaystack = matchCase ? haystack : haystack.toLocaleLowerCase(locales)
|
| 28 |
+
const needle = matchCase ? query : query.toLocaleLowerCase(locales)
|
| 29 |
+
const needleLength = needle.length
|
| 30 |
+
let index = -1
|
| 31 |
+
let strIndex = -1
|
| 32 |
+
let sum = 0
|
| 33 |
+
do {
|
| 34 |
+
index = lowerHaystack.indexOf(needle, index + 1)
|
| 35 |
+
if (index > -1) {
|
| 36 |
+
while (sum <= index) sum += strs[++strIndex].length
|
| 37 |
+
const startIndex = strIndex
|
| 38 |
+
const startOffset = index - (sum - strs[strIndex].length)
|
| 39 |
+
const end = index + needleLength
|
| 40 |
+
while (sum <= end) sum += strs[++strIndex].length
|
| 41 |
+
const endIndex = strIndex
|
| 42 |
+
const endOffset = end - (sum - strs[strIndex].length)
|
| 43 |
+
const range = { startIndex, startOffset, endIndex, endOffset }
|
| 44 |
+
yield { range, excerpt: makeExcerpt(strs, range) }
|
| 45 |
+
}
|
| 46 |
+
} while (index > -1)
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
const segmenterSearch = function* (strs, query, options = {}) {
|
| 50 |
+
const { locales = 'en', granularity = 'word', sensitivity = 'base' } = options
|
| 51 |
+
let segmenter, collator
|
| 52 |
+
try {
|
| 53 |
+
segmenter = new Intl.Segmenter(locales, { usage: 'search', granularity })
|
| 54 |
+
collator = new Intl.Collator(locales, { sensitivity })
|
| 55 |
+
} catch (e) {
|
| 56 |
+
console.warn(e)
|
| 57 |
+
segmenter = new Intl.Segmenter('en', { usage: 'search', granularity })
|
| 58 |
+
collator = new Intl.Collator('en', { sensitivity })
|
| 59 |
+
}
|
| 60 |
+
const queryLength = Array.from(segmenter.segment(query)).length
|
| 61 |
+
|
| 62 |
+
const substrArr = []
|
| 63 |
+
let strIndex = 0
|
| 64 |
+
let segments = segmenter.segment(strs[strIndex])[Symbol.iterator]()
|
| 65 |
+
main: while (strIndex < strs.length) {
|
| 66 |
+
while (substrArr.length < queryLength) {
|
| 67 |
+
const { done, value } = segments.next()
|
| 68 |
+
if (done) {
|
| 69 |
+
// the current string is exhausted
|
| 70 |
+
// move on to the next string
|
| 71 |
+
strIndex++
|
| 72 |
+
if (strIndex < strs.length) {
|
| 73 |
+
segments = segmenter.segment(strs[strIndex])[Symbol.iterator]()
|
| 74 |
+
continue
|
| 75 |
+
} else break main
|
| 76 |
+
}
|
| 77 |
+
const { index, segment } = value
|
| 78 |
+
// ignore formatting characters
|
| 79 |
+
if (!/[^\p{Format}]/u.test(segment)) continue
|
| 80 |
+
// normalize whitespace
|
| 81 |
+
if (/\s/u.test(segment)) {
|
| 82 |
+
if (!/\s/u.test(substrArr[substrArr.length - 1]?.segment))
|
| 83 |
+
substrArr.push({ strIndex, index, segment: ' ' })
|
| 84 |
+
continue
|
| 85 |
+
}
|
| 86 |
+
value.strIndex = strIndex
|
| 87 |
+
substrArr.push(value)
|
| 88 |
+
}
|
| 89 |
+
const substr = substrArr.map(x => x.segment).join('')
|
| 90 |
+
if (collator.compare(query, substr) === 0) {
|
| 91 |
+
const endIndex = strIndex
|
| 92 |
+
const lastSeg = substrArr[substrArr.length - 1]
|
| 93 |
+
const endOffset = lastSeg.index + lastSeg.segment.length
|
| 94 |
+
const startIndex = substrArr[0].strIndex
|
| 95 |
+
const startOffset = substrArr[0].index
|
| 96 |
+
const range = { startIndex, startOffset, endIndex, endOffset }
|
| 97 |
+
yield { range, excerpt: makeExcerpt(strs, range) }
|
| 98 |
+
}
|
| 99 |
+
substrArr.shift()
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
export const search = (strs, query, options) => {
|
| 104 |
+
const { granularity = 'grapheme', sensitivity = 'base' } = options
|
| 105 |
+
if (!Intl?.Segmenter || granularity === 'grapheme'
|
| 106 |
+
&& (sensitivity === 'variant' || sensitivity === 'accent'))
|
| 107 |
+
return simpleSearch(strs, query, options)
|
| 108 |
+
return segmenterSearch(strs, query, options)
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
export const searchMatcher = (textWalker, opts) => {
|
| 112 |
+
const { defaultLocale, matchCase, matchDiacritics, matchWholeWords, acceptNode } = opts
|
| 113 |
+
return function* (doc, query) {
|
| 114 |
+
const iter = textWalker(doc, function* (strs, makeRange) {
|
| 115 |
+
for (const result of search(strs, query, {
|
| 116 |
+
locales: doc.body.lang || doc.documentElement.lang || defaultLocale || 'en',
|
| 117 |
+
granularity: matchWholeWords ? 'word' : 'grapheme',
|
| 118 |
+
sensitivity: matchDiacritics && matchCase ? 'variant'
|
| 119 |
+
: matchDiacritics && !matchCase ? 'accent'
|
| 120 |
+
: !matchDiacritics && matchCase ? 'case'
|
| 121 |
+
: 'base',
|
| 122 |
+
})) {
|
| 123 |
+
const { startIndex, startOffset, endIndex, endOffset } = result.range
|
| 124 |
+
result.range = makeRange(startIndex, startOffset, endIndex, endOffset)
|
| 125 |
+
yield result
|
| 126 |
+
}
|
| 127 |
+
}, acceptNode)
|
| 128 |
+
for (const result of iter) yield result
|
| 129 |
+
}
|
| 130 |
+
}
|
packages/foliate-js/tests/epubcfi-tests.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as CFI from '../epubcfi.js'
|
| 2 |
+
|
| 3 |
+
const parser = new DOMParser()
|
| 4 |
+
const XML = str => parser.parseFromString(str, 'application/xml')
|
| 5 |
+
const XHTML = str => parser.parseFromString(str, 'application/xhtml+xml')
|
| 6 |
+
|
| 7 |
+
{
|
| 8 |
+
// example from EPUB CFI spec
|
| 9 |
+
const opf = XML(`<?xml version="1.0"?>
|
| 10 |
+
|
| 11 |
+
<package version="2.0"
|
| 12 |
+
unique-identifier="bookid"
|
| 13 |
+
xmlns="http://www.idpf.org/2007/opf"
|
| 14 |
+
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
| 15 |
+
xmlns:opf="http://www.idpf.org/2007/opf">
|
| 16 |
+
|
| 17 |
+
<metadata>
|
| 18 |
+
<dc:title>…</dc:title>
|
| 19 |
+
<dc:identifier id="bookid">…</dc:identifier>
|
| 20 |
+
<dc:creator>…</dc:creator>
|
| 21 |
+
<dc:language>en</dc:language>
|
| 22 |
+
</metadata>
|
| 23 |
+
|
| 24 |
+
<manifest>
|
| 25 |
+
<item id="toc"
|
| 26 |
+
properties="nav"
|
| 27 |
+
href="toc.xhtml"
|
| 28 |
+
media-type="application/xhtml+xml"/>
|
| 29 |
+
<item id="titlepage"
|
| 30 |
+
href="titlepage.xhtml"
|
| 31 |
+
media-type="application/xhtml+xml"/>
|
| 32 |
+
<item id="chapter01"
|
| 33 |
+
href="chapter01.xhtml"
|
| 34 |
+
media-type="application/xhtml+xml"/>
|
| 35 |
+
<item id="chapter02"
|
| 36 |
+
href="chapter02.xhtml"
|
| 37 |
+
media-type="application/xhtml+xml"/>
|
| 38 |
+
<item id="chapter03"
|
| 39 |
+
href="chapter03.xhtml"
|
| 40 |
+
media-type="application/xhtml+xml"/>
|
| 41 |
+
<item id="chapter04"
|
| 42 |
+
href="chapter04.xhtml"
|
| 43 |
+
media-type="application/xhtml+xml"/>
|
| 44 |
+
</manifest>
|
| 45 |
+
|
| 46 |
+
<spine>
|
| 47 |
+
<itemref id="titleref" idref="titlepage"/>
|
| 48 |
+
<itemref id="chap01ref" idref="chapter01"/>
|
| 49 |
+
<itemref id="chap02ref" idref="chapter02"/>
|
| 50 |
+
<itemref id="chap03ref" idref="chapter03"/>
|
| 51 |
+
<itemref id="chap04ref" idref="chapter04"/>
|
| 52 |
+
</spine>
|
| 53 |
+
|
| 54 |
+
</package>`)
|
| 55 |
+
|
| 56 |
+
const a = opf.getElementById('chap01ref')
|
| 57 |
+
const b = CFI.toElement(opf, CFI.parse('/6/4[chap01ref]')[0])
|
| 58 |
+
const c = CFI.toElement(opf, CFI.parse('/6/4')[0])
|
| 59 |
+
console.assert(a === b)
|
| 60 |
+
console.assert(a === c)
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
{
|
| 64 |
+
// example from EPUB CFI spec
|
| 65 |
+
const page = XHTML(`<html xmlns="http://www.w3.org/1999/xhtml">
|
| 66 |
+
<head>
|
| 67 |
+
<title>…</title>
|
| 68 |
+
</head>
|
| 69 |
+
|
| 70 |
+
<body id="body01">
|
| 71 |
+
<p>…</p>
|
| 72 |
+
<p>…</p>
|
| 73 |
+
<p>…</p>
|
| 74 |
+
<p>…</p>
|
| 75 |
+
<p id="para05">xxx<em>yyy</em>0123456789</p>
|
| 76 |
+
<p>…</p>
|
| 77 |
+
<p>…</p>
|
| 78 |
+
<img id="svgimg" src="foo.svg" alt="…"/>
|
| 79 |
+
<p>…</p>
|
| 80 |
+
<p>…</p>
|
| 81 |
+
</body>
|
| 82 |
+
</html>`)
|
| 83 |
+
|
| 84 |
+
// the exact same page with some text nodes removed, CDATA & comment added,
|
| 85 |
+
// and characters changed to entities
|
| 86 |
+
const page2 = XHTML(`<html xmlns="http://www.w3.org/1999/xhtml">
|
| 87 |
+
<head>
|
| 88 |
+
<title>…</title>
|
| 89 |
+
</head>
|
| 90 |
+
<body id="body01">
|
| 91 |
+
<p>…</p><p>…</p><p>…</p><p>…</p>
|
| 92 |
+
<p id="para05">xxx<em>yyy</em><![CDATA[]]><!--comment1--><![CDATA[0123]]>4<!--comment2-->5<![CDATA[67]]>89</p>
|
| 93 |
+
<p>…</p>
|
| 94 |
+
<p>…</p>
|
| 95 |
+
<img id="svgimg" src="foo.svg" alt="…"/>
|
| 96 |
+
<p>…</p>
|
| 97 |
+
<p>…</p>
|
| 98 |
+
</body>
|
| 99 |
+
</html>`)
|
| 100 |
+
|
| 101 |
+
// the exact same page with nodes are to be ignored
|
| 102 |
+
const page3 = XHTML(`<html xmlns="http://www.w3.org/1999/xhtml">
|
| 103 |
+
<head>
|
| 104 |
+
<title>…</title>
|
| 105 |
+
</head>
|
| 106 |
+
<body id="body01">
|
| 107 |
+
<h1 class="reject">This is ignored!</h1>
|
| 108 |
+
<section class="skip">
|
| 109 |
+
<p class="reject">Also ignored</p>
|
| 110 |
+
<p>…</p><p>…</p><p>…</p><p>…</p>
|
| 111 |
+
<p id="para05">xxx<em>yyy</em><span class="reject">Note: we put ignored text in this span but not the other ones because although the CFI library should ignore them, they won't be ignored by DOM Ranges, which will break the tests.</span><span class="skip">0<span class="skip"><span class="reject"><![CDATA[]]></span>123</span></span>45<span class="reject"><img src="icon.svg"/></span>6789</p>
|
| 112 |
+
<p>…</p>
|
| 113 |
+
<p>…</p>
|
| 114 |
+
<img id="svgimg" src="foo.svg" alt="…"/>
|
| 115 |
+
<p>…</p>
|
| 116 |
+
<p>…</p>
|
| 117 |
+
</section>
|
| 118 |
+
</body>
|
| 119 |
+
</html>`)
|
| 120 |
+
|
| 121 |
+
const filter = node => node.nodeType !== 1 ? NodeFilter.FILTER_ACCEPT
|
| 122 |
+
: node.matches('.reject') ? NodeFilter.FILTER_REJECT
|
| 123 |
+
: node.matches('.skip') ? NodeFilter.FILTER_SKIP
|
| 124 |
+
: NodeFilter.FILTER_ACCEPT
|
| 125 |
+
|
| 126 |
+
const test = (page, filter) => {
|
| 127 |
+
for (const cfi of [
|
| 128 |
+
'/4[body01]/10[para05]/3:10',
|
| 129 |
+
'/4[body01]/16[svgimg]',
|
| 130 |
+
'/4[body01]/10[para05]/1:0',
|
| 131 |
+
'/4[body01]/10[para05]/2/1:0',
|
| 132 |
+
'/4[body01]/10[para05]/2/1:3',
|
| 133 |
+
]) {
|
| 134 |
+
const range = CFI.toRange(page, CFI.parse(cfi), filter)
|
| 135 |
+
const a = CFI.fromRange(range, filter)
|
| 136 |
+
const b = `epubcfi(${cfi})`
|
| 137 |
+
console.assert(a === b, `expected ${b}, got ${a}`)
|
| 138 |
+
}
|
| 139 |
+
for (let i = 0; i < 10; i++) {
|
| 140 |
+
const cfi = `/4/10,/3:${i},/3:${i+1}`
|
| 141 |
+
const range = CFI.toRange(page, CFI.parse(cfi), filter)
|
| 142 |
+
const n = `${i}`
|
| 143 |
+
console.assert(range.toString() === n, `expected ${n}, got ${range}`)
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
test(page)
|
| 147 |
+
test(page2)
|
| 148 |
+
|
| 149 |
+
test(page, filter)
|
| 150 |
+
test(page2, filter)
|
| 151 |
+
test(page3, filter)
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
{
|
| 155 |
+
// special characters in ID assertions
|
| 156 |
+
const opf = XML(`<?xml version="1.0"?>
|
| 157 |
+
<package version="2.0"
|
| 158 |
+
unique-identifier="bookid"
|
| 159 |
+
xmlns="http://www.idpf.org/2007/opf"
|
| 160 |
+
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
| 161 |
+
xmlns:opf="http://www.idpf.org/2007/opf">
|
| 162 |
+
<metadata></metadata>
|
| 163 |
+
<manifest></manifest>
|
| 164 |
+
<spine>
|
| 165 |
+
<itemref id="titleref" idref="titlepage"/>
|
| 166 |
+
<itemref id="chap0]!/1ref^" idref="chapter01"/>
|
| 167 |
+
<itemref id="chap02ref" idref="chapter02"/>
|
| 168 |
+
<itemref id="chap03ref" idref="chapter03"/>
|
| 169 |
+
<itemref id="chap04ref" idref="chapter04"/>
|
| 170 |
+
</spine>
|
| 171 |
+
</package>`)
|
| 172 |
+
|
| 173 |
+
const a = opf.getElementById('chap0]!/1ref^')
|
| 174 |
+
const b = CFI.toElement(opf, CFI.parse('/6/4[chap0^]!/1ref^^]')[0])
|
| 175 |
+
console.assert(a === b)
|
| 176 |
+
|
| 177 |
+
const page = XHTML(`<html xmlns="http://www.w3.org/1999/xhtml">
|
| 178 |
+
<head>
|
| 179 |
+
<title>…</title>
|
| 180 |
+
</head>
|
| 181 |
+
<body id="body0]!/1^">
|
| 182 |
+
<p>…</p>
|
| 183 |
+
<p>…</p>
|
| 184 |
+
<p>…</p>
|
| 185 |
+
<p>…</p>
|
| 186 |
+
<p id="para]/0,/5">xxx<em>yyy</em>0123456789</p>
|
| 187 |
+
<p>…</p>
|
| 188 |
+
<p>…</p>
|
| 189 |
+
<img id="s][vgimg" src="foo.svg" alt="…"/>
|
| 190 |
+
<p>…</p>
|
| 191 |
+
<p>…</p>
|
| 192 |
+
</body>
|
| 193 |
+
</html>`)
|
| 194 |
+
|
| 195 |
+
for (const cfi of [
|
| 196 |
+
'/4[body0^]!/1^^]/10[para^]/0^,/5]/3:10',
|
| 197 |
+
'/4[body0^]!/1^^]/16[s^]^[vgimg]',
|
| 198 |
+
'/4[body0^]!/1^^]/10[para^]/0^,/5]/1:0',
|
| 199 |
+
'/4[body0^]!/1^^]/10[para^]/0^,/5]/2/1:0',
|
| 200 |
+
'/4[body0^]!/1^^]/10[para^]/0^,/5]/2/1:3',
|
| 201 |
+
]) {
|
| 202 |
+
const range = CFI.toRange(page, CFI.parse(cfi))
|
| 203 |
+
const a = CFI.fromRange(range)
|
| 204 |
+
const b = `epubcfi(${cfi})`
|
| 205 |
+
console.assert(a === b, `expected ${b}, got ${a}`)
|
| 206 |
+
}
|
| 207 |
+
for (let i = 0; i < 10; i++) {
|
| 208 |
+
const cfi = `/4[body0^]!/1^^]/10[para^]/0^,^/5],/3:${i},/3:${i+1}`
|
| 209 |
+
const range = CFI.toRange(page, CFI.parse(cfi))
|
| 210 |
+
const n = `${i}`
|
| 211 |
+
console.assert(range.toString() === n, `expected ${n}, got ${range}`)
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
{
|
| 216 |
+
for (const [a, b, c] of [
|
| 217 |
+
['/6/4!/10', '/6/4!/10', 0],
|
| 218 |
+
['/6/4!/2/3:0', '/6/4!/2', 1],
|
| 219 |
+
['/6/4!/2/4/6/8/10/3:0', '/6/4!/4', -1],
|
| 220 |
+
[
|
| 221 |
+
'/6/4[chap0^]!/1ref^^]!/4[body01^^]/10[para^]^,05^^]',
|
| 222 |
+
'/6/4!/4/10',
|
| 223 |
+
0,
|
| 224 |
+
],
|
| 225 |
+
[
|
| 226 |
+
'/6/4[chap0^]!/1ref^^]!/4[body01^^],/10[para^]^,05^^],/15:10[foo^]]',
|
| 227 |
+
'/6/4!/4/12',
|
| 228 |
+
-1,
|
| 229 |
+
],
|
| 230 |
+
['/6/4', '/6/4!/2', -1],
|
| 231 |
+
['/6/4!/2', '/6/4!/2!/2', -1],
|
| 232 |
+
]) {
|
| 233 |
+
const x = CFI.compare(a, b)
|
| 234 |
+
console.assert(x === c, `compare ${a} and ${b}, expected ${c}, got ${x}`)
|
| 235 |
+
}
|
| 236 |
+
}
|
packages/foliate-js/tests/tests.html
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<meta charset="utf-8">
|
| 3 |
+
<meta name="color-scheme" content="light dark">
|
| 4 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 5 |
+
<script src="tests.js" type="module"></script>
|
packages/foliate-js/tests/tests.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
import './epubcfi-tests.js'
|
packages/foliate-js/text-walker.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const walkRange = (range, walker) => {
|
| 2 |
+
const nodes = []
|
| 3 |
+
for (let node = walker.currentNode; node; node = walker.nextNode()) {
|
| 4 |
+
const compare = range.comparePoint(node, 0)
|
| 5 |
+
if (compare === 0) nodes.push(node)
|
| 6 |
+
else if (compare > 0) break
|
| 7 |
+
}
|
| 8 |
+
return nodes
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
const walkDocument = (_, walker) => {
|
| 12 |
+
const nodes = []
|
| 13 |
+
for (let node = walker.nextNode(); node; node = walker.nextNode())
|
| 14 |
+
nodes.push(node)
|
| 15 |
+
return nodes
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const filter = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT
|
| 19 |
+
| NodeFilter.SHOW_CDATA_SECTION
|
| 20 |
+
|
| 21 |
+
const acceptNode = node => {
|
| 22 |
+
if (node.nodeType === 1) {
|
| 23 |
+
const name = node.tagName.toLowerCase()
|
| 24 |
+
if (name === 'script' || name === 'style') return NodeFilter.FILTER_REJECT
|
| 25 |
+
return NodeFilter.FILTER_SKIP
|
| 26 |
+
}
|
| 27 |
+
return NodeFilter.FILTER_ACCEPT
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
export const textWalker = function* (x, func, filterFunc) {
|
| 31 |
+
const root = x.commonAncestorContainer ?? x.body ?? x
|
| 32 |
+
const walker = document.createTreeWalker(root, filter, { acceptNode: filterFunc || acceptNode })
|
| 33 |
+
const walk = x.commonAncestorContainer ? walkRange : walkDocument
|
| 34 |
+
const nodes = walk(x, walker)
|
| 35 |
+
const strs = nodes.map(node => node.nodeValue ?? '')
|
| 36 |
+
const makeRange = (startIndex, startOffset, endIndex, endOffset) => {
|
| 37 |
+
const range = document.createRange()
|
| 38 |
+
range.setStart(nodes[startIndex], startOffset)
|
| 39 |
+
range.setEnd(nodes[endIndex], endOffset)
|
| 40 |
+
return range
|
| 41 |
+
}
|
| 42 |
+
for (const match of func(strs, makeRange)) yield match
|
| 43 |
+
}
|
packages/foliate-js/tts.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const NS = {
|
| 2 |
+
XML: 'http://www.w3.org/XML/1998/namespace',
|
| 3 |
+
SSML: 'http://www.w3.org/2001/10/synthesis',
|
| 4 |
+
}
|
| 5 |
+
|
| 6 |
+
const blockTags = new Set([
|
| 7 |
+
'article', 'aside', 'audio', 'blockquote', 'caption',
|
| 8 |
+
'details', 'dialog', 'div', 'dl', 'dt', 'dd',
|
| 9 |
+
'figure', 'footer', 'form', 'figcaption',
|
| 10 |
+
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li',
|
| 11 |
+
'main', 'math', 'nav', 'ol', 'p', 'pre', 'section', 'tr',
|
| 12 |
+
])
|
| 13 |
+
|
| 14 |
+
const getLang = el => {
|
| 15 |
+
const x = el.lang || el?.getAttributeNS?.(NS.XML, 'lang')
|
| 16 |
+
return x ? x : el.parentElement ? getLang(el.parentElement) : null
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const getAlphabet = el => {
|
| 20 |
+
const x = el?.getAttributeNS?.(NS.XML, 'lang')
|
| 21 |
+
return x ? x : el.parentElement ? getAlphabet(el.parentElement) : null
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const getSegmenter = (lang = 'en', granularity = 'word') => {
|
| 25 |
+
const segmenter = new Intl.Segmenter(lang, { granularity })
|
| 26 |
+
const granularityIsWord = granularity === 'word'
|
| 27 |
+
return function* (strs, makeRange) {
|
| 28 |
+
const str = strs.join('').replace(/\r\n/g, ' ').replace(/\r/g, ' ').replace(/\n/g, ' ')
|
| 29 |
+
let name = 0
|
| 30 |
+
let strIndex = -1
|
| 31 |
+
let sum = 0
|
| 32 |
+
const rawSegments = Array.from(segmenter.segment(str))
|
| 33 |
+
const mergedSegments = []
|
| 34 |
+
for (let i = 0; i < rawSegments.length; i++) {
|
| 35 |
+
const current = rawSegments[i]
|
| 36 |
+
const next = rawSegments[i + 1]
|
| 37 |
+
const segment = current.segment.trim()
|
| 38 |
+
const nextSegment = next?.segment?.trim()
|
| 39 |
+
const endsWithAbbr = /(?:^|\s)([A-Z][a-z]{1,5})\.$/.test(segment)
|
| 40 |
+
const nextStartsWithCapital = /^[A-Z]/.test(nextSegment || '')
|
| 41 |
+
if ((endsWithAbbr && nextStartsWithCapital) || segment.length <= 3) {
|
| 42 |
+
const mergedSegment = {
|
| 43 |
+
index: current.index,
|
| 44 |
+
segment: current.segment + (next?.segment || ''),
|
| 45 |
+
isWordLike: true,
|
| 46 |
+
}
|
| 47 |
+
mergedSegments.push(mergedSegment)
|
| 48 |
+
i++
|
| 49 |
+
} else {
|
| 50 |
+
mergedSegments.push(current)
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
for (const { index, segment, isWordLike } of mergedSegments) {
|
| 54 |
+
if (granularityIsWord && !isWordLike) continue
|
| 55 |
+
while (sum <= index) sum += strs[++strIndex].length
|
| 56 |
+
const startIndex = strIndex
|
| 57 |
+
const startOffset = index - (sum - strs[strIndex].length)
|
| 58 |
+
const end = index + segment.length - 1
|
| 59 |
+
if (end < str.length) while (sum <= end) sum += strs[++strIndex].length
|
| 60 |
+
const endIndex = strIndex
|
| 61 |
+
const endOffset = end - (sum - strs[strIndex].length) + 1
|
| 62 |
+
yield [(name++).toString(),
|
| 63 |
+
makeRange(startIndex, startOffset, endIndex, endOffset)]
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
const fragmentToSSML = (fragment, nodeFilter, inherited) => {
|
| 69 |
+
const ssml = document.implementation.createDocument(NS.SSML, 'speak')
|
| 70 |
+
const { lang } = inherited
|
| 71 |
+
if (lang) ssml.documentElement.setAttributeNS(NS.XML, 'lang', lang)
|
| 72 |
+
|
| 73 |
+
const convert = (node, parent, inheritedAlphabet) => {
|
| 74 |
+
if (!node) return
|
| 75 |
+
if (node.nodeType === 3) return ssml.createTextNode(node.textContent)
|
| 76 |
+
if (node.nodeType === 4) return ssml.createCDATASection(node.textContent)
|
| 77 |
+
if (node.nodeType !== 1 && node.nodeType !== 11) return
|
| 78 |
+
if (nodeFilter && nodeFilter(node) === NodeFilter.FILTER_REJECT) return
|
| 79 |
+
|
| 80 |
+
let el
|
| 81 |
+
const nodeName = node.nodeName.toLowerCase()
|
| 82 |
+
if (nodeName === 'foliate-mark') {
|
| 83 |
+
el = ssml.createElementNS(NS.SSML, 'mark')
|
| 84 |
+
el.setAttribute('name', node.dataset.name)
|
| 85 |
+
}
|
| 86 |
+
else if (nodeName === 'br')
|
| 87 |
+
el = ssml.createElementNS(NS.SSML, 'break')
|
| 88 |
+
else if (nodeName === 'em' || nodeName === 'strong')
|
| 89 |
+
el = ssml.createElementNS(NS.SSML, 'emphasis')
|
| 90 |
+
|
| 91 |
+
const lang = node.lang || node.getAttributeNS?.(NS.XML, 'lang')
|
| 92 |
+
if (lang) {
|
| 93 |
+
if (!el) el = ssml.createElementNS(NS.SSML, 'lang')
|
| 94 |
+
el.setAttributeNS(NS.XML, 'lang', lang)
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
const alphabet = node.getAttributeNS?.(NS.SSML, 'alphabet') || inheritedAlphabet
|
| 98 |
+
if (!el) {
|
| 99 |
+
const ph = node.getAttributeNS?.(NS.SSML, 'ph')
|
| 100 |
+
if (ph) {
|
| 101 |
+
el = ssml.createElementNS(NS.SSML, 'phoneme')
|
| 102 |
+
if (alphabet) el.setAttribute('alphabet', alphabet)
|
| 103 |
+
el.setAttribute('ph', ph)
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
if (!el) el = parent
|
| 108 |
+
|
| 109 |
+
let child = node.firstChild
|
| 110 |
+
while (child) {
|
| 111 |
+
const childEl = convert(child, el, alphabet)
|
| 112 |
+
if (childEl && el !== childEl) el.append(childEl)
|
| 113 |
+
child = child.nextSibling
|
| 114 |
+
}
|
| 115 |
+
return el
|
| 116 |
+
}
|
| 117 |
+
convert(fragment, ssml.documentElement, inherited.alphabet)
|
| 118 |
+
return ssml
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
const getFragmentWithMarks = (range, textWalker, nodeFilter, granularity) => {
|
| 122 |
+
const lang = getLang(range.commonAncestorContainer)
|
| 123 |
+
const alphabet = getAlphabet(range.commonAncestorContainer)
|
| 124 |
+
|
| 125 |
+
const segmenter = getSegmenter(lang, granularity)
|
| 126 |
+
const fragment = range.cloneContents()
|
| 127 |
+
|
| 128 |
+
// we need ranges on both the original document (for highlighting)
|
| 129 |
+
// and the document fragment (for inserting marks)
|
| 130 |
+
// so unfortunately need to do it twice, as you can't copy the ranges
|
| 131 |
+
const entries = [...textWalker(range, segmenter, nodeFilter)]
|
| 132 |
+
const fragmentEntries = [...textWalker(fragment, segmenter, nodeFilter)]
|
| 133 |
+
|
| 134 |
+
for (const [name, range] of fragmentEntries) {
|
| 135 |
+
const mark = document.createElement('foliate-mark')
|
| 136 |
+
mark.dataset.name = name
|
| 137 |
+
range.insertNode(mark)
|
| 138 |
+
}
|
| 139 |
+
const ssml = fragmentToSSML(fragment, nodeFilter, { lang, alphabet })
|
| 140 |
+
return { entries, ssml }
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
const rangeIsEmpty = range => !range.toString().trim()
|
| 144 |
+
|
| 145 |
+
function* getBlocks(doc) {
|
| 146 |
+
let last
|
| 147 |
+
const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT)
|
| 148 |
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
| 149 |
+
const name = node.tagName.toLowerCase()
|
| 150 |
+
if (blockTags.has(name)) {
|
| 151 |
+
if (last) {
|
| 152 |
+
last.setEndBefore(node)
|
| 153 |
+
if (!rangeIsEmpty(last)) yield last
|
| 154 |
+
}
|
| 155 |
+
last = doc.createRange()
|
| 156 |
+
last.setStart(node, 0)
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
if (!last) {
|
| 160 |
+
last = doc.createRange()
|
| 161 |
+
last.setStart(doc.body.firstChild ?? doc.body, 0)
|
| 162 |
+
}
|
| 163 |
+
last.setEndAfter(doc.body.lastChild ?? doc.body)
|
| 164 |
+
if (!rangeIsEmpty(last)) yield last
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
class ListIterator {
|
| 168 |
+
#arr = []
|
| 169 |
+
#iter
|
| 170 |
+
#index = -1
|
| 171 |
+
#f
|
| 172 |
+
constructor(iter, f = x => x) {
|
| 173 |
+
this.#iter = iter
|
| 174 |
+
this.#f = f
|
| 175 |
+
}
|
| 176 |
+
current() {
|
| 177 |
+
if (this.#arr[this.#index]) return this.#f(this.#arr[this.#index])
|
| 178 |
+
}
|
| 179 |
+
first() {
|
| 180 |
+
const newIndex = 0
|
| 181 |
+
if (this.#arr[newIndex]) {
|
| 182 |
+
this.#index = newIndex
|
| 183 |
+
return this.#f(this.#arr[newIndex])
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
prev() {
|
| 187 |
+
const newIndex = this.#index - 1
|
| 188 |
+
if (this.#arr[newIndex]) {
|
| 189 |
+
this.#index = newIndex
|
| 190 |
+
return this.#f(this.#arr[newIndex])
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
next() {
|
| 194 |
+
const newIndex = this.#index + 1
|
| 195 |
+
if (this.#arr[newIndex]) {
|
| 196 |
+
this.#index = newIndex
|
| 197 |
+
return this.#f(this.#arr[newIndex])
|
| 198 |
+
}
|
| 199 |
+
while (true) {
|
| 200 |
+
const { done, value } = this.#iter.next()
|
| 201 |
+
if (done) break
|
| 202 |
+
this.#arr.push(value)
|
| 203 |
+
if (this.#arr[newIndex]) {
|
| 204 |
+
this.#index = newIndex
|
| 205 |
+
return this.#f(this.#arr[newIndex])
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
find(f) {
|
| 210 |
+
const index = this.#arr.findIndex(x => f(x))
|
| 211 |
+
if (index > -1) {
|
| 212 |
+
this.#index = index
|
| 213 |
+
return this.#f(this.#arr[index])
|
| 214 |
+
}
|
| 215 |
+
while (true) {
|
| 216 |
+
const { done, value } = this.#iter.next()
|
| 217 |
+
if (done) break
|
| 218 |
+
this.#arr.push(value)
|
| 219 |
+
if (f(value)) {
|
| 220 |
+
this.#index = this.#arr.length - 1
|
| 221 |
+
return this.#f(value)
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
export class TTS {
|
| 228 |
+
#list
|
| 229 |
+
#ranges
|
| 230 |
+
#lastMark
|
| 231 |
+
#serializer = new XMLSerializer()
|
| 232 |
+
constructor(doc, textWalker, nodeFilter, highlight, granularity) {
|
| 233 |
+
this.doc = doc
|
| 234 |
+
this.highlight = highlight
|
| 235 |
+
this.#list = new ListIterator(getBlocks(doc), range => {
|
| 236 |
+
const { entries, ssml } = getFragmentWithMarks(range, textWalker, nodeFilter, granularity)
|
| 237 |
+
this.#ranges = new Map(entries)
|
| 238 |
+
return [ssml, range]
|
| 239 |
+
})
|
| 240 |
+
}
|
| 241 |
+
#getMarkElement(doc, mark) {
|
| 242 |
+
if (!mark) return null
|
| 243 |
+
return doc.querySelector(`mark[name="${CSS.escape(mark)}"`)
|
| 244 |
+
}
|
| 245 |
+
#speak(doc, getNode) {
|
| 246 |
+
if (!doc) return
|
| 247 |
+
if (!getNode) return this.#serializer.serializeToString(doc)
|
| 248 |
+
const ssml = document.implementation.createDocument(NS.SSML, 'speak')
|
| 249 |
+
ssml.documentElement.replaceWith(ssml.importNode(doc.documentElement, true))
|
| 250 |
+
let node = getNode(ssml)?.previousSibling
|
| 251 |
+
while (node) {
|
| 252 |
+
const next = node.previousSibling ?? node.parentNode?.previousSibling
|
| 253 |
+
node.parentNode.removeChild(node)
|
| 254 |
+
node = next
|
| 255 |
+
}
|
| 256 |
+
const ssmlStr = this.#serializer.serializeToString(ssml)
|
| 257 |
+
return ssmlStr
|
| 258 |
+
}
|
| 259 |
+
start() {
|
| 260 |
+
this.#lastMark = null
|
| 261 |
+
const [doc] = this.#list.first() ?? []
|
| 262 |
+
if (!doc) return this.next()
|
| 263 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, this.#lastMark))
|
| 264 |
+
}
|
| 265 |
+
resume() {
|
| 266 |
+
const [doc] = this.#list.current() ?? []
|
| 267 |
+
if (!doc) return this.next()
|
| 268 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, this.#lastMark))
|
| 269 |
+
}
|
| 270 |
+
prev(paused) {
|
| 271 |
+
this.#lastMark = null
|
| 272 |
+
const [doc, range] = this.#list.prev() ?? []
|
| 273 |
+
if (paused && range) this.highlight(range.cloneRange())
|
| 274 |
+
return this.#speak(doc)
|
| 275 |
+
}
|
| 276 |
+
next(paused) {
|
| 277 |
+
this.#lastMark = null
|
| 278 |
+
const [doc, range] = this.#list.next() ?? []
|
| 279 |
+
if (paused && range) this.highlight(range.cloneRange())
|
| 280 |
+
return this.#speak(doc)
|
| 281 |
+
}
|
| 282 |
+
prevMark(paused) {
|
| 283 |
+
const marks = Array.from(this.#ranges.keys())
|
| 284 |
+
if (marks.length === 0) return
|
| 285 |
+
|
| 286 |
+
const currentIndex = this.#lastMark ? marks.indexOf(this.#lastMark) : -1
|
| 287 |
+
if (currentIndex > 0) {
|
| 288 |
+
const prevMarkName = marks[currentIndex - 1]
|
| 289 |
+
const range = this.#ranges.get(prevMarkName)
|
| 290 |
+
if (range) {
|
| 291 |
+
this.#lastMark = prevMarkName
|
| 292 |
+
if (paused) this.highlight(range.cloneRange())
|
| 293 |
+
|
| 294 |
+
const [doc] = this.#list.current() ?? []
|
| 295 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, prevMarkName))
|
| 296 |
+
}
|
| 297 |
+
} else {
|
| 298 |
+
const [doc, range] = this.#list.prev() ?? []
|
| 299 |
+
if (doc && range) {
|
| 300 |
+
const prevMarks = Array.from(this.#ranges.keys())
|
| 301 |
+
if (prevMarks.length > 0) {
|
| 302 |
+
const lastMarkName = prevMarks[prevMarks.length - 1]
|
| 303 |
+
const lastMarkRange = this.#ranges.get(lastMarkName)
|
| 304 |
+
if (lastMarkRange) {
|
| 305 |
+
this.#lastMark = lastMarkName
|
| 306 |
+
if (paused) this.highlight(lastMarkRange.cloneRange())
|
| 307 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, lastMarkName))
|
| 308 |
+
}
|
| 309 |
+
} else {
|
| 310 |
+
this.#lastMark = null
|
| 311 |
+
if (paused) this.highlight(range.cloneRange())
|
| 312 |
+
return this.#speak(doc)
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
nextMark(paused) {
|
| 318 |
+
const marks = Array.from(this.#ranges.keys())
|
| 319 |
+
if (marks.length === 0) return
|
| 320 |
+
|
| 321 |
+
const currentIndex = this.#lastMark ? marks.indexOf(this.#lastMark) : -1
|
| 322 |
+
if (currentIndex >= 0 && currentIndex < marks.length - 1) {
|
| 323 |
+
const nextMarkName = marks[currentIndex + 1]
|
| 324 |
+
const range = this.#ranges.get(nextMarkName)
|
| 325 |
+
if (range) {
|
| 326 |
+
this.#lastMark = nextMarkName
|
| 327 |
+
if (paused) this.highlight(range.cloneRange())
|
| 328 |
+
const [doc] = this.#list.current() ?? []
|
| 329 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, nextMarkName))
|
| 330 |
+
}
|
| 331 |
+
} else {
|
| 332 |
+
const [doc, range] = this.#list.next() ?? []
|
| 333 |
+
if (doc && range) {
|
| 334 |
+
const nextMarks = Array.from(this.#ranges.keys())
|
| 335 |
+
if (nextMarks.length > 0) {
|
| 336 |
+
const firstMarkName = nextMarks[0]
|
| 337 |
+
const firstMarkRange = this.#ranges.get(firstMarkName)
|
| 338 |
+
if (firstMarkRange) {
|
| 339 |
+
this.#lastMark = firstMarkName
|
| 340 |
+
if (paused) this.highlight(firstMarkRange.cloneRange())
|
| 341 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, firstMarkName))
|
| 342 |
+
}
|
| 343 |
+
} else {
|
| 344 |
+
this.#lastMark = null
|
| 345 |
+
if (paused) this.highlight(range.cloneRange())
|
| 346 |
+
return this.#speak(doc)
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
from(range) {
|
| 352 |
+
this.#lastMark = null
|
| 353 |
+
const [doc] = this.#list.find(range_ =>
|
| 354 |
+
range.compareBoundaryPoints(Range.END_TO_START, range_) <= 0)
|
| 355 |
+
let mark
|
| 356 |
+
for (const [name, range_] of this.#ranges.entries())
|
| 357 |
+
if (range.compareBoundaryPoints(Range.START_TO_START, range_) <= 0) {
|
| 358 |
+
mark = name
|
| 359 |
+
break
|
| 360 |
+
}
|
| 361 |
+
return this.#speak(doc, ssml => this.#getMarkElement(ssml, mark))
|
| 362 |
+
}
|
| 363 |
+
getLastRange() {
|
| 364 |
+
if (this.#lastMark) {
|
| 365 |
+
const range = this.#ranges.get(this.#lastMark)
|
| 366 |
+
if (range) return range.cloneRange()
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
setMark(mark) {
|
| 370 |
+
const range = this.#ranges.get(mark)
|
| 371 |
+
if (range) {
|
| 372 |
+
this.#lastMark = mark
|
| 373 |
+
this.highlight(range.cloneRange())
|
| 374 |
+
return range
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
}
|
packages/foliate-js/ui/menu.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const createMenuItemRadioGroup = (label, arr, onclick) => {
|
| 2 |
+
const group = document.createElement('ul')
|
| 3 |
+
group.setAttribute('role', 'group')
|
| 4 |
+
group.setAttribute('aria-label', label)
|
| 5 |
+
const map = new Map()
|
| 6 |
+
const select = value => {
|
| 7 |
+
onclick(value)
|
| 8 |
+
const item = map.get(value)
|
| 9 |
+
for (const child of group.children)
|
| 10 |
+
child.setAttribute('aria-checked', child === item ? 'true' : 'false')
|
| 11 |
+
}
|
| 12 |
+
for (const [label, value] of arr) {
|
| 13 |
+
const item = document.createElement('li')
|
| 14 |
+
item.setAttribute('role', 'menuitemradio')
|
| 15 |
+
item.innerText = label
|
| 16 |
+
item.onclick = () => select(value)
|
| 17 |
+
map.set(value, item)
|
| 18 |
+
group.append(item)
|
| 19 |
+
}
|
| 20 |
+
return { element: group, select }
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
export const createMenu = arr => {
|
| 24 |
+
const groups = {}
|
| 25 |
+
const element = document.createElement('ul')
|
| 26 |
+
element.setAttribute('role', 'menu')
|
| 27 |
+
const hide = () => element.classList.remove('show')
|
| 28 |
+
const hideAnd = f => (...args) => (hide(), f(...args))
|
| 29 |
+
for (const { name, label, type, items, onclick } of arr) {
|
| 30 |
+
const widget = type === 'radio'
|
| 31 |
+
? createMenuItemRadioGroup(label, items, hideAnd(onclick))
|
| 32 |
+
: null
|
| 33 |
+
if (name) groups[name] = widget
|
| 34 |
+
element.append(widget.element)
|
| 35 |
+
}
|
| 36 |
+
// TODO: keyboard events
|
| 37 |
+
window.addEventListener('blur', () => hide())
|
| 38 |
+
window.addEventListener('click', e => {
|
| 39 |
+
if (!element.parentNode.contains(e.target)) hide()
|
| 40 |
+
})
|
| 41 |
+
return { element, groups }
|
| 42 |
+
}
|
packages/foliate-js/ui/tree.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const createSVGElement = tag =>
|
| 2 |
+
document.createElementNS('http://www.w3.org/2000/svg', tag)
|
| 3 |
+
|
| 4 |
+
const createExpanderIcon = () => {
|
| 5 |
+
const svg = createSVGElement('svg')
|
| 6 |
+
svg.setAttribute('viewBox', '0 0 13 10')
|
| 7 |
+
svg.setAttribute('width', '13')
|
| 8 |
+
svg.setAttribute('height', '13')
|
| 9 |
+
const polygon = createSVGElement('polygon')
|
| 10 |
+
polygon.setAttribute('points', '2 1, 12 1, 7 9')
|
| 11 |
+
svg.append(polygon)
|
| 12 |
+
return svg
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
const createTOCItemElement = (list, map, onclick) => {
|
| 16 |
+
let count = 0
|
| 17 |
+
const makeID = () => `toc-element-${count++}`
|
| 18 |
+
const createItem = ({ label, href, subitems }, depth = 0) => {
|
| 19 |
+
const a = document.createElement(href ? 'a' : 'span')
|
| 20 |
+
a.innerText = label
|
| 21 |
+
a.setAttribute('role', 'treeitem')
|
| 22 |
+
a.tabIndex = -1
|
| 23 |
+
a.style.paddingInlineStart = `${(depth + 1) * 24}px`
|
| 24 |
+
list.push(a)
|
| 25 |
+
if (href) {
|
| 26 |
+
if (!map.has(href)) map.set(href, a)
|
| 27 |
+
a.href = href
|
| 28 |
+
a.onclick = event => {
|
| 29 |
+
event.preventDefault()
|
| 30 |
+
onclick(href)
|
| 31 |
+
}
|
| 32 |
+
} else a.onclick = event => a.firstElementChild?.onclick(event)
|
| 33 |
+
|
| 34 |
+
const li = document.createElement('li')
|
| 35 |
+
li.setAttribute('role', 'none')
|
| 36 |
+
li.append(a)
|
| 37 |
+
if (subitems?.length) {
|
| 38 |
+
a.setAttribute('aria-expanded', 'false')
|
| 39 |
+
const expander = createExpanderIcon()
|
| 40 |
+
expander.onclick = event => {
|
| 41 |
+
event.preventDefault()
|
| 42 |
+
event.stopPropagation()
|
| 43 |
+
const expanded = a.getAttribute('aria-expanded')
|
| 44 |
+
a.setAttribute('aria-expanded', expanded === 'true' ? 'false' : 'true')
|
| 45 |
+
}
|
| 46 |
+
a.prepend(expander)
|
| 47 |
+
const ol = document.createElement('ol')
|
| 48 |
+
ol.id = makeID()
|
| 49 |
+
ol.setAttribute('role', 'group')
|
| 50 |
+
a.setAttribute('aria-owns', ol.id)
|
| 51 |
+
ol.replaceChildren(...subitems.map(item => createItem(item, depth + 1)))
|
| 52 |
+
li.append(ol)
|
| 53 |
+
}
|
| 54 |
+
return li
|
| 55 |
+
}
|
| 56 |
+
return createItem
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// https://www.w3.org/TR/wai-aria-practices-1.2/examples/treeview/treeview-navigation.html
|
| 60 |
+
export const createTOCView = (toc, onclick) => {
|
| 61 |
+
const $toc = document.createElement('ol')
|
| 62 |
+
$toc.setAttribute('role', 'tree')
|
| 63 |
+
const list = []
|
| 64 |
+
const map = new Map()
|
| 65 |
+
const createItem = createTOCItemElement(list, map, onclick)
|
| 66 |
+
$toc.replaceChildren(...toc.map(item => createItem(item)))
|
| 67 |
+
|
| 68 |
+
const isTreeItem = item => item?.getAttribute('role') === 'treeitem'
|
| 69 |
+
const getParents = function* (el) {
|
| 70 |
+
for (let parent = el.parentNode; parent !== $toc; parent = parent.parentNode) {
|
| 71 |
+
const item = parent.previousElementSibling
|
| 72 |
+
if (isTreeItem(item)) yield item
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
let currentItem, currentVisibleParent
|
| 77 |
+
$toc.addEventListener('focusout', () => {
|
| 78 |
+
if (!currentItem) return
|
| 79 |
+
// reset parent focus from last time
|
| 80 |
+
if (currentVisibleParent) currentVisibleParent.tabIndex = -1
|
| 81 |
+
// if current item is visible, let it have the focus
|
| 82 |
+
if (currentItem.offsetParent) {
|
| 83 |
+
currentItem.tabIndex = 0
|
| 84 |
+
return
|
| 85 |
+
}
|
| 86 |
+
// current item is hidden; give focus to the nearest visible parent
|
| 87 |
+
for (const item of getParents(currentItem)) {
|
| 88 |
+
if (item.offsetParent) {
|
| 89 |
+
item.tabIndex = 0
|
| 90 |
+
currentVisibleParent = item
|
| 91 |
+
break
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
})
|
| 95 |
+
|
| 96 |
+
const setCurrentHref = href => {
|
| 97 |
+
if (currentItem) {
|
| 98 |
+
currentItem.removeAttribute('aria-current')
|
| 99 |
+
currentItem.tabIndex = -1
|
| 100 |
+
}
|
| 101 |
+
const el = map.get(href)
|
| 102 |
+
if (!el) {
|
| 103 |
+
currentItem = list[0]
|
| 104 |
+
currentItem.tabIndex = 0
|
| 105 |
+
return
|
| 106 |
+
}
|
| 107 |
+
for (const item of getParents(el))
|
| 108 |
+
item.setAttribute('aria-expanded', 'true')
|
| 109 |
+
el.setAttribute('aria-current', 'page')
|
| 110 |
+
el.tabIndex = 0
|
| 111 |
+
el.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
| 112 |
+
currentItem = el
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
const acceptNode = node => isTreeItem(node) && node.offsetParent
|
| 116 |
+
? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
|
| 117 |
+
const iter = document.createTreeWalker($toc, 1, { acceptNode })
|
| 118 |
+
const getIter = current => (iter.currentNode = current, iter)
|
| 119 |
+
|
| 120 |
+
for (const el of list) el.addEventListener('keydown', event => {
|
| 121 |
+
let stop = false
|
| 122 |
+
const { currentTarget, key } = event
|
| 123 |
+
switch (key) {
|
| 124 |
+
case ' ':
|
| 125 |
+
case 'Enter':
|
| 126 |
+
currentTarget.click()
|
| 127 |
+
stop = true
|
| 128 |
+
break
|
| 129 |
+
case 'ArrowDown':
|
| 130 |
+
getIter(currentTarget).nextNode()?.focus()
|
| 131 |
+
stop = true
|
| 132 |
+
break
|
| 133 |
+
case 'ArrowUp':
|
| 134 |
+
getIter(currentTarget).previousNode()?.focus()
|
| 135 |
+
stop = true
|
| 136 |
+
break
|
| 137 |
+
case 'ArrowLeft':
|
| 138 |
+
if (currentTarget.getAttribute('aria-expanded') === 'true')
|
| 139 |
+
currentTarget.setAttribute('aria-expanded', 'false')
|
| 140 |
+
else getParents(currentTarget).next()?.value?.focus()
|
| 141 |
+
stop = true
|
| 142 |
+
break
|
| 143 |
+
case 'ArrowRight':
|
| 144 |
+
if (currentTarget.getAttribute('aria-expanded') === 'true')
|
| 145 |
+
getIter(currentTarget).nextNode()?.focus()
|
| 146 |
+
else if (currentTarget.getAttribute('aria-owns'))
|
| 147 |
+
currentTarget.setAttribute('aria-expanded', 'true')
|
| 148 |
+
stop = true
|
| 149 |
+
break
|
| 150 |
+
case 'Home':
|
| 151 |
+
list[0].focus()
|
| 152 |
+
stop = true
|
| 153 |
+
break
|
| 154 |
+
case 'End': {
|
| 155 |
+
const last = list[list.length - 1]
|
| 156 |
+
if (last.offsetParent) last.focus()
|
| 157 |
+
else getIter(last).previousNode()?.focus()
|
| 158 |
+
stop = true
|
| 159 |
+
break
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
if (stop) {
|
| 163 |
+
event.preventDefault()
|
| 164 |
+
event.stopPropagation()
|
| 165 |
+
}
|
| 166 |
+
})
|
| 167 |
+
|
| 168 |
+
return { element: $toc, setCurrentHref }
|
| 169 |
+
}
|
packages/foliate-js/uri-template.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// URI Template: https://datatracker.ietf.org/doc/html/rfc6570
|
| 2 |
+
|
| 3 |
+
const regex = /{([+#./;?&])?([^}]+?)}/g
|
| 4 |
+
const varspecRegex = /(.+?)(\*|:[1-9]\d{0,3})?$/
|
| 5 |
+
|
| 6 |
+
const table = {
|
| 7 |
+
undefined: { first: '', sep: ',' },
|
| 8 |
+
'+': { first: '', sep: ',', allowReserved: true },
|
| 9 |
+
'.': { first: '.', sep: '.' },
|
| 10 |
+
'/': { first: '/', sep: '/' },
|
| 11 |
+
';': { first: ';', sep: ';', named: true, ifemp: '' },
|
| 12 |
+
'?': { first: '?', sep: '&', named: true, ifemp: '=' },
|
| 13 |
+
'&': { first: '&', sep: '&', named: true, ifemp: '=' },
|
| 14 |
+
'#': { first: '&', sep: '&', allowReserved: true },
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
// 2.4.1 Prefix Values, "Note that this numbering is in characters, not octets"
|
| 18 |
+
const prefix = (maxLength, str) => {
|
| 19 |
+
let result = ''
|
| 20 |
+
for (const char of str) {
|
| 21 |
+
const newResult = char
|
| 22 |
+
if (newResult.length > maxLength) return result
|
| 23 |
+
else result = newResult
|
| 24 |
+
}
|
| 25 |
+
return result
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export const replace = (str, map) => str.replace(regex, (_, operator, variableList) => {
|
| 29 |
+
const { first, sep, named, ifemp, allowReserved } = table[operator]
|
| 30 |
+
// TODO: this isn't spec compliant
|
| 31 |
+
const encode = allowReserved ? encodeURI : encodeURIComponent
|
| 32 |
+
const values = variableList.split(',').map(varspec => {
|
| 33 |
+
const match = varspec.match(varspecRegex)
|
| 34 |
+
if (!match) return
|
| 35 |
+
const [, name, modifier] = match
|
| 36 |
+
let value = map.get(name)
|
| 37 |
+
if (modifier?.startsWith(':')) {
|
| 38 |
+
const maxLength = parseInt(modifier.slice(1))
|
| 39 |
+
value = prefix(maxLength, value)
|
| 40 |
+
}
|
| 41 |
+
return [name, value ? encode(value) : null]
|
| 42 |
+
})
|
| 43 |
+
if (!values.filter(([, value]) => value).length) return ''
|
| 44 |
+
return first + values
|
| 45 |
+
.map(([name, value]) => value
|
| 46 |
+
? (named ? name + (value ? '=' + value : ifemp) : value) : '')
|
| 47 |
+
.filter(x => x).join(sep)
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
export const getVariables = str => new Set(Array.from(str.matchAll(regex),
|
| 51 |
+
([,, variableList]) => variableList.split(',')
|
| 52 |
+
.map(varspec => varspec.match(varspecRegex)?.[1])).flat())
|
packages/foliate-js/vendor/fflate.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
var r=Uint8Array,a=Uint16Array,e=Int32Array,n=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),t=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),f=function(r,n){for(var i=new a(31),t=0;t<31;++t)i[t]=n+=1<<r[t-1];var f=new e(i[30]);for(t=1;t<30;++t)for(var o=i[t];o<i[t+1];++o)f[o]=o-i[t]<<5|t;return{b:i,r:f}},o=f(n,2),v=o.b,l=o.r;v[28]=258,l[258]=28;for(var u=f(i,0).b,c=new a(32768),d=0;d<32768;++d){var w=(43690&d)>>1|(21845&d)<<1;w=(61680&(w=(52428&w)>>2|(13107&w)<<2))>>4|(3855&w)<<4,c[d]=((65280&w)>>8|(255&w)<<8)>>1}var b=function(r,e,n){for(var i=r.length,t=0,f=new a(e);t<i;++t)r[t]&&++f[r[t]-1];var o,v=new a(e);for(t=1;t<e;++t)v[t]=v[t-1]+f[t-1]<<1;if(n){o=new a(1<<e);var l=15-e;for(t=0;t<i;++t)if(r[t])for(var u=t<<4|r[t],d=e-r[t],w=v[r[t]-1]++<<d,b=w|(1<<d)-1;w<=b;++w)o[c[w]>>l]=u}else for(o=new a(i),t=0;t<i;++t)r[t]&&(o[t]=c[v[r[t]-1]++]>>15-r[t]);return o},s=new r(288);for(d=0;d<144;++d)s[d]=8;for(d=144;d<256;++d)s[d]=9;for(d=256;d<280;++d)s[d]=7;for(d=280;d<288;++d)s[d]=8;var h=new r(32);for(d=0;d<32;++d)h[d]=5;var y=b(s,9,1),g=b(h,5,1),p=function(r){for(var a=r[0],e=1;e<r.length;++e)r[e]>a&&(a=r[e]);return a},k=function(r,a,e){var n=a/8|0;return(r[n]|r[n+1]<<8)>>(7&a)&e},m=function(r,a){var e=a/8|0;return(r[e]|r[e+1]<<8|r[e+2]<<16)>>(7&a)},x=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],T=function(r,a,e){var n=new Error(a||x[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,T),!e)throw n;return n},E=function(a,e,f,o){var l=a.length,c=o?o.length:0;if(!l||e.f&&!e.l)return f||new r(0);var d=!f,w=d||2!=e.i,s=e.i;d&&(f=new r(3*l));var h=function(a){var e=f.length;if(a>e){var n=new r(Math.max(2*e,a));n.set(f),f=n}},x=e.f||0,E=e.p||0,z=e.b||0,A=e.l,U=e.d,D=e.m,F=e.n,M=8*l;do{if(!A){x=k(a,E,1);var S=k(a,E+1,3);if(E+=3,!S){var I=a[(N=4+((E+7)/8|0))-4]|a[N-3]<<8,O=N+I;if(O>l){s&&T(0);break}w&&h(z+I),f.set(a.subarray(N,O),z),e.b=z+=I,e.p=E=8*O,e.f=x;continue}if(1==S)A=y,U=g,D=9,F=5;else if(2==S){var j=k(a,E,31)+257,q=k(a,E+10,15)+4,B=j+k(a,E+5,31)+1;E+=14;for(var C=new r(B),G=new r(19),H=0;H<q;++H)G[t[H]]=k(a,E+3*H,7);E+=3*q;var J=p(G),K=(1<<J)-1,L=b(G,J,1);for(H=0;H<B;){var N,P=L[k(a,E,K)];if(E+=15&P,(N=P>>4)<16)C[H++]=N;else{var Q=0,R=0;for(16==N?(R=3+k(a,E,3),E+=2,Q=C[H-1]):17==N?(R=3+k(a,E,7),E+=3):18==N&&(R=11+k(a,E,127),E+=7);R--;)C[H++]=Q}}var V=C.subarray(0,j),W=C.subarray(j);D=p(V),F=p(W),A=b(V,D,1),U=b(W,F,1)}else T(1);if(E>M){s&&T(0);break}}w&&h(z+131072);for(var X=(1<<D)-1,Y=(1<<F)-1,Z=E;;Z=E){var $=(Q=A[m(a,E)&X])>>4;if((E+=15&Q)>M){s&&T(0);break}if(Q||T(2),$<256)f[z++]=$;else{if(256==$){Z=E,A=null;break}var _=$-254;if($>264){var rr=n[H=$-257];_=k(a,E,(1<<rr)-1)+v[H],E+=rr}var ar=U[m(a,E)&Y],er=ar>>4;ar||T(3),E+=15&ar;W=u[er];if(er>3){rr=i[er];W+=m(a,E)&(1<<rr)-1,E+=rr}if(E>M){s&&T(0);break}w&&h(z+131072);var nr=z+_;if(z<W){var ir=c-W,tr=Math.min(W,nr);for(ir+z<0&&T(3);z<tr;++z)f[z]=o[ir+z]}for(;z<nr;++z)f[z]=f[z-W]}}e.l=A,e.p=Z,e.b=z,e.f=x,A&&(x=1,e.m=D,e.d=U,e.n=F)}while(!x);return z!=f.length&&d?function(a,e,n){return(null==n||n>a.length)&&(n=a.length),new r(a.subarray(e,n))}(f,0,z):f.subarray(0,z)},z=new r(0);function A(r,a){return E(r.subarray((e=r,n=a&&a.dictionary,(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&T(6,"invalid zlib data"),(e[1]>>5&1)==+!n&&T(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)),-4),{i:2},a&&a.out,a&&a.dictionary);var e,n}var U="undefined"!=typeof TextDecoder&&new TextDecoder;try{U.decode(z,{stream:!0})}catch(r){}export{A as unzlibSync};
|
packages/foliate-js/vendor/pdfjs/annotation_layer_builder.css
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Copyright 2014 Mozilla Foundation
|
| 2 |
+
*
|
| 3 |
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
* you may not use this file except in compliance with the License.
|
| 5 |
+
* You may obtain a copy of the License at
|
| 6 |
+
*
|
| 7 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
*
|
| 9 |
+
* Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
* See the License for the specific language governing permissions and
|
| 13 |
+
* limitations under the License.
|
| 14 |
+
*/
|
| 15 |
+
|
| 16 |
+
.annotationLayer {
|
| 17 |
+
color-scheme: only light;
|
| 18 |
+
|
| 19 |
+
--annotation-unfocused-field-background: url("data:image/svg+xml;charset=UTF-8,<svg width='1px' height='1px' xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' style='fill:rgba(0, 54, 255, 0.13);'/></svg>");
|
| 20 |
+
--input-focus-border-color: Highlight;
|
| 21 |
+
--input-focus-outline: 1px solid Canvas;
|
| 22 |
+
--input-unfocused-border-color: transparent;
|
| 23 |
+
--input-disabled-border-color: transparent;
|
| 24 |
+
--input-hover-border-color: black;
|
| 25 |
+
--link-outline: none;
|
| 26 |
+
|
| 27 |
+
@media screen and (forced-colors: active) {
|
| 28 |
+
--input-focus-border-color: CanvasText;
|
| 29 |
+
--input-unfocused-border-color: ActiveText;
|
| 30 |
+
--input-disabled-border-color: GrayText;
|
| 31 |
+
--input-hover-border-color: Highlight;
|
| 32 |
+
--link-outline: 1.5px solid LinkText;
|
| 33 |
+
|
| 34 |
+
.textWidgetAnnotation :is(input, textarea):required,
|
| 35 |
+
.choiceWidgetAnnotation select:required,
|
| 36 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
|
| 37 |
+
outline: 1.5px solid selectedItem;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
.linkAnnotation {
|
| 41 |
+
outline: var(--link-outline);
|
| 42 |
+
|
| 43 |
+
&:hover {
|
| 44 |
+
backdrop-filter: var(--hcm-highlight-filter);
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
& > a:hover {
|
| 48 |
+
opacity: 0 !important;
|
| 49 |
+
background: none !important;
|
| 50 |
+
box-shadow: none;
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
.popupAnnotation .popup {
|
| 55 |
+
outline: calc(1.5px * var(--total-scale-factor)) solid CanvasText !important;
|
| 56 |
+
background-color: ButtonFace !important;
|
| 57 |
+
color: ButtonText !important;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
.highlightArea:hover::after {
|
| 61 |
+
position: absolute;
|
| 62 |
+
top: 0;
|
| 63 |
+
left: 0;
|
| 64 |
+
width: 100%;
|
| 65 |
+
height: 100%;
|
| 66 |
+
backdrop-filter: var(--hcm-highlight-filter);
|
| 67 |
+
content: "";
|
| 68 |
+
pointer-events: none;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
.popupAnnotation.focused .popup {
|
| 72 |
+
outline: calc(3px * var(--total-scale-factor)) solid Highlight !important;
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
position: absolute;
|
| 77 |
+
top: 0;
|
| 78 |
+
left: 0;
|
| 79 |
+
pointer-events: none;
|
| 80 |
+
transform-origin: 0 0;
|
| 81 |
+
|
| 82 |
+
&[data-main-rotation="90"] .norotate {
|
| 83 |
+
transform: rotate(270deg) translateX(-100%);
|
| 84 |
+
}
|
| 85 |
+
&[data-main-rotation="180"] .norotate {
|
| 86 |
+
transform: rotate(180deg) translate(-100%, -100%);
|
| 87 |
+
}
|
| 88 |
+
&[data-main-rotation="270"] .norotate {
|
| 89 |
+
transform: rotate(90deg) translateY(-100%);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
&.disabled {
|
| 93 |
+
section,
|
| 94 |
+
.popup {
|
| 95 |
+
pointer-events: none;
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
.annotationContent {
|
| 100 |
+
position: absolute;
|
| 101 |
+
width: 100%;
|
| 102 |
+
height: 100%;
|
| 103 |
+
pointer-events: none;
|
| 104 |
+
|
| 105 |
+
&.freetext {
|
| 106 |
+
background: transparent;
|
| 107 |
+
border: none;
|
| 108 |
+
inset: 0;
|
| 109 |
+
overflow: visible;
|
| 110 |
+
white-space: nowrap;
|
| 111 |
+
font: 10px sans-serif;
|
| 112 |
+
line-height: 1.35;
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
section {
|
| 117 |
+
position: absolute;
|
| 118 |
+
text-align: initial;
|
| 119 |
+
pointer-events: auto;
|
| 120 |
+
box-sizing: border-box;
|
| 121 |
+
transform-origin: 0 0;
|
| 122 |
+
user-select: none;
|
| 123 |
+
|
| 124 |
+
&:has(div.annotationContent) {
|
| 125 |
+
canvas.annotationContent {
|
| 126 |
+
display: none;
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
.overlaidText {
|
| 131 |
+
position: absolute;
|
| 132 |
+
top: 0;
|
| 133 |
+
left: 0;
|
| 134 |
+
width: 0;
|
| 135 |
+
height: 0;
|
| 136 |
+
display: inline-block;
|
| 137 |
+
overflow: hidden;
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
.textLayer.selecting ~ & section {
|
| 142 |
+
pointer-events: none;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
:is(.linkAnnotation, .buttonWidgetAnnotation.pushButton) > a {
|
| 146 |
+
position: absolute;
|
| 147 |
+
font-size: 1em;
|
| 148 |
+
top: 0;
|
| 149 |
+
left: 0;
|
| 150 |
+
width: 100%;
|
| 151 |
+
height: 100%;
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
:is(.linkAnnotation, .buttonWidgetAnnotation.pushButton):not(.hasBorder)
|
| 155 |
+
> a:hover {
|
| 156 |
+
opacity: 0.2;
|
| 157 |
+
background-color: rgb(255 255 0);
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
.linkAnnotation.hasBorder:hover {
|
| 161 |
+
background-color: rgb(255 255 0 / 0.2);
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
.hasBorder {
|
| 165 |
+
background-size: 100% 100%;
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
.textAnnotation img {
|
| 169 |
+
position: absolute;
|
| 170 |
+
cursor: pointer;
|
| 171 |
+
width: 100%;
|
| 172 |
+
height: 100%;
|
| 173 |
+
top: 0;
|
| 174 |
+
left: 0;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
.textWidgetAnnotation :is(input, textarea),
|
| 178 |
+
.choiceWidgetAnnotation select,
|
| 179 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
|
| 180 |
+
background-image: var(--annotation-unfocused-field-background);
|
| 181 |
+
border: 2px solid var(--input-unfocused-border-color);
|
| 182 |
+
box-sizing: border-box;
|
| 183 |
+
font: calc(9px * var(--total-scale-factor)) sans-serif;
|
| 184 |
+
height: 100%;
|
| 185 |
+
margin: 0;
|
| 186 |
+
vertical-align: top;
|
| 187 |
+
width: 100%;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
.textWidgetAnnotation :is(input, textarea):required,
|
| 191 |
+
.choiceWidgetAnnotation select:required,
|
| 192 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
|
| 193 |
+
outline: 1.5px solid red;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
.choiceWidgetAnnotation select option {
|
| 197 |
+
padding: 0;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
.buttonWidgetAnnotation.radioButton input {
|
| 201 |
+
border-radius: 50%;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
.textWidgetAnnotation textarea {
|
| 205 |
+
resize: none;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
.textWidgetAnnotation :is(input, textarea)[disabled],
|
| 209 |
+
.choiceWidgetAnnotation select[disabled],
|
| 210 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] {
|
| 211 |
+
background: none;
|
| 212 |
+
border: 2px solid var(--input-disabled-border-color);
|
| 213 |
+
cursor: not-allowed;
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
.textWidgetAnnotation :is(input, textarea):hover,
|
| 217 |
+
.choiceWidgetAnnotation select:hover,
|
| 218 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover {
|
| 219 |
+
border: 2px solid var(--input-hover-border-color);
|
| 220 |
+
}
|
| 221 |
+
.textWidgetAnnotation :is(input, textarea):hover,
|
| 222 |
+
.choiceWidgetAnnotation select:hover,
|
| 223 |
+
.buttonWidgetAnnotation.checkBox input:hover {
|
| 224 |
+
border-radius: 2px;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
.textWidgetAnnotation :is(input, textarea):focus,
|
| 228 |
+
.choiceWidgetAnnotation select:focus {
|
| 229 |
+
background: none;
|
| 230 |
+
border: 2px solid var(--input-focus-border-color);
|
| 231 |
+
border-radius: 2px;
|
| 232 |
+
outline: var(--input-focus-outline);
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) :focus {
|
| 236 |
+
background-image: none;
|
| 237 |
+
background-color: transparent;
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
.buttonWidgetAnnotation.checkBox :focus {
|
| 241 |
+
border: 2px solid var(--input-focus-border-color);
|
| 242 |
+
border-radius: 2px;
|
| 243 |
+
outline: var(--input-focus-outline);
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
.buttonWidgetAnnotation.radioButton :focus {
|
| 247 |
+
border: 2px solid var(--input-focus-border-color);
|
| 248 |
+
outline: var(--input-focus-outline);
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
.buttonWidgetAnnotation.checkBox input:checked::before,
|
| 252 |
+
.buttonWidgetAnnotation.checkBox input:checked::after,
|
| 253 |
+
.buttonWidgetAnnotation.radioButton input:checked::before {
|
| 254 |
+
background-color: CanvasText;
|
| 255 |
+
content: "";
|
| 256 |
+
display: block;
|
| 257 |
+
position: absolute;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
.buttonWidgetAnnotation.checkBox input:checked::before,
|
| 261 |
+
.buttonWidgetAnnotation.checkBox input:checked::after {
|
| 262 |
+
height: 80%;
|
| 263 |
+
left: 45%;
|
| 264 |
+
width: 1px;
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
.buttonWidgetAnnotation.checkBox input:checked::before {
|
| 268 |
+
transform: rotate(45deg);
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
.buttonWidgetAnnotation.checkBox input:checked::after {
|
| 272 |
+
transform: rotate(-45deg);
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
.buttonWidgetAnnotation.radioButton input:checked::before {
|
| 276 |
+
border-radius: 50%;
|
| 277 |
+
height: 50%;
|
| 278 |
+
left: 25%;
|
| 279 |
+
top: 25%;
|
| 280 |
+
width: 50%;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
.textWidgetAnnotation input.comb {
|
| 284 |
+
font-family: monospace;
|
| 285 |
+
padding-left: 2px;
|
| 286 |
+
padding-right: 0;
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
.textWidgetAnnotation input.comb:focus {
|
| 290 |
+
/*
|
| 291 |
+
* Letter spacing is placed on the right side of each character. Hence, the
|
| 292 |
+
* letter spacing of the last character may be placed outside the visible
|
| 293 |
+
* area, causing horizontal scrolling. We avoid this by extending the width
|
| 294 |
+
* when the element has focus and revert this when it loses focus.
|
| 295 |
+
*/
|
| 296 |
+
width: 103%;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
|
| 300 |
+
appearance: none;
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
.fileAttachmentAnnotation .popupTriggerArea {
|
| 304 |
+
height: 100%;
|
| 305 |
+
width: 100%;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
.popupAnnotation {
|
| 309 |
+
position: absolute;
|
| 310 |
+
font-size: calc(9px * var(--total-scale-factor));
|
| 311 |
+
pointer-events: none;
|
| 312 |
+
width: max-content;
|
| 313 |
+
max-width: 45%;
|
| 314 |
+
height: auto;
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
.popup {
|
| 318 |
+
background-color: rgb(255 255 153);
|
| 319 |
+
color: black;
|
| 320 |
+
box-shadow: 0 calc(2px * var(--total-scale-factor))
|
| 321 |
+
calc(5px * var(--total-scale-factor)) rgb(136 136 136);
|
| 322 |
+
border-radius: calc(2px * var(--total-scale-factor));
|
| 323 |
+
outline: 1.5px solid rgb(255 255 74);
|
| 324 |
+
padding: calc(6px * var(--total-scale-factor));
|
| 325 |
+
cursor: pointer;
|
| 326 |
+
font: message-box;
|
| 327 |
+
white-space: normal;
|
| 328 |
+
word-wrap: break-word;
|
| 329 |
+
pointer-events: auto;
|
| 330 |
+
user-select: text;
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
.popupAnnotation.focused .popup {
|
| 334 |
+
outline-width: 3px;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
.popup * {
|
| 338 |
+
font-size: calc(9px * var(--total-scale-factor));
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
.popup > .header {
|
| 342 |
+
display: inline-block;
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
.popup > .header > .title {
|
| 346 |
+
display: inline;
|
| 347 |
+
font-weight: bold;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
.popup > .header .popupDate {
|
| 351 |
+
display: inline-block;
|
| 352 |
+
margin-left: calc(5px * var(--total-scale-factor));
|
| 353 |
+
width: fit-content;
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
.popupContent {
|
| 357 |
+
border-top: 1px solid rgb(51 51 51);
|
| 358 |
+
margin-top: calc(2px * var(--total-scale-factor));
|
| 359 |
+
padding-top: calc(2px * var(--total-scale-factor));
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
.richText > * {
|
| 363 |
+
white-space: pre-wrap;
|
| 364 |
+
font-size: calc(9px * var(--total-scale-factor));
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
.popupTriggerArea {
|
| 368 |
+
cursor: pointer;
|
| 369 |
+
|
| 370 |
+
&:hover {
|
| 371 |
+
backdrop-filter: var(--hcm-highlight-filter);
|
| 372 |
+
}
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
section svg {
|
| 376 |
+
position: absolute;
|
| 377 |
+
width: 100%;
|
| 378 |
+
height: 100%;
|
| 379 |
+
top: 0;
|
| 380 |
+
left: 0;
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
.annotationTextContent {
|
| 384 |
+
position: absolute;
|
| 385 |
+
width: 100%;
|
| 386 |
+
height: 100%;
|
| 387 |
+
opacity: 0;
|
| 388 |
+
color: transparent;
|
| 389 |
+
user-select: none;
|
| 390 |
+
pointer-events: none;
|
| 391 |
+
|
| 392 |
+
span {
|
| 393 |
+
width: 100%;
|
| 394 |
+
display: inline-block;
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
svg.quadrilateralsContainer {
|
| 399 |
+
contain: strict;
|
| 400 |
+
width: 0;
|
| 401 |
+
height: 0;
|
| 402 |
+
position: absolute;
|
| 403 |
+
top: 0;
|
| 404 |
+
left: 0;
|
| 405 |
+
z-index: -1;
|
| 406 |
+
}
|
| 407 |
+
}
|
packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-H.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d92a261336dc18b8c03a46eb4d462382d33f4338fa195d303256b2031434c874
|
| 3 |
+
size 2404
|
packages/foliate-js/vendor/pdfjs/cmaps/78-EUC-V.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:61670bebc4e4827b67230c054fd0d820d6e30c3584d02e386804e62bbedc032a
|
| 3 |
+
size 173
|
packages/foliate-js/vendor/pdfjs/cmaps/78-H.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ece6415b853d61e1b2560165151407d35cf16e6556932b85a13ea75276b77402
|
| 3 |
+
size 2379
|
packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-H.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:696b1f973c97623496703809eaaa5f9b40696c77540057413f4b826a08edfa7b
|
| 3 |
+
size 2398
|
packages/foliate-js/vendor/pdfjs/cmaps/78-RKSJ-V.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53cb6d560ab377da48cf65d6dcacb0bdb31f13fab7066c580de38c12a73a7ff9
|
| 3 |
+
size 173
|
packages/foliate-js/vendor/pdfjs/cmaps/78-V.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:289000f02fd34872b6975503217f33abae6bee676e7d28f640473a67c8db1712
|
| 3 |
+
size 169
|
packages/foliate-js/vendor/pdfjs/cmaps/78ms-RKSJ-H.bcmap
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a2442595218f5f8bd8e1b42188e368587d876cfe0cc4cd87196f077c878f72e2
|
| 3 |
+
size 2651
|