@open-document/core 0.7.0 → 0.9.0
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/dist/{check-pEQh4jJE.js → check-CL0-0eB8.js} +1 -1
- package/dist/cli/bin.js +5 -9
- package/dist/{export-BQ-GvMsb.js → export-CmVJdl9a.js} +3 -6
- package/dist/{import-Daat3L2J.js → import-E6vRo7xm.js} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -1
- package/dist/ops/index.d.ts +2 -3
- package/dist/ops/index.js +3 -3
- package/dist/{ops-DQfckiyp.js → ops-OZZVBgsM.js} +4 -3
- package/dist/{sdk-C9nl30dW.d.ts → sdk-BqU6mwD_.d.ts} +8 -1
- package/dist/{sdk-DhcqZdAw.js → sdk-CqNZzbkz.js} +12 -1
- package/package.json +1 -1
- package/skills/doc-authoring/SKILL.md +2 -1
- package/src/app/components/footnote.tsx +6 -1
- package/src/app/components/inspector/inspector.tsx +7 -3
- package/src/app/components/numbering.tsx +1 -0
- package/src/app/lib/agent-bridge.ts +13 -0
- package/src/app/lib/docx/from-dom.ts +889 -0
- package/src/app/lib/docx/ooxml.test.ts +299 -0
- package/src/app/lib/docx/ooxml.ts +755 -0
- package/src/app/lib/export-docx.ts +225 -0
- package/src/app/lib/export-dom.ts +19 -3
- package/src/app/lib/export-image.ts +45 -2
- package/src/app/lib/sdk.ts +8 -0
- package/src/app/lib/view-mode.test.ts +46 -0
- package/src/app/lib/view-mode.ts +76 -0
- package/src/app/routes/doc.tsx +111 -12
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The document as a .docx — structure Word flows itself, for review that runs
|
|
3
|
+
* on Word: track changes, comments, pasting a section into someone else's
|
|
4
|
+
* template. Page-for-page fidelity is not the aim; Word repaginates the moment
|
|
5
|
+
* anyone types, so what has to survive is the structure.
|
|
6
|
+
*
|
|
7
|
+
* The browser downloads it; the headless exporter writes it to disk through
|
|
8
|
+
* the bridge. Both call `buildDocDocx`, so there is one way to make one.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createElement } from 'react';
|
|
12
|
+
import { createRoot } from 'react-dom/client';
|
|
13
|
+
import { type DesignSystem, defaultDesign, designToCssVars } from './design';
|
|
14
|
+
import { docxFromPages, lineOf, type PageInfo, type StyleBaseline } from './docx/from-dom';
|
|
15
|
+
import {
|
|
16
|
+
buildDocxParts,
|
|
17
|
+
type DocxModel,
|
|
18
|
+
fontsFor,
|
|
19
|
+
hexColor,
|
|
20
|
+
type Inline,
|
|
21
|
+
type Paragraph,
|
|
22
|
+
PX_TO_HALF_POINTS,
|
|
23
|
+
PX_TO_TWIPS,
|
|
24
|
+
type StyleId,
|
|
25
|
+
} from './docx/ooxml';
|
|
26
|
+
import { downloadBlob, withRenderedPages } from './export-dom';
|
|
27
|
+
import { type DocEntry, type FlowSection, isFlowSection } from './flow';
|
|
28
|
+
import { DocPageProvider } from './page-context';
|
|
29
|
+
import { nextFrame, waitForFonts } from './print-ready';
|
|
30
|
+
import { type DocModule, resolvePageGeometry } from './sdk';
|
|
31
|
+
import type { ExpandedPage } from './use-doc-pages';
|
|
32
|
+
|
|
33
|
+
export type DocxBundle = { filename: string; mimeType: string; bytes: Uint8Array };
|
|
34
|
+
|
|
35
|
+
export const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
|
36
|
+
|
|
37
|
+
// Page numbers no document prints, so the footer can be drawn once and every
|
|
38
|
+
// place a number landed found again and handed to Word as a field.
|
|
39
|
+
const PAGE_SENTINEL = 97_531;
|
|
40
|
+
const TOTAL_SENTINEL = 86_420;
|
|
41
|
+
|
|
42
|
+
/** A flow page after the first of its section continues it; everything else starts a sheet. */
|
|
43
|
+
function pageInfo(pages: ExpandedPage[]): PageInfo[] {
|
|
44
|
+
return pages.map((page, at) => {
|
|
45
|
+
const flow = /^f(\d+)-(\d+)$/.exec(page.key);
|
|
46
|
+
const previous = /^f(\d+)-/.exec(pages[at - 1]?.key ?? '');
|
|
47
|
+
return { continues: Boolean(flow && previous && previous[1] === flow[1]) };
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function firstFamily(stack: string): string {
|
|
52
|
+
return (stack.split(',')[0] ?? '')
|
|
53
|
+
.trim()
|
|
54
|
+
.replace(/^['"]|['"]$/g, '')
|
|
55
|
+
.toLowerCase();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function baselines(design: DesignSystem): Record<StyleId, StyleBaseline> {
|
|
59
|
+
const text = hexColor(design.palette.text) ?? '000000';
|
|
60
|
+
const muted = hexColor(design.palette.muted) ?? text;
|
|
61
|
+
const size = (px: number) => Math.round(px * PX_TO_HALF_POINTS);
|
|
62
|
+
const plain = { color: text, bold: false, italic: false };
|
|
63
|
+
const heading = (px: number) => ({
|
|
64
|
+
halfPoints: size(px),
|
|
65
|
+
color: text,
|
|
66
|
+
bold: true,
|
|
67
|
+
italic: false,
|
|
68
|
+
});
|
|
69
|
+
const { typeScale } = design;
|
|
70
|
+
return {
|
|
71
|
+
Normal: { ...plain, halfPoints: size(typeScale.body) },
|
|
72
|
+
ListParagraph: { ...plain, halfPoints: size(typeScale.body) },
|
|
73
|
+
Title: heading(typeScale.title),
|
|
74
|
+
Heading1: heading(typeScale.h1),
|
|
75
|
+
Heading2: heading(typeScale.h2),
|
|
76
|
+
Heading3: heading(typeScale.h3),
|
|
77
|
+
Heading4: heading(Math.max(typeScale.body, (typeScale.h3 + typeScale.body) / 2)),
|
|
78
|
+
Heading5: heading(typeScale.body),
|
|
79
|
+
Heading6: { ...heading(typeScale.body), color: muted },
|
|
80
|
+
Caption: { ...plain, color: muted, halfPoints: size(typeScale.caption) },
|
|
81
|
+
Code: { ...plain, halfPoints: Math.max(12, size(typeScale.body) - 2) },
|
|
82
|
+
Quote: { ...plain, color: muted, italic: true, halfPoints: size(typeScale.body) },
|
|
83
|
+
FootnoteText: { ...plain, color: muted, halfPoints: size(typeScale.caption) },
|
|
84
|
+
TOCHeading: heading(typeScale.h1),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The first flow section's footer, as a Word footer. It is drawn once with
|
|
90
|
+
* sentinel page numbers, and wherever a sentinel landed the text becomes a
|
|
91
|
+
* PAGE or NUMPAGES field — so Word numbers the pages it lays out, not the ones
|
|
92
|
+
* open-doc did.
|
|
93
|
+
*/
|
|
94
|
+
async function footerOf(
|
|
95
|
+
doc: DocModule,
|
|
96
|
+
design: DesignSystem,
|
|
97
|
+
width: number,
|
|
98
|
+
walk: Parameters<typeof lineOf>[1],
|
|
99
|
+
): Promise<Paragraph | undefined> {
|
|
100
|
+
const section = ((doc.default ?? []) as DocEntry[]).find(
|
|
101
|
+
(entry): entry is FlowSection => isFlowSection(entry) && Boolean(entry.footer),
|
|
102
|
+
);
|
|
103
|
+
const Footer = section?.footer;
|
|
104
|
+
if (!Footer) return undefined;
|
|
105
|
+
|
|
106
|
+
const host = document.createElement('div');
|
|
107
|
+
host.setAttribute('aria-hidden', 'true');
|
|
108
|
+
Object.assign(host.style, { position: 'fixed', left: '-99999px', top: '0', width: `${width}px` });
|
|
109
|
+
for (const [name, value] of Object.entries(designToCssVars(design))) {
|
|
110
|
+
host.style.setProperty(name, value);
|
|
111
|
+
}
|
|
112
|
+
host.style.fontFamily = 'var(--od-font-body)';
|
|
113
|
+
host.style.color = 'var(--od-text)';
|
|
114
|
+
document.body.appendChild(host);
|
|
115
|
+
const root = createRoot(host);
|
|
116
|
+
try {
|
|
117
|
+
root.render(
|
|
118
|
+
createElement(
|
|
119
|
+
DocPageProvider,
|
|
120
|
+
{ index: PAGE_SENTINEL - 1, total: TOTAL_SENTINEL },
|
|
121
|
+
createElement(Footer),
|
|
122
|
+
),
|
|
123
|
+
);
|
|
124
|
+
await nextFrame();
|
|
125
|
+
await waitForFonts();
|
|
126
|
+
await nextFrame();
|
|
127
|
+
const target = host.firstElementChild;
|
|
128
|
+
const line = target ? await lineOf(target, walk) : null;
|
|
129
|
+
if (!line) return undefined;
|
|
130
|
+
const fields = (inlines: Inline[]): Inline[] =>
|
|
131
|
+
inlines.flatMap((inline): Inline[] => {
|
|
132
|
+
if (inline.type !== 'text') return [inline];
|
|
133
|
+
return inline.text
|
|
134
|
+
.split(new RegExp(`(${PAGE_SENTINEL}|${TOTAL_SENTINEL})`))
|
|
135
|
+
.filter((piece) => piece !== '')
|
|
136
|
+
.map(
|
|
137
|
+
(piece): Inline =>
|
|
138
|
+
piece === String(PAGE_SENTINEL)
|
|
139
|
+
? { type: 'field', instr: 'PAGE', cached: '1' }
|
|
140
|
+
: piece === String(TOTAL_SENTINEL)
|
|
141
|
+
? { type: 'field', instr: 'NUMPAGES', cached: '1' }
|
|
142
|
+
: { ...inline, text: piece },
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
return { ...line, inlines: fields(line.inlines) };
|
|
146
|
+
} finally {
|
|
147
|
+
root.unmount();
|
|
148
|
+
host.remove();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function buildDocDocx(
|
|
153
|
+
doc: DocModule,
|
|
154
|
+
docId: string,
|
|
155
|
+
pages: ExpandedPage[],
|
|
156
|
+
): Promise<DocxBundle | null> {
|
|
157
|
+
if (pages.length === 0) return null;
|
|
158
|
+
const geometry = resolvePageGeometry(doc.meta);
|
|
159
|
+
const design = (doc.design as DesignSystem | undefined) ?? defaultDesign;
|
|
160
|
+
const textWidth = geometry.width - design.margin * 2;
|
|
161
|
+
const walk = {
|
|
162
|
+
doc,
|
|
163
|
+
textWidth,
|
|
164
|
+
baselines: baselines(design),
|
|
165
|
+
monoFamilies: [firstFamily(design.fonts.mono)].filter((family) => family !== ''),
|
|
166
|
+
margin: design.margin,
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const content = await withRenderedPages(pages, geometry, doc, (hosts, container) =>
|
|
170
|
+
docxFromPages(hosts, pageInfo(pages), container, walk),
|
|
171
|
+
);
|
|
172
|
+
const footer = await footerOf(doc, design, textWidth, walk);
|
|
173
|
+
|
|
174
|
+
const size = (px: number) => Math.round(px * PX_TO_HALF_POINTS);
|
|
175
|
+
const text = hexColor(design.palette.text) ?? '000000';
|
|
176
|
+
const model: DocxModel = {
|
|
177
|
+
title: doc.meta?.title ?? docId,
|
|
178
|
+
...(doc.meta?.author ? { author: doc.meta.author } : {}),
|
|
179
|
+
page: {
|
|
180
|
+
width: geometry.width * PX_TO_TWIPS,
|
|
181
|
+
height: geometry.height * PX_TO_TWIPS,
|
|
182
|
+
landscape: geometry.width > geometry.height,
|
|
183
|
+
margin: design.margin * PX_TO_TWIPS,
|
|
184
|
+
},
|
|
185
|
+
fonts: {
|
|
186
|
+
body: fontsFor(design.fonts.body, 'sans'),
|
|
187
|
+
heading: fontsFor(design.fonts.heading, 'sans'),
|
|
188
|
+
mono: fontsFor(design.fonts.mono, 'mono'),
|
|
189
|
+
},
|
|
190
|
+
sizes: {
|
|
191
|
+
title: size(design.typeScale.title),
|
|
192
|
+
h1: size(design.typeScale.h1),
|
|
193
|
+
h2: size(design.typeScale.h2),
|
|
194
|
+
h3: size(design.typeScale.h3),
|
|
195
|
+
body: size(design.typeScale.body),
|
|
196
|
+
caption: size(design.typeScale.caption),
|
|
197
|
+
},
|
|
198
|
+
colors: {
|
|
199
|
+
text,
|
|
200
|
+
muted: hexColor(design.palette.muted) ?? text,
|
|
201
|
+
accent: hexColor(design.palette.accent) ?? text,
|
|
202
|
+
},
|
|
203
|
+
line: design.leading * design.typeScale.body * PX_TO_TWIPS,
|
|
204
|
+
...content,
|
|
205
|
+
...(footer ? { footer } : {}),
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const parts = buildDocxParts(model);
|
|
209
|
+
const { zipSync, strToU8 } = await import('fflate');
|
|
210
|
+
const tree: Record<string, Uint8Array> = {};
|
|
211
|
+
for (const [name, part] of Object.entries(parts)) {
|
|
212
|
+
tree[name] = typeof part === 'string' ? strToU8(part) : part;
|
|
213
|
+
}
|
|
214
|
+
return { filename: `${docId}.docx`, mimeType: DOCX_MIME, bytes: zipSync(tree) };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export async function exportDocAsDocx(
|
|
218
|
+
doc: DocModule,
|
|
219
|
+
docId: string,
|
|
220
|
+
pages: ExpandedPage[],
|
|
221
|
+
): Promise<void> {
|
|
222
|
+
const bundle = await buildDocDocx(doc, docId, pages);
|
|
223
|
+
if (!bundle) return;
|
|
224
|
+
downloadBlob(new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }), bundle.filename);
|
|
225
|
+
}
|
|
@@ -17,11 +17,18 @@ import type { ExpandedPage } from './use-doc-pages';
|
|
|
17
17
|
export const ASSET_EXT_RE =
|
|
18
18
|
/\.(?:png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf)(?:\?[^#]*)?(?:#.*)?$/i;
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Draws the pages offscreen at true sheet size, waits until they are settled —
|
|
22
|
+
* fonts, images, the numbering scan — hands the page hosts to `visit` while
|
|
23
|
+
* they are still live, and tears everything down after. Exporters that need
|
|
24
|
+
* computed styles (DOCX reads them) visit the live tree; the others serialise.
|
|
25
|
+
*/
|
|
26
|
+
export async function withRenderedPages<T>(
|
|
21
27
|
pages: ExpandedPage[],
|
|
22
28
|
geometry: PageGeometry,
|
|
23
29
|
doc: DocModule,
|
|
24
|
-
|
|
30
|
+
visit: (hosts: HTMLElement[], container: HTMLElement) => Promise<T> | T,
|
|
31
|
+
): Promise<T> {
|
|
25
32
|
const container = document.createElement('div');
|
|
26
33
|
container.setAttribute('aria-hidden', 'true');
|
|
27
34
|
Object.assign(container.style, {
|
|
@@ -63,13 +70,22 @@ export async function renderPagesToHtml(
|
|
|
63
70
|
await nextFrame();
|
|
64
71
|
await nextFrame();
|
|
65
72
|
|
|
66
|
-
return hosts
|
|
73
|
+
return await visit(hosts, container);
|
|
67
74
|
} finally {
|
|
68
75
|
for (const root of roots) root.unmount();
|
|
69
76
|
container.remove();
|
|
70
77
|
restoreScan(previousScan);
|
|
71
78
|
}
|
|
72
79
|
}
|
|
80
|
+
|
|
81
|
+
export async function renderPagesToHtml(
|
|
82
|
+
pages: ExpandedPage[],
|
|
83
|
+
geometry: PageGeometry,
|
|
84
|
+
doc: DocModule,
|
|
85
|
+
): Promise<string[]> {
|
|
86
|
+
return withRenderedPages(pages, geometry, doc, (hosts) => hosts.map((host) => host.innerHTML));
|
|
87
|
+
}
|
|
88
|
+
|
|
73
89
|
export function collectCss(): string {
|
|
74
90
|
const chunks: string[] = [];
|
|
75
91
|
for (const sheet of Array.from(document.styleSheets)) {
|
|
@@ -146,7 +146,9 @@ function blobToDataUrl(blob: Blob): Promise<string> {
|
|
|
146
146
|
* The design variables live on the page host, and renderPagesToHtml returns the
|
|
147
147
|
* host's innerHTML, so they are not in the markup and have to be put back.
|
|
148
148
|
*/
|
|
149
|
-
|
|
149
|
+
type Box = Pick<PageGeometry, 'width' | 'height'>;
|
|
150
|
+
|
|
151
|
+
function buildSvg(pageHtml: string, css: string, geometry: Box, doc: DocModule): string {
|
|
150
152
|
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
151
153
|
const XHTML_NS = 'http://www.w3.org/1999/xhtml';
|
|
152
154
|
|
|
@@ -177,7 +179,11 @@ function buildSvg(pageHtml: string, css: string, geometry: PageGeometry, doc: Do
|
|
|
177
179
|
style.appendChild(document.createTextNode(css));
|
|
178
180
|
wrapper.appendChild(style);
|
|
179
181
|
|
|
182
|
+
// A page sized by `height: 100%` measures against this box; without a height
|
|
183
|
+
// of its own the page collapses to its content, and whatever it placed
|
|
184
|
+
// against its foot — a footer, a centred closing, a cover's title — moves up.
|
|
180
185
|
const content = document.createElementNS(XHTML_NS, 'div');
|
|
186
|
+
content.setAttribute('style', 'width:100%;height:100%');
|
|
181
187
|
content.innerHTML = pageHtml;
|
|
182
188
|
wrapper.appendChild(content);
|
|
183
189
|
|
|
@@ -195,7 +201,7 @@ function buildSvg(pageHtml: string, css: string, geometry: PageGeometry, doc: Do
|
|
|
195
201
|
* Verified against Chrome 151 — a plain SVG is clean either way, so the taint
|
|
196
202
|
* follows the foreignObject and the URL scheme together, not either alone.
|
|
197
203
|
*/
|
|
198
|
-
async function rasterise(svg: string, geometry:
|
|
204
|
+
async function rasterise(svg: string, geometry: Box): Promise<Blob> {
|
|
199
205
|
const source = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
200
206
|
|
|
201
207
|
const image = new Image();
|
|
@@ -224,3 +230,40 @@ async function rasterise(svg: string, geometry: PageGeometry): Promise<Blob> {
|
|
|
224
230
|
);
|
|
225
231
|
});
|
|
226
232
|
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* One element as a PNG, through the same `foreignObject` path as a page — for
|
|
236
|
+
* what a DOCX cannot hold as structure: a chart built from boxes, a compiled
|
|
237
|
+
* diagram whose colours are the document's CSS variables. Pulled out of its
|
|
238
|
+
* page, the element would lose the type it inherits, so that goes round it.
|
|
239
|
+
*/
|
|
240
|
+
export async function elementToPng(
|
|
241
|
+
el: Element,
|
|
242
|
+
doc: DocModule,
|
|
243
|
+
): Promise<{ bytes: Uint8Array; width: number; height: number }> {
|
|
244
|
+
const rect = el.getBoundingClientRect();
|
|
245
|
+
const width = Math.max(1, Math.ceil(rect.width));
|
|
246
|
+
const height = Math.max(1, Math.ceil(rect.height));
|
|
247
|
+
const inherited = getComputedStyle(el);
|
|
248
|
+
// Drawn on its own canvas, the element must start at the canvas's corner.
|
|
249
|
+
// Whatever placed it on the page — absolute offsets, a transform, margins —
|
|
250
|
+
// would otherwise put it off the edge, and the picture comes out blank.
|
|
251
|
+
const clone = el.cloneNode(true) as HTMLElement | SVGElement;
|
|
252
|
+
for (const [name, value] of [
|
|
253
|
+
['position', 'static'],
|
|
254
|
+
['inset', 'auto'],
|
|
255
|
+
['margin', '0'],
|
|
256
|
+
['transform', 'none'],
|
|
257
|
+
['width', `${width}px`],
|
|
258
|
+
['height', `${height}px`],
|
|
259
|
+
]) {
|
|
260
|
+
clone.style.setProperty(name as string, value as string);
|
|
261
|
+
}
|
|
262
|
+
const wrapped =
|
|
263
|
+
`<div style="font-family:${inherited.fontFamily.replace(/"/g, "'")};color:${inherited.color};` +
|
|
264
|
+
`font-size:${inherited.fontSize};line-height:${inherited.lineHeight};width:${width}px">${clone.outerHTML}</div>`;
|
|
265
|
+
const { css, html } = await embedAssets([wrapped], doc);
|
|
266
|
+
const svg = buildSvg(html[0] ?? '', css, { width, height }, doc);
|
|
267
|
+
const blob = await rasterise(svg, { width, height });
|
|
268
|
+
return { bytes: new Uint8Array(await blob.arrayBuffer()), width, height };
|
|
269
|
+
}
|
package/src/app/lib/sdk.ts
CHANGED
|
@@ -64,6 +64,14 @@ export type FlowSection = {
|
|
|
64
64
|
/** What a document's default export may contain: fixed pages, flow sections, or both. */
|
|
65
65
|
export type DocEntry = DocPage | FlowSection;
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* Every format `open-doc export` can write. The CLI's `--format`, the MCP
|
|
69
|
+
* `export_document` schema and `ops/layout.ts` all read this tuple, so adding a
|
|
70
|
+
* format is one edit here and its branch in `exportDocument`.
|
|
71
|
+
*/
|
|
72
|
+
export const EXPORT_FORMATS = ['pdf', 'html', 'png', 'docx'] as const;
|
|
73
|
+
export type ExportFormat = (typeof EXPORT_FORMATS)[number];
|
|
74
|
+
|
|
67
75
|
export type DocMeta = {
|
|
68
76
|
title?: string;
|
|
69
77
|
subtitle?: string;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { fitWidthScale, pageAtMarker, sheetsAcross } from './view-mode.ts';
|
|
3
|
+
|
|
4
|
+
describe('fitWidthScale', () => {
|
|
5
|
+
it('fits one sheet, a spread, or a row of three into the width', () => {
|
|
6
|
+
expect(sheetsAcross('continuous')).toBe(1);
|
|
7
|
+
for (const mode of ['continuous', 'spread', 'grid'] as const) {
|
|
8
|
+
const scale = fitWidthScale(mode, 960, 794, 24);
|
|
9
|
+
const across = sheetsAcross(mode);
|
|
10
|
+
// The row the viewer lays out — scaled sheets plus fixed gaps — fills it exactly.
|
|
11
|
+
expect(across * 794 * scale + (across - 1) * 24).toBeCloseTo(960);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('pageAtMarker', () => {
|
|
17
|
+
it('follows a single column', () => {
|
|
18
|
+
expect(pageAtMarker([0, 1100, 2200], 1500)).toBe(2);
|
|
19
|
+
expect(pageAtMarker([0, 1100, 2200], 10)).toBe(1);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('reports the left page of the spread in view', () => {
|
|
23
|
+
// Page 1 alone on the right, then 2–3, 4–5.
|
|
24
|
+
const tops = [0, 1100, 1100, 2200, 2200];
|
|
25
|
+
expect(pageAtMarker(tops, 1500)).toBe(2);
|
|
26
|
+
expect(pageAtMarker(tops, 2300)).toBe(4);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('reports the first sheet of the grid row in view', () => {
|
|
30
|
+
const tops = [0, 0, 0, 300, 300, 300, 600];
|
|
31
|
+
expect(pageAtMarker(tops, 450)).toBe(4);
|
|
32
|
+
expect(pageAtMarker(tops, 650)).toBe(7);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('keeps a page just jumped to while its row is in view', () => {
|
|
36
|
+
const tops = [0, 1100, 1100, 2200, 2200];
|
|
37
|
+
expect(pageAtMarker(tops, 1500, 3)).toBe(3);
|
|
38
|
+
// Scrolled on to the next spread: the jump no longer describes the view.
|
|
39
|
+
expect(pageAtMarker(tops, 2300, 3)).toBe(4);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('falls back to the first page before anything has passed the marker', () => {
|
|
43
|
+
expect(pageAtMarker([200, 1300], 100)).toBe(1);
|
|
44
|
+
expect(pageAtMarker([], 100)).toBe(1);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the viewer lays the sheets out. Every mode keeps all pages in the one
|
|
3
|
+
* scroll container, so the page counter, page jump, the outline, find and the
|
|
4
|
+
* inspector overlay work the same in each — there is no single-sheet mode,
|
|
5
|
+
* which would need its own navigation path through all of them.
|
|
6
|
+
*/
|
|
7
|
+
export const VIEW_MODES = ['continuous', 'spread', 'grid'] as const;
|
|
8
|
+
export type ViewMode = (typeof VIEW_MODES)[number];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* How many sheets side by side the zoom fits to. Fit width in two-up fits the
|
|
12
|
+
* spread, not one of its pages; in grid it fits a row of three, which is what
|
|
13
|
+
* keeps a chapter readable at a glance rather than a strip of postage stamps.
|
|
14
|
+
*/
|
|
15
|
+
export function sheetsAcross(mode: ViewMode): number {
|
|
16
|
+
return mode === 'continuous' ? 1 : mode === 'spread' ? 2 : 3;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The scale at which the mode's row of sheets exactly fills `width`. The gaps
|
|
21
|
+
* between sheets are fixed pixels, not scaled with the pages, so they come off
|
|
22
|
+
* the width before the sheets share what is left — counting them as page width
|
|
23
|
+
* would leave the row a little too wide, and a grid of three would wrap to two.
|
|
24
|
+
*/
|
|
25
|
+
export function fitWidthScale(
|
|
26
|
+
mode: ViewMode,
|
|
27
|
+
width: number,
|
|
28
|
+
pageWidth: number,
|
|
29
|
+
gap: number,
|
|
30
|
+
): number {
|
|
31
|
+
const across = sheetsAcross(mode);
|
|
32
|
+
return Math.max(0, width - (across - 1) * gap) / (across * pageWidth);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The page the reader is on: the first sheet of the lowest row whose top has
|
|
37
|
+
* passed the marker. In two-up that is the left page of the spread in view —
|
|
38
|
+
* the one a reader starts on — not the right one that shares its row.
|
|
39
|
+
*
|
|
40
|
+
* `prefer` is a page the reader just asked for. Jumping to page 3 in two-up
|
|
41
|
+
* brings the 2–3 spread into view, and reporting 2 would read as the jump
|
|
42
|
+
* having missed; while that page is in the row in view, it is the answer.
|
|
43
|
+
*/
|
|
44
|
+
export function pageAtMarker(tops: number[], marker: number, prefer?: number | null): number {
|
|
45
|
+
let rowTop = Number.NEGATIVE_INFINITY;
|
|
46
|
+
tops.forEach((top) => {
|
|
47
|
+
if (top <= marker && top > rowTop) rowTop = top;
|
|
48
|
+
});
|
|
49
|
+
const index = tops.indexOf(rowTop);
|
|
50
|
+
if (index < 0) return 1;
|
|
51
|
+
if (prefer && tops[prefer - 1] === rowTop) return prefer;
|
|
52
|
+
return index + 1;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const key = (docId: string) => `open-doc:view:${docId}`;
|
|
56
|
+
|
|
57
|
+
/** The mode last used for this document, so coming back resumes the same reading. */
|
|
58
|
+
export function readViewMode(docId: string | undefined): ViewMode {
|
|
59
|
+
if (!docId) return 'continuous';
|
|
60
|
+
try {
|
|
61
|
+
const stored = localStorage.getItem(key(docId));
|
|
62
|
+
return (VIEW_MODES as readonly string[]).includes(stored ?? '')
|
|
63
|
+
? (stored as ViewMode)
|
|
64
|
+
: 'continuous';
|
|
65
|
+
} catch {
|
|
66
|
+
return 'continuous';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function writeViewMode(docId: string | undefined, mode: ViewMode): void {
|
|
71
|
+
if (!docId) return;
|
|
72
|
+
try {
|
|
73
|
+
if (mode === 'continuous') localStorage.removeItem(key(docId));
|
|
74
|
+
else localStorage.setItem(key(docId), mode);
|
|
75
|
+
} catch {}
|
|
76
|
+
}
|