@folijs/view 0.2.0 → 0.4.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.
@@ -0,0 +1,372 @@
1
+ /**
2
+ * A schema v3 document on pages, as Word lays it out (8.6b, read-only): each section's page
3
+ * size and margins, the blocks of `blocks.ts` measured in the page's width and flowed with
4
+ * Word's spacing, keep rules, widow and orphan control and explicit breaks. Editing moves to
5
+ * v3 in 8.7.
6
+ */
7
+ import type { FoliDocument, SectionJSON } from "@folijs/core";
8
+ import { type BlockBox, flow } from "../layout/flow.js";
9
+ import {
10
+ type BlockOptions,
11
+ PX_PER_TWIP,
12
+ renderBlocks,
13
+ WORD_PAGE_BREAK_ATTR,
14
+ type WordBlock,
15
+ } from "./blocks.js";
16
+
17
+ export type { ReviewView } from "./blocks.js";
18
+
19
+ /** The class of each page element. */
20
+ export const WORD_PAGE_CLASS = "foli-word-page";
21
+
22
+ export interface DocumentPages {
23
+ /** The page elements, in order. */
24
+ readonly pages: readonly HTMLElement[];
25
+ /** The page (0-based) where the top-level node at `index` starts; undefined if not shown. */
26
+ pageOf(index: number): number | undefined;
27
+ /**
28
+ * The line on its page (1-based, counting every line of the blocks above it on the page)
29
+ * where the top-level node at `index` starts, as Word numbers lines; undefined if not shown.
30
+ */
31
+ lineOf(index: number): number | undefined;
32
+ /** Removes the pages. */
33
+ destroy(): void;
34
+ }
35
+
36
+ /** Word's defaults for what a section leaves out: Letter, 1 inch margins. */
37
+ const PAGE_DEFAULTS = { width: 12240, height: 15840, margin: 1440 };
38
+
39
+ interface Geometry {
40
+ width: number;
41
+ height: number;
42
+ top: number;
43
+ right: number;
44
+ bottom: number;
45
+ left: number;
46
+ }
47
+
48
+ function geometry(section: SectionJSON): Geometry {
49
+ const m = section.margins ?? {};
50
+ // A negative top or bottom margin is measured the same way in Word (text may overlap headers).
51
+ return {
52
+ width: (section.pageSize?.width ?? PAGE_DEFAULTS.width) * PX_PER_TWIP,
53
+ height: (section.pageSize?.height ?? PAGE_DEFAULTS.height) * PX_PER_TWIP,
54
+ top: Math.abs(m.top ?? PAGE_DEFAULTS.margin) * PX_PER_TWIP,
55
+ right: (m.right ?? PAGE_DEFAULTS.margin) * PX_PER_TWIP,
56
+ bottom: Math.abs(m.bottom ?? PAGE_DEFAULTS.margin) * PX_PER_TWIP,
57
+ left: ((m.left ?? PAGE_DEFAULTS.margin) + (m.gutter ?? 0)) * PX_PER_TWIP,
58
+ };
59
+ }
60
+
61
+ const sameGeometry = (a: Geometry, b: Geometry) =>
62
+ a.width === b.width &&
63
+ a.height === b.height &&
64
+ a.top === b.top &&
65
+ a.bottom === b.bottom &&
66
+ a.left === b.left &&
67
+ a.right === b.right;
68
+
69
+ /** An empty page: the page box with its margins as padding, and its content box. */
70
+ function createPage(doc: Document, g: Geometry): { page: HTMLElement; body: HTMLElement } {
71
+ const page = doc.createElement("div");
72
+ page.className = WORD_PAGE_CLASS;
73
+ const { style } = page;
74
+ style.boxSizing = "border-box";
75
+ style.position = "relative";
76
+ style.width = `${g.width}px`;
77
+ style.height = `${g.height}px`;
78
+ style.padding = `${g.top}px ${g.right}px ${g.bottom}px ${g.left}px`;
79
+ style.background = "#fff";
80
+ style.color = "#000";
81
+ style.overflow = "hidden";
82
+ const body = doc.createElement("div");
83
+ body.style.display = "flow-root";
84
+ page.append(body);
85
+ return { page, body };
86
+ }
87
+
88
+ /**
89
+ * The ratio of a font's normal line height to its size, measured: a line of 100 px text with
90
+ * `line-height: normal` (the font's own ascent, descent and gap, as Word's single spacing).
91
+ */
92
+ export function measureLineRatio(container: HTMLElement): (family: string) => number {
93
+ return (family) => {
94
+ const probe = container.ownerDocument.createElement("div");
95
+ const { style } = probe;
96
+ style.position = "absolute";
97
+ style.visibility = "hidden";
98
+ style.fontFamily = family;
99
+ style.fontSize = "100px";
100
+ style.lineHeight = "normal";
101
+ style.whiteSpace = "nowrap";
102
+ probe.textContent = "x";
103
+ container.append(probe);
104
+ const height = probe.getBoundingClientRect().height;
105
+ probe.remove();
106
+ return height > 0 ? height / 100 : 1.2;
107
+ };
108
+ }
109
+
110
+ /**
111
+ * The bottom of each line of a rendered block, from its top. Lines are the vertical clusters of
112
+ * its contents' client rects; a boundary is halfway between one line's content and the next's,
113
+ * the last line ends at the block's bottom.
114
+ *
115
+ * shortcut: line boxes are inferred from content rects (exact for even line heights); a
116
+ * superscript or a much larger run on a line moves that line's boundaries slightly.
117
+ */
118
+ export function lineBottoms(element: HTMLElement): number[] {
119
+ const box = element.getBoundingClientRect();
120
+ const doc = element.ownerDocument;
121
+ const range = doc.createRange();
122
+ const rects: { rect: DOMRect; text: boolean }[] = [];
123
+ // Text and line breaks only: a range over the whole block also has the boxes of the
124
+ // elements inside it (a table's), which span many lines.
125
+ const walker = doc.createTreeWalker(element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
126
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
127
+ if (node.nodeType === Node.TEXT_NODE) {
128
+ range.selectNodeContents(node);
129
+ for (const rect of range.getClientRects()) rects.push({ rect, text: true });
130
+ } else if (node.nodeName === "BR")
131
+ rects.push({ rect: (node as Element).getBoundingClientRect(), text: false });
132
+ }
133
+ rects.sort((a, b) => a.rect.top - b.rect.top);
134
+ type Line = { top: number; bottom: number; text: boolean };
135
+ const lines: Line[] = [];
136
+ for (const { rect, text } of rects) {
137
+ if (rect.height <= 0) continue;
138
+ const last = lines[lines.length - 1];
139
+ // Same line: it starts above the middle of the line so far.
140
+ if (last && rect.top < (last.top + last.bottom) / 2) {
141
+ // A line's text says where it is; a <br> only for a line without text (engines size
142
+ // its box differently).
143
+ if (text && !last.text) Object.assign(last, { top: rect.top, bottom: rect.bottom, text });
144
+ else if (text === last.text) {
145
+ last.top = Math.min(last.top, rect.top);
146
+ last.bottom = Math.max(last.bottom, rect.bottom);
147
+ }
148
+ } else lines.push({ top: rect.top, bottom: rect.bottom, text });
149
+ }
150
+ const bottoms = lines.slice(1).map((line, i) => {
151
+ const above = lines[i] as { bottom: number };
152
+ return (above.bottom + line.top) / 2 - box.top;
153
+ });
154
+ bottoms.push(box.height);
155
+ return bottoms;
156
+ }
157
+
158
+ /** The height of a table's leading header rows (repeated on each page it continues on), or 0. */
159
+ function headerHeight(element: HTMLElement): number {
160
+ let bottom = 0;
161
+ // The table's own rows: not those of a table nested in a cell.
162
+ for (const row of element.querySelectorAll(":scope > table > tbody > tr")) {
163
+ if (!(row as HTMLElement).dataset || !("foliHeader" in (row as HTMLElement).dataset)) break;
164
+ bottom = row.getBoundingClientRect().bottom;
165
+ }
166
+ return bottom ? bottom - element.getBoundingClientRect().top : 0;
167
+ }
168
+
169
+ /** The lines that end with an explicit page break, by the break's position. */
170
+ function breakLines(element: HTMLElement, bottoms: readonly number[]): number[] {
171
+ const top = element.getBoundingClientRect().top;
172
+ return [...element.querySelectorAll(`br[${WORD_PAGE_BREAK_ATTR}]`)].map((br) => {
173
+ const y = br.getBoundingClientRect().top - top;
174
+ const line = bottoms.findIndex((bottom) => y < bottom);
175
+ return line < 0 ? bottoms.length - 1 : line;
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Lays a v3 document out on pages inside `container`. Headers, footers, footnotes and floating
181
+ * content are not laid out yet (Phase 11); tables are shown from their verbatim XML until
182
+ * Phase 10.
183
+ */
184
+ export function renderDocument(
185
+ document: FoliDocument,
186
+ container: HTMLElement,
187
+ options: Omit<BlockOptions, "lineRatio"> = {},
188
+ ): DocumentPages {
189
+ const doc = container.ownerDocument;
190
+ const blocks = renderBlocks(document, doc, {
191
+ ...options,
192
+ lineRatio: measureLineRatio(container),
193
+ });
194
+ // Sections: consecutive blocks with one page setup. A section starts a new page unless it is
195
+ // continuous with the same geometry (shortcut: a continuous section with another geometry
196
+ // starts a new page).
197
+ const groups: { geometry: Geometry; blocks: WordBlock[] }[] = [];
198
+ let current: WordBlock[] = [];
199
+ const close = (section: SectionJSON) => {
200
+ const g = geometry(section);
201
+ const previous = groups[groups.length - 1];
202
+ if (section.type === "continuous" && previous && sameGeometry(previous.geometry, g))
203
+ previous.blocks.push(...current);
204
+ else groups.push({ geometry: g, blocks: current });
205
+ current = [];
206
+ };
207
+ for (const block of blocks) {
208
+ current.push(block);
209
+ if (block.section) close(block.section);
210
+ }
211
+ if (current.length || !groups.length) close(document.section);
212
+
213
+ const pages: HTMLElement[] = [];
214
+ const firstPage = new Map<number, number>();
215
+ /** Every fragment placed, in order: its page and how many lines it shows (measured lazily). */
216
+ const placements: { page: number; nodes: number[] | null; lines: () => number }[] = [];
217
+ for (const group of groups) {
218
+ const g = group.geometry;
219
+ // Measure in a page of the section's width, out of view.
220
+ const measuring = createPage(doc, g);
221
+ measuring.page.style.position = "absolute";
222
+ measuring.page.style.visibility = "hidden";
223
+ measuring.page.style.height = "auto";
224
+ container.append(measuring.page);
225
+ for (const block of group.blocks) measuring.body.append(block.element);
226
+ const lines = new Map<WordBlock, number[]>();
227
+ const linesOf = (block: WordBlock) => {
228
+ let value = lines.get(block);
229
+ if (!value) {
230
+ value = lineBottoms(block.element);
231
+ lines.set(block, value);
232
+ }
233
+ return value;
234
+ };
235
+ const headers = new Map<WordBlock, number>();
236
+ const pageHeight = g.height - g.top - g.bottom;
237
+ const boxes: BlockBox[] = group.blocks.map((block, i) => {
238
+ const height = block.element.getBoundingClientRect().height;
239
+ const repeat = block.element.querySelector("tr") ? headerHeight(block.element) : 0;
240
+ if (repeat) headers.set(block, repeat);
241
+ const next = group.blocks[i + 1];
242
+ const hasBreak = !!block.element.querySelector(`br[${WORD_PAGE_BREAK_ATTR}]`);
243
+ // A paragraph kept together is one line to the flow, unless it cannot be: taller than a
244
+ // page, or broken by a page break.
245
+ const kept = block.keepLines && !hasBreak && height <= pageHeight;
246
+ return {
247
+ height,
248
+ marginTop: block.before,
249
+ marginBottom: block.after,
250
+ repeat,
251
+ keepWithNext: block.keepNext,
252
+ lines: () => (kept ? [height] : linesOf(block)),
253
+ breaksAfter: () => {
254
+ const breaks = hasBreak ? breakLines(block.element, linesOf(block)) : [];
255
+ // The next block starts a page: this one's last line ends it.
256
+ if (next?.pageBreakBefore) breaks.push((kept ? 1 : linesOf(block).length) - 1);
257
+ return breaks;
258
+ },
259
+ };
260
+ });
261
+ // shortcut: widow and orphan control is on for every paragraph (Word's Normal has it; a
262
+ // paragraph turning it off is still kept to two lines).
263
+ const fragments = flow(boxes, pageHeight, { orphans: 2, widows: 2, spacing: "word" });
264
+ // What placing needs of the layout, read while the blocks are still laid out: the lines of
265
+ // split blocks, and which blocks end with an explicit page break.
266
+ const endsWithBreak = new Set<WordBlock>();
267
+ group.blocks.forEach((block, b) => {
268
+ if ((fragments[b]?.length ?? 0) > 1) linesOf(block);
269
+ if (!block.element.querySelector(`br[${WORD_PAGE_BREAK_ATTR}]`)) return;
270
+ const bottoms = linesOf(block);
271
+ if (breakLines(block.element, bottoms).includes(bottoms.length - 1)) endsWithBreak.add(block);
272
+ });
273
+ measuring.page.remove();
274
+
275
+ const count = Math.max(1, ...fragments.flat().map((f) => f.page + 1));
276
+ const groupPages = Array.from({ length: count }, () => createPage(doc, g));
277
+ let previousOnPage: { page: number; block: number } | null = null;
278
+ group.blocks.forEach((block, b) => {
279
+ const placed = fragments[b] ?? [];
280
+ const bottoms = placed.length > 1 ? linesOf(block) : [];
281
+ placed.forEach((fragment, f) => {
282
+ const target = groupPages[fragment.page] as { body: HTMLElement };
283
+ let gap = 0;
284
+ if (fragment.fromLine === 0) {
285
+ if (previousOnPage?.page === fragment.page)
286
+ gap = (group.blocks[previousOnPage.block] as WordBlock).after + block.before;
287
+ else {
288
+ // The first block on a page: Word keeps its space before on the section's first
289
+ // page and after an explicit break only.
290
+ const prior = group.blocks[b - 1];
291
+ const forced =
292
+ fragment.page === 0 ||
293
+ block.pageBreakBefore ||
294
+ (prior !== undefined && endsWithBreak.has(prior));
295
+ gap = forced ? block.before : 0;
296
+ }
297
+ }
298
+ let element: HTMLElement = block.element;
299
+ if (placed.length > 1) {
300
+ // A split block: each fragment shows its lines of the whole block, clipped.
301
+ const top = fragment.fromLine ? (bottoms[fragment.fromLine - 1] ?? 0) : 0;
302
+ const end =
303
+ fragment.toLine === Number.POSITIVE_INFINITY
304
+ ? (bottoms[bottoms.length - 1] ?? 0)
305
+ : (bottoms[fragment.toLine - 1] ?? 0);
306
+ const clip = doc.createElement("div");
307
+ clip.style.overflow = "hidden";
308
+ clip.style.height = `${end - top}px`;
309
+ const inner = f === 0 ? block.element : (block.element.cloneNode(true) as HTMLElement);
310
+ if (f > 0) inner.setAttribute("aria-hidden", "true");
311
+ inner.style.marginTop = `${-top}px`;
312
+ clip.append(inner);
313
+ element = clip;
314
+ const repeat = f > 0 ? (headers.get(block) ?? 0) : 0;
315
+ if (repeat) {
316
+ // The header rows again above the continuation.
317
+ const header = doc.createElement("div");
318
+ header.style.overflow = "hidden";
319
+ header.style.height = `${repeat}px`;
320
+ const copy = block.element.cloneNode(true) as HTMLElement;
321
+ copy.setAttribute("aria-hidden", "true");
322
+ copy.style.marginTop = "0";
323
+ header.append(copy);
324
+ element = doc.createElement("div");
325
+ element.append(header, clip);
326
+ }
327
+ }
328
+ element.style.marginTop = `${gap}px`;
329
+ target.body.append(element);
330
+ previousOnPage = { page: fragment.page, block: b };
331
+ placements.push({
332
+ page: pages.length + fragment.page,
333
+ nodes: f === 0 ? block.nodes : null,
334
+ lines: () =>
335
+ (fragment.toLine === Number.POSITIVE_INFINITY
336
+ ? linesOf(block).length
337
+ : fragment.toLine) - fragment.fromLine,
338
+ });
339
+ });
340
+ const first = placed[0];
341
+ if (first) for (const index of block.nodes) firstPage.set(index, pages.length + first.page);
342
+ });
343
+ for (const { page } of groupPages) {
344
+ container.append(page);
345
+ pages.push(page);
346
+ }
347
+ }
348
+ let firstLine: Map<number, number> | null = null;
349
+ return {
350
+ pages,
351
+ pageOf: (index) => firstPage.get(index),
352
+ lineOf: (index) => {
353
+ if (!firstLine) {
354
+ firstLine = new Map();
355
+ let page = -1;
356
+ let line = 1;
357
+ for (const placement of placements) {
358
+ if (placement.page !== page) {
359
+ page = placement.page;
360
+ line = 1;
361
+ }
362
+ for (const node of placement.nodes ?? []) firstLine.set(node, line);
363
+ line += placement.lines();
364
+ }
365
+ }
366
+ return firstLine.get(index);
367
+ },
368
+ destroy: () => {
369
+ for (const page of pages) page.remove();
370
+ },
371
+ };
372
+ }