pulpweaver4-epub 0.0.0-stage → 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +121 -0
- package/README.md +29 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +28 -0
- package/dist/options.d.ts +22 -0
- package/dist/options.js +55 -0
- package/dist/output.d.ts +13 -0
- package/dist/output.js +356 -0
- package/dist/package.d.ts +77 -0
- package/dist/package.js +173 -0
- package/dist/page-list.d.ts +36 -0
- package/dist/page-list.js +207 -0
- package/dist/problems.d.ts +11 -0
- package/dist/problems.js +10 -0
- package/dist/xhtml.d.ts +34 -0
- package/dist/xhtml.js +114 -0
- package/docs/README.md +18 -0
- package/docs/guide.md +81 -0
- package/docs/reference/epub-output.md +39 -0
- package/docs/reference/index.md +33 -0
- package/docs/reference/options.md +81 -0
- package/package.json +57 -4
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Where the package's files are in the zip. */
|
|
2
|
+
export declare const ROOT = "EPUB";
|
|
3
|
+
export declare const PACKAGE_FILE = "package.opf";
|
|
4
|
+
export declare const NAV_FILE = "nav.xhtml";
|
|
5
|
+
/** A file of the publication, by its path from the package document. */
|
|
6
|
+
export interface PublicationFile {
|
|
7
|
+
readonly path: string;
|
|
8
|
+
readonly data: Uint8Array | string;
|
|
9
|
+
/** Its manifest item's properties (`mathml`, `nav`, `cover-image`). */
|
|
10
|
+
readonly properties?: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
/** A content document in the spine. */
|
|
13
|
+
export interface SpineItem {
|
|
14
|
+
readonly path: string;
|
|
15
|
+
readonly linear?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** The package document's metadata. */
|
|
18
|
+
export interface PackageMetadata {
|
|
19
|
+
readonly identifier: string;
|
|
20
|
+
readonly title: string;
|
|
21
|
+
readonly language: string;
|
|
22
|
+
/** `dcterms:modified`, in UTC, to the second. */
|
|
23
|
+
readonly modified: Date;
|
|
24
|
+
readonly creators: readonly string[];
|
|
25
|
+
readonly publisher?: string;
|
|
26
|
+
/** The print edition its page list is from, its `dc:source`, refined as the source of the pagination. */
|
|
27
|
+
readonly pageSource?: string;
|
|
28
|
+
readonly accessibility: Accessibility;
|
|
29
|
+
}
|
|
30
|
+
/** What the package says of its accessibility, in schema.org's terms (EPUB Accessibility 1.1). */
|
|
31
|
+
export interface Accessibility {
|
|
32
|
+
readonly accessModes: readonly string[];
|
|
33
|
+
readonly accessModesSufficient: readonly (readonly string[])[];
|
|
34
|
+
readonly features: readonly string[];
|
|
35
|
+
readonly hazards: readonly string[];
|
|
36
|
+
readonly summary: string;
|
|
37
|
+
}
|
|
38
|
+
/** A file's media type by its extension, if it is one of EPUB's core media types. */
|
|
39
|
+
export declare function mediaType(path: string): string | undefined;
|
|
40
|
+
/** The package document. */
|
|
41
|
+
export declare function packageDocument(metadata: PackageMetadata, files: readonly PublicationFile[], spine: readonly SpineItem[]): string;
|
|
42
|
+
/** The OCF's container file, which names the package document. */
|
|
43
|
+
export declare function containerXml(): string;
|
|
44
|
+
/** An entry of the contents: a heading, where it is, and the headings under it. */
|
|
45
|
+
export interface TocEntry {
|
|
46
|
+
readonly title: string;
|
|
47
|
+
readonly href: string;
|
|
48
|
+
readonly children: readonly TocEntry[];
|
|
49
|
+
}
|
|
50
|
+
/** A link in a navigation list. */
|
|
51
|
+
export interface NavLink {
|
|
52
|
+
readonly title: string;
|
|
53
|
+
readonly href: string;
|
|
54
|
+
/** A landmark's `epub:type` (`toc`, `bodymatter`). */
|
|
55
|
+
readonly type?: string;
|
|
56
|
+
}
|
|
57
|
+
/** The words the navigation document shows, in the book's language. */
|
|
58
|
+
export interface NavLabels {
|
|
59
|
+
readonly contents: string;
|
|
60
|
+
readonly pages: string;
|
|
61
|
+
readonly landmarks: string;
|
|
62
|
+
}
|
|
63
|
+
/** The navigation document: the contents, the landmarks and the page list, if there is one. */
|
|
64
|
+
export declare function navDocument(options: {
|
|
65
|
+
title: string;
|
|
66
|
+
language: string;
|
|
67
|
+
labels: NavLabels;
|
|
68
|
+
toc: readonly TocEntry[];
|
|
69
|
+
landmarks: readonly NavLink[];
|
|
70
|
+
pages?: readonly NavLink[];
|
|
71
|
+
}): string;
|
|
72
|
+
/**
|
|
73
|
+
* The publication as an EPUB: the `mimetype` first and stored, then the
|
|
74
|
+
* container file and the package's files, each dated `mtime` (milliseconds
|
|
75
|
+
* since 1970), so the same files give the same bytes.
|
|
76
|
+
*/
|
|
77
|
+
export declare function zipEpub(files: readonly PublicationFile[], mtime: number): Uint8Array;
|
package/dist/package.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The EPUB's package (EPUB 3.3, https://www.w3.org/TR/epub-33/): its
|
|
3
|
+
* container file, its package document (the metadata, accessibility
|
|
4
|
+
* metadata among it, the manifest and the spine) and its navigation
|
|
5
|
+
* document (the contents, the landmarks and the page list), and the zip
|
|
6
|
+
* they go in, the `mimetype` first and stored, as the OCF asks.
|
|
7
|
+
*/
|
|
8
|
+
import { zipSync } from 'fflate';
|
|
9
|
+
import { setEpubType, xhtmlDocument, XHTML } from './xhtml.js';
|
|
10
|
+
/** Where the package's files are in the zip. */
|
|
11
|
+
export const ROOT = 'EPUB';
|
|
12
|
+
export const PACKAGE_FILE = 'package.opf';
|
|
13
|
+
export const NAV_FILE = 'nav.xhtml';
|
|
14
|
+
const MEDIA_TYPES = {
|
|
15
|
+
xhtml: 'application/xhtml+xml',
|
|
16
|
+
css: 'text/css',
|
|
17
|
+
otf: 'font/otf',
|
|
18
|
+
ttf: 'font/ttf',
|
|
19
|
+
woff: 'font/woff',
|
|
20
|
+
woff2: 'font/woff2',
|
|
21
|
+
svg: 'image/svg+xml',
|
|
22
|
+
png: 'image/png',
|
|
23
|
+
jpg: 'image/jpeg',
|
|
24
|
+
jpeg: 'image/jpeg',
|
|
25
|
+
gif: 'image/gif',
|
|
26
|
+
webp: 'image/webp',
|
|
27
|
+
js: 'application/javascript',
|
|
28
|
+
};
|
|
29
|
+
/** A file's media type by its extension, if it is one of EPUB's core media types. */
|
|
30
|
+
export function mediaType(path) {
|
|
31
|
+
return MEDIA_TYPES[path.slice(path.lastIndexOf('.') + 1).toLowerCase()];
|
|
32
|
+
}
|
|
33
|
+
function escapeXml(s) {
|
|
34
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
35
|
+
}
|
|
36
|
+
/** Manifest ids for paths: XML names, unique, as alike to the path as can be. */
|
|
37
|
+
function itemIds(paths) {
|
|
38
|
+
const ids = new Map();
|
|
39
|
+
const used = new Set();
|
|
40
|
+
for (const path of paths) {
|
|
41
|
+
let id = path.replace(/[^A-Za-z0-9._-]+/g, '-');
|
|
42
|
+
if (!/^[A-Za-z_]/.test(id))
|
|
43
|
+
id = `x${id}`;
|
|
44
|
+
let unique = id;
|
|
45
|
+
for (let n = 2; used.has(unique); n++)
|
|
46
|
+
unique = `${id}-${n}`;
|
|
47
|
+
used.add(unique);
|
|
48
|
+
ids.set(path, unique);
|
|
49
|
+
}
|
|
50
|
+
return ids;
|
|
51
|
+
}
|
|
52
|
+
/** The package document. */
|
|
53
|
+
export function packageDocument(metadata, files, spine) {
|
|
54
|
+
const ids = itemIds(files.map((f) => f.path));
|
|
55
|
+
const meta = (property, value) => ` <meta property="${property}">${escapeXml(value)}</meta>`;
|
|
56
|
+
const a11y = metadata.accessibility;
|
|
57
|
+
const lines = [
|
|
58
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
59
|
+
`<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="pub-id" xml:lang="${escapeXml(metadata.language)}">`,
|
|
60
|
+
' <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">',
|
|
61
|
+
` <dc:identifier id="pub-id">${escapeXml(metadata.identifier)}</dc:identifier>`,
|
|
62
|
+
` <dc:title>${escapeXml(metadata.title)}</dc:title>`,
|
|
63
|
+
` <dc:language>${escapeXml(metadata.language)}</dc:language>`,
|
|
64
|
+
...metadata.creators.map((c, i) => ` <dc:creator id="creator-${i + 1}">${escapeXml(c)}</dc:creator>`),
|
|
65
|
+
...(metadata.publisher !== undefined ? [` <dc:publisher>${escapeXml(metadata.publisher)}</dc:publisher>`] : []),
|
|
66
|
+
...(metadata.pageSource !== undefined
|
|
67
|
+
? [` <dc:source id="page-source">${escapeXml(metadata.pageSource)}</dc:source>`, ' <meta refines="#page-source" property="source-of">pagination</meta>']
|
|
68
|
+
: []),
|
|
69
|
+
meta('dcterms:modified', metadata.modified.toISOString().replace(/\.\d+Z$/, 'Z')),
|
|
70
|
+
...a11y.accessModes.map((m) => meta('schema:accessMode', m)),
|
|
71
|
+
...a11y.accessModesSufficient.map((m) => meta('schema:accessModeSufficient', m.join(','))),
|
|
72
|
+
...a11y.features.map((f) => meta('schema:accessibilityFeature', f)),
|
|
73
|
+
...a11y.hazards.map((h) => meta('schema:accessibilityHazard', h)),
|
|
74
|
+
meta('schema:accessibilitySummary', a11y.summary),
|
|
75
|
+
' </metadata>',
|
|
76
|
+
' <manifest>',
|
|
77
|
+
...files.map((f) => {
|
|
78
|
+
const type = mediaType(f.path) ?? 'application/octet-stream';
|
|
79
|
+
const properties = f.properties?.length ? ` properties="${f.properties.join(' ')}"` : '';
|
|
80
|
+
return ` <item id="${ids.get(f.path)}" href="${escapeXml(encodeURI(f.path))}" media-type="${type}"${properties}/>`;
|
|
81
|
+
}),
|
|
82
|
+
' </manifest>',
|
|
83
|
+
' <spine>',
|
|
84
|
+
...spine.map((s) => ` <itemref idref="${ids.get(s.path)}"${s.linear === false ? ' linear="no"' : ''}/>`),
|
|
85
|
+
' </spine>',
|
|
86
|
+
'</package>',
|
|
87
|
+
'',
|
|
88
|
+
];
|
|
89
|
+
return lines.join('\n');
|
|
90
|
+
}
|
|
91
|
+
/** The OCF's container file, which names the package document. */
|
|
92
|
+
export function containerXml() {
|
|
93
|
+
return [
|
|
94
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
95
|
+
'<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">',
|
|
96
|
+
' <rootfiles>',
|
|
97
|
+
` <rootfile full-path="${ROOT}/${PACKAGE_FILE}" media-type="application/oebps-package+xml"/>`,
|
|
98
|
+
' </rootfiles>',
|
|
99
|
+
'</container>',
|
|
100
|
+
'',
|
|
101
|
+
].join('\n');
|
|
102
|
+
}
|
|
103
|
+
/** The navigation document: the contents, the landmarks and the page list, if there is one. */
|
|
104
|
+
export function navDocument(options) {
|
|
105
|
+
const doc = document.implementation.createHTMLDocument('');
|
|
106
|
+
const el = (name, text) => {
|
|
107
|
+
const e = doc.createElementNS(XHTML, name);
|
|
108
|
+
if (text !== undefined)
|
|
109
|
+
e.textContent = text;
|
|
110
|
+
return e;
|
|
111
|
+
};
|
|
112
|
+
const link = (l) => {
|
|
113
|
+
const a = el('a', l.title);
|
|
114
|
+
a.setAttribute('href', l.href);
|
|
115
|
+
if (l.type)
|
|
116
|
+
setEpubType(a, l.type);
|
|
117
|
+
return a;
|
|
118
|
+
};
|
|
119
|
+
const list = (entries) => {
|
|
120
|
+
const ol = el('ol');
|
|
121
|
+
for (const e of entries) {
|
|
122
|
+
const li = el('li');
|
|
123
|
+
li.append(link(e));
|
|
124
|
+
if (e.children.length)
|
|
125
|
+
li.append(list(e.children));
|
|
126
|
+
ol.append(li);
|
|
127
|
+
}
|
|
128
|
+
return ol;
|
|
129
|
+
};
|
|
130
|
+
const nav = (type, role, heading, body, hidden) => {
|
|
131
|
+
const n = el('nav');
|
|
132
|
+
setEpubType(n, type);
|
|
133
|
+
n.id = type;
|
|
134
|
+
if (role)
|
|
135
|
+
n.setAttribute('role', role);
|
|
136
|
+
if (hidden)
|
|
137
|
+
n.setAttribute('hidden', 'hidden');
|
|
138
|
+
n.append(el('h2', heading), body);
|
|
139
|
+
return n;
|
|
140
|
+
};
|
|
141
|
+
const navs = [nav('toc', 'doc-toc', options.labels.contents, list(options.toc), false)];
|
|
142
|
+
if (options.landmarks.length)
|
|
143
|
+
navs.push(nav('landmarks', undefined, options.labels.landmarks, flat(options.landmarks), true));
|
|
144
|
+
if (options.pages?.length)
|
|
145
|
+
navs.push(nav('page-list', 'doc-pagelist', options.labels.pages, flat(options.pages), true));
|
|
146
|
+
return xhtmlDocument({ title: options.title, language: options.language, body: navs });
|
|
147
|
+
function flat(links) {
|
|
148
|
+
const ol = el('ol');
|
|
149
|
+
for (const l of links) {
|
|
150
|
+
const li = el('li');
|
|
151
|
+
li.append(link(l));
|
|
152
|
+
ol.append(li);
|
|
153
|
+
}
|
|
154
|
+
return ol;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* The publication as an EPUB: the `mimetype` first and stored, then the
|
|
159
|
+
* container file and the package's files, each dated `mtime` (milliseconds
|
|
160
|
+
* since 1970), so the same files give the same bytes.
|
|
161
|
+
*/
|
|
162
|
+
export function zipEpub(files, mtime) {
|
|
163
|
+
const encode = (d) => (typeof d === 'string' ? new TextEncoder().encode(d) : d);
|
|
164
|
+
// A zip's dates start in 1980.
|
|
165
|
+
const date = new Date(Math.max(mtime, Date.UTC(1980, 0, 1, 12)));
|
|
166
|
+
const tree = {
|
|
167
|
+
mimetype: [encode('application/epub+zip'), { level: 0 }],
|
|
168
|
+
'META-INF/container.xml': encode(containerXml()),
|
|
169
|
+
};
|
|
170
|
+
for (const f of files)
|
|
171
|
+
tree[`${ROOT}/${f.path}`] = encode(f.data);
|
|
172
|
+
return zipSync(tree, { mtime: date });
|
|
173
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AstNode, Book } from 'pulpweaver4/test';
|
|
2
|
+
/** Where a page of the print edition begins. */
|
|
3
|
+
export interface PageStart {
|
|
4
|
+
/** Its number, counted from 1. */
|
|
5
|
+
readonly number: number;
|
|
6
|
+
/** Its label, as the print edition prints it in its folio and its PDF's page labels (`iii`, `12`). */
|
|
7
|
+
readonly label: string;
|
|
8
|
+
/** The node whose element holds its first letter, and how many of that element's letters earlier pages hold; none if it has nothing the EPUB has. */
|
|
9
|
+
readonly at?: {
|
|
10
|
+
readonly node: AstNode;
|
|
11
|
+
readonly letters: number;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** How many letters and digits a text has. */
|
|
15
|
+
export declare function letterCount(text: string): number;
|
|
16
|
+
/** Where each page of a laid-out print edition begins. */
|
|
17
|
+
export declare function pageStarts(book: Book): PageStart[];
|
|
18
|
+
/** An EPUB document: its DOM, and the elements each AST node was rendered as in it. */
|
|
19
|
+
export interface PagedDocument {
|
|
20
|
+
readonly root: Element;
|
|
21
|
+
elementsOf(node: AstNode): readonly Element[];
|
|
22
|
+
}
|
|
23
|
+
/** Where a page break was put: its page, and the document it is in. */
|
|
24
|
+
export interface PlacedBreak {
|
|
25
|
+
readonly start: PageStart;
|
|
26
|
+
readonly document: number;
|
|
27
|
+
readonly marker: Element;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Puts a page break, as `marker` makes it, where each page begins in the
|
|
31
|
+
* documents, which are the EPUB's in reading order. A page whose start
|
|
32
|
+
* isn't in them gets its break just before the next page's, and pages after
|
|
33
|
+
* the last start at the end of the last document. Returns the breaks in
|
|
34
|
+
* page order.
|
|
35
|
+
*/
|
|
36
|
+
export declare function placePageBreaks(documents: readonly PagedDocument[], starts: readonly PageStart[], marker: (start: PageStart) => Element): PlacedBreak[];
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page list (https://plans.inkylabs.com/pulpweaver#how-a-build-runs):
|
|
3
|
+
* where each page of a print edition begins, found in that edition's
|
|
4
|
+
* layout, and marked in the EPUB's text with a page break that the
|
|
5
|
+
* navigation's page list links to.
|
|
6
|
+
*
|
|
7
|
+
* A page begins at its main text's first letter (its floats' if its main
|
|
8
|
+
* text has none), which is somewhere in an element rendered for an AST
|
|
9
|
+
* node: the start is that node, and how many letters of the node's element
|
|
10
|
+
* the pages before hold. The EPUB is rendered from the same manuscript, so
|
|
11
|
+
* the node's element is there too, and the break goes before the same
|
|
12
|
+
* letter, or before the word it ends if a hyphen split that word. Letters
|
|
13
|
+
* are counted in the source's text alone: generated text, which the core
|
|
14
|
+
* marks (`isGenerated`), differs between print and screen (numbers, page
|
|
15
|
+
* references, note calls, an index's locators) or is on the pages alone (a
|
|
16
|
+
* table's header rows repeated on a later page), and spaces and hyphens are
|
|
17
|
+
* set differently by the layout. A page with nothing the EPUB
|
|
18
|
+
* has (a blank page, a print-only half-title) begins where the next page
|
|
19
|
+
* does.
|
|
20
|
+
*/
|
|
21
|
+
import { isGenerated } from 'pulpweaver4';
|
|
22
|
+
/** What a print page's text is laid out in: the main text, then the floats. */
|
|
23
|
+
const REGIONS = ['.pw-main', '.pw-top-floats', '.pw-bottom-floats'];
|
|
24
|
+
/** Content with no letters that a page can begin with. */
|
|
25
|
+
const ATOMIC = new Set(['img', 'svg', 'math', 'video', 'audio', 'canvas', 'iframe', 'object']);
|
|
26
|
+
const LETTER = /[\p{L}\p{N}]/gu;
|
|
27
|
+
/** How many letters and digits a text has. */
|
|
28
|
+
export function letterCount(text) {
|
|
29
|
+
return text.match(LETTER)?.length ?? 0;
|
|
30
|
+
}
|
|
31
|
+
/** The source's text under `root`, its text nodes in document order. */
|
|
32
|
+
function* sourceTexts(root) {
|
|
33
|
+
const doc = root.ownerDocument ?? root;
|
|
34
|
+
const walker = doc.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */);
|
|
35
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode())
|
|
36
|
+
if (!isGenerated(n))
|
|
37
|
+
yield n;
|
|
38
|
+
}
|
|
39
|
+
/** The letters of the source's text under `root`. */
|
|
40
|
+
function lettersIn(root) {
|
|
41
|
+
let n = 0;
|
|
42
|
+
for (const t of sourceTexts(root))
|
|
43
|
+
n += letterCount(t.data);
|
|
44
|
+
return n;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The first thing a page shows that has a place in the source: the first
|
|
48
|
+
* text with a letter, or an image, in its main text, else its floats; none
|
|
49
|
+
* on a blank page.
|
|
50
|
+
*/
|
|
51
|
+
function firstContent(page) {
|
|
52
|
+
for (const selector of REGIONS) {
|
|
53
|
+
const region = page.querySelector(selector);
|
|
54
|
+
if (!region)
|
|
55
|
+
continue;
|
|
56
|
+
const doc = region.ownerDocument;
|
|
57
|
+
const walker = doc.createTreeWalker(region, 1 | 4 /* NodeFilter.SHOW_ELEMENT | SHOW_TEXT */);
|
|
58
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
59
|
+
if (isGenerated(n))
|
|
60
|
+
continue;
|
|
61
|
+
if (n.nodeType === 3 ? letterCount(n.data) > 0 : ATOMIC.has(n.localName))
|
|
62
|
+
return n;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The element of the page that `content` is the start of, rendered for a
|
|
69
|
+
* node of its own: the nearest that is one of its node's elements (not an
|
|
70
|
+
* element the layout made, nor one the renderer added inside a node's).
|
|
71
|
+
*/
|
|
72
|
+
function ownElement(book, content) {
|
|
73
|
+
for (let el = content.nodeType === 1 ? content : content.parentElement; el; el = el.parentElement) {
|
|
74
|
+
const key = el.dataset?.['pwKey'];
|
|
75
|
+
if (key === undefined)
|
|
76
|
+
continue;
|
|
77
|
+
const node = book.nodeOf(el);
|
|
78
|
+
if (node !== undefined && book.resolve(node).keys.has(key))
|
|
79
|
+
return { element: el, node };
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
/** Where each page of a laid-out print edition begins. */
|
|
84
|
+
export function pageStarts(book) {
|
|
85
|
+
const pages = [...book.pages];
|
|
86
|
+
// The letters each key's fragments hold, on each page, counted when first asked for.
|
|
87
|
+
const held = new Map();
|
|
88
|
+
const lettersBefore = (key, page) => {
|
|
89
|
+
let counts = held.get(key);
|
|
90
|
+
if (!counts) {
|
|
91
|
+
counts = pages.map((p) => {
|
|
92
|
+
let n = 0;
|
|
93
|
+
for (const area of p.element?.querySelectorAll('.pw-area') ?? []) {
|
|
94
|
+
for (const fragment of area.querySelectorAll(`[data-pw-key="${CSS.escape(key)}"]`))
|
|
95
|
+
n += lettersIn(fragment);
|
|
96
|
+
}
|
|
97
|
+
return n;
|
|
98
|
+
});
|
|
99
|
+
held.set(key, counts);
|
|
100
|
+
}
|
|
101
|
+
return counts.slice(0, page).reduce((a, b) => a + b, 0);
|
|
102
|
+
};
|
|
103
|
+
return pages.map((page, i) => {
|
|
104
|
+
const content = page.element && !page.blank ? firstContent(page.element) : undefined;
|
|
105
|
+
const own = content ? ownElement(book, content) : undefined;
|
|
106
|
+
const start = { number: page.number, label: page.label };
|
|
107
|
+
return own ? { ...start, at: { node: own.node, letters: lettersBefore(own.element.dataset['pwKey'], i) } } : start;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Puts a page break, as `marker` makes it, where each page begins in the
|
|
112
|
+
* documents, which are the EPUB's in reading order. A page whose start
|
|
113
|
+
* isn't in them gets its break just before the next page's, and pages after
|
|
114
|
+
* the last start at the end of the last document. Returns the breaks in
|
|
115
|
+
* page order.
|
|
116
|
+
*/
|
|
117
|
+
export function placePageBreaks(documents, starts, marker) {
|
|
118
|
+
const placed = starts.map(() => undefined);
|
|
119
|
+
let pending = [];
|
|
120
|
+
// Places the breaks of pages that had nowhere of their own before `here`, a break just placed.
|
|
121
|
+
const flush = (here) => {
|
|
122
|
+
for (const start of pending) {
|
|
123
|
+
const m = marker(start);
|
|
124
|
+
here.marker.before(m);
|
|
125
|
+
placed[starts.indexOf(start)] = { start, document: here.document, marker: m };
|
|
126
|
+
}
|
|
127
|
+
pending = [];
|
|
128
|
+
};
|
|
129
|
+
for (const [i, start] of starts.entries()) {
|
|
130
|
+
const found = start.at ? locate(documents, start.at) : undefined;
|
|
131
|
+
if (!found) {
|
|
132
|
+
pending.push(start);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const m = marker(start);
|
|
136
|
+
insertAt(found.element, start.at.letters, m);
|
|
137
|
+
const here = { start, document: found.document, marker: m };
|
|
138
|
+
placed[i] = here;
|
|
139
|
+
flush(here);
|
|
140
|
+
}
|
|
141
|
+
const last = documents.length - 1;
|
|
142
|
+
for (const start of pending) {
|
|
143
|
+
const m = marker(start);
|
|
144
|
+
const root = documents[last].root;
|
|
145
|
+
root.append(m);
|
|
146
|
+
placed[starts.indexOf(start)] = { start, document: last, marker: m };
|
|
147
|
+
}
|
|
148
|
+
return placed.filter((p) => p !== undefined);
|
|
149
|
+
}
|
|
150
|
+
/** A node's first element in the documents, and which document it is in. */
|
|
151
|
+
function locate(documents, at) {
|
|
152
|
+
for (const [document, d] of documents.entries()) {
|
|
153
|
+
const element = d.elementsOf(at.node)[0];
|
|
154
|
+
if (element)
|
|
155
|
+
return { element, document };
|
|
156
|
+
}
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
/** Elements a page break can't be put before, whose parent holds only their own kind. */
|
|
160
|
+
const NOT_BEFORE = new Set(['li', 'dt', 'dd', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'caption', 'colgroup', 'col', 'summary', 'option', 'figcaption', 'legend']);
|
|
161
|
+
/**
|
|
162
|
+
* Puts `marker` before the letter of `element` that `letters` letters come
|
|
163
|
+
* before, moved past the rest of a word a page break split; at the
|
|
164
|
+
* element's start, before the element itself if its parent can take one.
|
|
165
|
+
*/
|
|
166
|
+
function insertAt(element, letters, marker) {
|
|
167
|
+
if (letters === 0) {
|
|
168
|
+
if (!NOT_BEFORE.has(element.localName) && element.parentElement && !NOT_BEFORE.has(element.parentElement.localName))
|
|
169
|
+
element.before(marker);
|
|
170
|
+
else
|
|
171
|
+
element.prepend(marker);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
let seen = 0;
|
|
175
|
+
let after;
|
|
176
|
+
for (const text of sourceTexts(element)) {
|
|
177
|
+
after = text;
|
|
178
|
+
const count = letterCount(text.data);
|
|
179
|
+
if (seen + count <= letters) {
|
|
180
|
+
seen += count;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
// The letter is in this text: find its offset, then the end of the word it is in, if a break split it.
|
|
184
|
+
let offset = 0;
|
|
185
|
+
for (const m of text.data.matchAll(LETTER)) {
|
|
186
|
+
if (seen === letters) {
|
|
187
|
+
offset = m.index;
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
seen++;
|
|
191
|
+
}
|
|
192
|
+
// A letter, a mark or a soft hyphen just before it: a word the page break split.
|
|
193
|
+
if (offset > 0 && /[\p{L}\p{N}\p{M}\u00ad]/u.test(text.data[offset - 1])) {
|
|
194
|
+
while (offset < text.data.length && /[\p{L}\p{N}\p{M}-]/u.test(text.data[offset]))
|
|
195
|
+
offset++;
|
|
196
|
+
while (offset < text.data.length && /\s/u.test(text.data[offset]))
|
|
197
|
+
offset++;
|
|
198
|
+
}
|
|
199
|
+
text.splitText(offset).before(marker);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
// Fewer letters than the print edition's: the end of the element's text.
|
|
203
|
+
if (after)
|
|
204
|
+
after.after(marker);
|
|
205
|
+
else
|
|
206
|
+
element.append(marker);
|
|
207
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The problems the `epub` output reports, by code, each with what it means
|
|
3
|
+
* for the reference (`scripts/reference.mjs`), which fails on a code the
|
|
4
|
+
* output reports that isn't here.
|
|
5
|
+
*/
|
|
6
|
+
export declare const PROBLEMS: {
|
|
7
|
+
readonly 'epub-date': 'The build has no date. An EPUB must say when it was modified (`dcterms:modified`), and pulpweaver4 never takes a date from the clock, so the edition isn’t written: set `date` in `pulpweaver4.toml`, or `SOURCE_DATE_EPOCH`.';
|
|
8
|
+
readonly 'epub-media-type': 'The web edition has a file that isn’t one of EPUB’s core media types (an AVIF image, say), which an EPUB can hold only with a fallback. It is left out of the EPUB.';
|
|
9
|
+
readonly 'epub-page-list': 'The build can’t lay out the print edition `page-list` names (a host on a pulpweaver4 before 0.0.93), so the EPUB has no page list.';
|
|
10
|
+
};
|
|
11
|
+
export type ProblemCode = keyof typeof PROBLEMS;
|
package/dist/problems.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The problems the `epub` output reports, by code, each with what it means
|
|
3
|
+
* for the reference (`scripts/reference.mjs`), which fails on a code the
|
|
4
|
+
* output reports that isn't here.
|
|
5
|
+
*/
|
|
6
|
+
export const PROBLEMS = {
|
|
7
|
+
'epub-date': 'The build has no date. An EPUB must say when it was modified (`dcterms:modified`), and pulpweaver4 never takes a date from the clock, so the edition isn’t written: set `date` in `pulpweaver4.toml`, or `SOURCE_DATE_EPOCH`.',
|
|
8
|
+
'epub-media-type': 'The web edition has a file that isn’t one of EPUB’s core media types (an AVIF image, say), which an EPUB can hold only with a fallback. It is left out of the EPUB.',
|
|
9
|
+
'epub-page-list': 'The build can’t lay out the print edition `page-list` names (a host on a pulpweaver4 before 0.0.93), so the EPUB has no page list.',
|
|
10
|
+
};
|
package/dist/xhtml.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The EPUB's content documents: the web edition's pages made EPUB 3's
|
|
3
|
+
* XHTML. The web shows a note as a pop-over its call opens with no script;
|
|
4
|
+
* an EPUB's reading systems show an `aside` marked as a footnote, which its
|
|
5
|
+
* call links to as a `noteref` and which links back, so that is what each
|
|
6
|
+
* becomes. Links to the site's other pages point at their XHTML documents,
|
|
7
|
+
* and each image at its file as the web output wrote it.
|
|
8
|
+
*/
|
|
9
|
+
export declare const XHTML = "http://www.w3.org/1999/xhtml";
|
|
10
|
+
export declare const OPS = "http://www.idpf.org/2007/ops";
|
|
11
|
+
/** Sets an element's `epub:type`. */
|
|
12
|
+
export declare function setEpubType(el: Element, type: string): void;
|
|
13
|
+
/**
|
|
14
|
+
* Makes the web edition's notes EPUB footnotes, in place: each note an
|
|
15
|
+
* `aside` (`epub:type="footnote"`) whose marker links back to its call, and
|
|
16
|
+
* each call a link to it (`epub:type="noteref"`).
|
|
17
|
+
*/
|
|
18
|
+
export declare function epubNotes(root: Element): void;
|
|
19
|
+
/**
|
|
20
|
+
* Points each link to one of the site's pages (`03-freely.html#x`) at its
|
|
21
|
+
* XHTML document, and the contents page the site had (`index.html`) at
|
|
22
|
+
* `contents`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function relink(root: Element, documents: ReadonlyMap<string, string>, contents: string): void;
|
|
25
|
+
/** What a content document holds that its manifest item must say: MathML, SVG. */
|
|
26
|
+
export declare function documentProperties(root: Element): string[];
|
|
27
|
+
/** An XHTML document of the EPUB: its title, language, stylesheets and body's content, serialized. */
|
|
28
|
+
export declare function xhtmlDocument(options: {
|
|
29
|
+
title: string;
|
|
30
|
+
language: string;
|
|
31
|
+
stylesheets?: readonly string[];
|
|
32
|
+
body: readonly Node[];
|
|
33
|
+
bodyType?: string;
|
|
34
|
+
}): string;
|
package/dist/xhtml.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The EPUB's content documents: the web edition's pages made EPUB 3's
|
|
3
|
+
* XHTML. The web shows a note as a pop-over its call opens with no script;
|
|
4
|
+
* an EPUB's reading systems show an `aside` marked as a footnote, which its
|
|
5
|
+
* call links to as a `noteref` and which links back, so that is what each
|
|
6
|
+
* becomes. Links to the site's other pages point at their XHTML documents,
|
|
7
|
+
* and each image at its file as the web output wrote it.
|
|
8
|
+
*/
|
|
9
|
+
export const XHTML = 'http://www.w3.org/1999/xhtml';
|
|
10
|
+
export const OPS = 'http://www.idpf.org/2007/ops';
|
|
11
|
+
const XMLNS = 'http://www.w3.org/2000/xmlns/';
|
|
12
|
+
const MATHML = 'http://www.w3.org/1998/Math/MathML';
|
|
13
|
+
const SVG = 'http://www.w3.org/2000/svg';
|
|
14
|
+
/** Sets an element's `epub:type`. */
|
|
15
|
+
export function setEpubType(el, type) {
|
|
16
|
+
el.setAttributeNS(OPS, 'epub:type', type);
|
|
17
|
+
}
|
|
18
|
+
/** Remakes `el` as an element named `name`, in its place, with its attributes and children. */
|
|
19
|
+
function rename(el, name) {
|
|
20
|
+
const out = el.ownerDocument.createElementNS(XHTML, name);
|
|
21
|
+
for (const a of el.attributes)
|
|
22
|
+
out.setAttributeNS(a.namespaceURI, a.name, a.value);
|
|
23
|
+
out.append(...el.childNodes);
|
|
24
|
+
el.replaceWith(out);
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Makes the web edition's notes EPUB footnotes, in place: each note an
|
|
29
|
+
* `aside` (`epub:type="footnote"`) whose marker links back to its call, and
|
|
30
|
+
* each call a link to it (`epub:type="noteref"`).
|
|
31
|
+
*/
|
|
32
|
+
export function epubNotes(root) {
|
|
33
|
+
const calls = new Map();
|
|
34
|
+
for (const button of [...root.querySelectorAll('button[popovertarget]')]) {
|
|
35
|
+
const target = button.getAttribute('popovertarget');
|
|
36
|
+
const a = rename(button, 'a');
|
|
37
|
+
for (const name of ['type', 'popovertarget', 'popovertargetaction'])
|
|
38
|
+
a.removeAttribute(name);
|
|
39
|
+
a.setAttribute('href', `#${target}`);
|
|
40
|
+
if (!a.id)
|
|
41
|
+
a.id = `${target}-call`;
|
|
42
|
+
a.setAttribute('role', 'doc-noteref');
|
|
43
|
+
setEpubType(a, 'noteref');
|
|
44
|
+
calls.set(target, a);
|
|
45
|
+
}
|
|
46
|
+
for (const popover of [...root.querySelectorAll('[popover]')]) {
|
|
47
|
+
popover.removeAttribute('popover');
|
|
48
|
+
if (popover.getAttribute('role') !== 'doc-footnote')
|
|
49
|
+
continue;
|
|
50
|
+
const aside = rename(popover, 'aside');
|
|
51
|
+
setEpubType(aside, 'footnote');
|
|
52
|
+
const call = calls.get(aside.id);
|
|
53
|
+
const marker = aside.querySelector('.pw-footnote-marker');
|
|
54
|
+
if (call && marker) {
|
|
55
|
+
const back = aside.ownerDocument.createElementNS(XHTML, 'a');
|
|
56
|
+
back.setAttribute('href', `#${call.id}`);
|
|
57
|
+
back.setAttribute('role', 'doc-backlink');
|
|
58
|
+
marker.replaceWith(back);
|
|
59
|
+
back.append(marker);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Points each link to one of the site's pages (`03-freely.html#x`) at its
|
|
65
|
+
* XHTML document, and the contents page the site had (`index.html`) at
|
|
66
|
+
* `contents`.
|
|
67
|
+
*/
|
|
68
|
+
export function relink(root, documents, contents) {
|
|
69
|
+
for (const a of root.querySelectorAll('a[href]')) {
|
|
70
|
+
const href = a.getAttribute('href');
|
|
71
|
+
const m = /^([^:/?#]+\.html)(#.*)?$/.exec(href);
|
|
72
|
+
if (!m)
|
|
73
|
+
continue;
|
|
74
|
+
const to = m[1] === 'index.html' && !documents.has('index.html') ? contents : documents.get(m[1]);
|
|
75
|
+
if (to !== undefined)
|
|
76
|
+
a.setAttribute('href', `${to}${m[2] ?? ''}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** What a content document holds that its manifest item must say: MathML, SVG. */
|
|
80
|
+
export function documentProperties(root) {
|
|
81
|
+
const properties = [];
|
|
82
|
+
if (root.getElementsByTagNameNS(MATHML, 'math').length)
|
|
83
|
+
properties.push('mathml');
|
|
84
|
+
if (root.getElementsByTagNameNS(SVG, 'svg').length)
|
|
85
|
+
properties.push('svg');
|
|
86
|
+
return properties;
|
|
87
|
+
}
|
|
88
|
+
/** An XHTML document of the EPUB: its title, language, stylesheets and body's content, serialized. */
|
|
89
|
+
export function xhtmlDocument(options) {
|
|
90
|
+
const doc = document.implementation.createDocument(XHTML, 'html', document.implementation.createDocumentType('html', '', ''));
|
|
91
|
+
const html = doc.documentElement;
|
|
92
|
+
html.setAttributeNS(XMLNS, 'xmlns:epub', OPS);
|
|
93
|
+
html.setAttribute('lang', options.language);
|
|
94
|
+
html.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:lang', options.language);
|
|
95
|
+
const head = doc.createElementNS(XHTML, 'head');
|
|
96
|
+
const meta = doc.createElementNS(XHTML, 'meta');
|
|
97
|
+
meta.setAttribute('charset', 'utf-8');
|
|
98
|
+
const title = doc.createElementNS(XHTML, 'title');
|
|
99
|
+
title.textContent = options.title;
|
|
100
|
+
head.append(meta, title);
|
|
101
|
+
for (const href of options.stylesheets ?? []) {
|
|
102
|
+
const link = doc.createElementNS(XHTML, 'link');
|
|
103
|
+
link.setAttribute('rel', 'stylesheet');
|
|
104
|
+
link.setAttribute('href', href);
|
|
105
|
+
head.append(link);
|
|
106
|
+
}
|
|
107
|
+
const body = doc.createElementNS(XHTML, 'body');
|
|
108
|
+
if (options.bodyType)
|
|
109
|
+
setEpubType(body, options.bodyType);
|
|
110
|
+
for (const node of options.body)
|
|
111
|
+
body.append(doc.importNode(node, true));
|
|
112
|
+
html.append(head, body);
|
|
113
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n${new XMLSerializer().serializeToString(doc)}\n`;
|
|
114
|
+
}
|