@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,826 @@
1
+ /**
2
+ * Schema v3 blocks as DOM, formatted as Word formats them (8.6b): every paragraph's and run's
3
+ * effective formatting from `Resolver` as inline CSS, list markers, tracked changes, comment
4
+ * anchors, and content the model keeps opaque shown as text. Read-only: built with
5
+ * createElement/textContent only (never innerHTML); the page layout is in `pages.ts`.
6
+ */
7
+ import {
8
+ type FoliDocument,
9
+ type ListMarker,
10
+ type MarkJSON,
11
+ type NodeJSON,
12
+ type ParagraphFormat,
13
+ Resolver,
14
+ type RunFormat,
15
+ type SectionJSON,
16
+ } from "@folijs/core";
17
+
18
+ /** Marks the <br> of an explicit page break (the page flow ends the page after its line). */
19
+ export const WORD_PAGE_BREAK_ATTR = "data-page-break";
20
+
21
+ /** CSS px per twip (1/1440 inch; CSS: 96 px per inch). */
22
+ export const PX_PER_TWIP = 96 / 1440;
23
+
24
+ /** Which version of tracked changes to show. */
25
+ /** How tracked changes show (`@folijs/core`'s, for `renderDocument` too). */
26
+ export type { ReviewView } from "@folijs/core";
27
+
28
+ import type { ReviewView } from "@folijs/core";
29
+
30
+ /** Colors for the authors of changes (contrast 4.5:1 or more on white), picked by name. */
31
+ const AUTHOR_COLORS = [
32
+ "#B5082E",
33
+ "#1F5FAD",
34
+ "#2E7D32",
35
+ "#8E24AA",
36
+ "#A64B00",
37
+ "#00737F",
38
+ "#AD1457",
39
+ "#5D4037",
40
+ ];
41
+
42
+ /** The color of `author`'s changes: always the same for a name. */
43
+ export function authorColor(author: string): string {
44
+ let hash = 0;
45
+ for (const c of author) hash = (hash * 31 + (c.codePointAt(0) ?? 0)) >>> 0;
46
+ return AUTHOR_COLORS[hash % AUTHOR_COLORS.length] as string;
47
+ }
48
+
49
+ /** The bar beside a paragraph with changes (`markup` and `simple`), drawn in the margin. */
50
+ export const CHANGE_BAR = "-4px 0 0 0 #6B6B6B";
51
+
52
+ /**
53
+ * The element around an inserted or deleted run: `ins` or `del` (named for screen readers by
54
+ * its title), styled for `review`. Deleted text not shown is hidden, not left out: the editable
55
+ * view maps positions through it.
56
+ */
57
+ export function changeElement(
58
+ doc: Document,
59
+ inserted: boolean,
60
+ author: string,
61
+ date: string | null,
62
+ review: ReviewView,
63
+ ): HTMLElement {
64
+ const element = doc.createElement(inserted ? "ins" : "del");
65
+ const when = date ? `, ${date.slice(0, 10)}` : "";
66
+ element.title = `${inserted ? "Inserted" : "Deleted"} by ${author || "an unknown author"}${when}`;
67
+ if (review === "markup") {
68
+ element.style.color = authorColor(author);
69
+ element.style.textDecorationLine = inserted ? "underline" : "line-through";
70
+ } else {
71
+ element.style.textDecorationLine = "none";
72
+ if (!inserted) element.style.display = "none";
73
+ }
74
+ return element;
75
+ }
76
+
77
+ export interface BlockOptions {
78
+ /** `markup` (the default): insertions underlined, deletions struck through; `simple`, `final`: as if accepted. */
79
+ review?: ReviewView;
80
+ /**
81
+ * The ratio of a font's normal line height to its size (`fontFamily`: a CSS font-family
82
+ * list). Word's single line spacing is the font's own line height; multiples scale it.
83
+ * Measured by the page layout; 1.2 when nothing measures (no layout engine).
84
+ */
85
+ lineRatio?: (fontFamily: string) => number;
86
+ }
87
+
88
+ /** A rendered block and what the page flow needs to know about it. */
89
+ export interface WordBlock {
90
+ element: HTMLElement;
91
+ /** Indices in the document's content of the nodes it shows (several when paragraphs merged). */
92
+ nodes: number[];
93
+ /** Space before and after, in CSS px (Word adds them: the flow places them). */
94
+ before: number;
95
+ after: number;
96
+ keepNext: boolean;
97
+ keepLines: boolean;
98
+ pageBreakBefore: boolean;
99
+ /** The page setup of the section this block ends (null: the section goes on). */
100
+ section: SectionJSON | null;
101
+ }
102
+
103
+ /**
104
+ * Metric-compatible open fonts for Word's common fonts: the same advance widths and line
105
+ * heights, so text breaks into the same lines where the original is not installed.
106
+ */
107
+ const SUBSTITUTES: Record<string, string[]> = {
108
+ calibri: ["Carlito"],
109
+ cambria: ["Caladea"],
110
+ arial: ["Liberation Sans", "Arimo"],
111
+ "times new roman": ["Liberation Serif", "Tinos"],
112
+ "courier new": ["Liberation Mono", "Cousine"],
113
+ georgia: ["Gelasio"],
114
+ };
115
+ const SERIF = new Set(["cambria", "times new roman", "georgia", "garamond", "book antiqua"]);
116
+ const MONOSPACE = new Set(["courier new", "consolas", "courier"]);
117
+
118
+ /** A CSS font-family list for a Word font name: the font, its substitutes, a generic family. */
119
+ export function fontStack(name: string | null): string {
120
+ const font = name ?? "Times New Roman";
121
+ const key = font.toLowerCase();
122
+ const generic = SERIF.has(key) ? "serif" : MONOSPACE.has(key) ? "monospace" : "sans-serif";
123
+ const quote = (f: string) => `"${f.replace(/["\\]/g, "")}"`;
124
+ const substitutes = Object.hasOwn(SUBSTITUTES, key) ? (SUBSTITUTES[key] as string[]) : [];
125
+ return [font, ...substitutes].map(quote).concat(generic).join(", ");
126
+ }
127
+
128
+ /** Word's highlight colors (`w:highlight`). */
129
+ const HIGHLIGHTS: Record<string, string> = {
130
+ black: "#000000",
131
+ blue: "#0000FF",
132
+ cyan: "#00FFFF",
133
+ green: "#00FF00",
134
+ magenta: "#FF00FF",
135
+ red: "#FF0000",
136
+ yellow: "#FFFF00",
137
+ white: "#FFFFFF",
138
+ darkBlue: "#000080",
139
+ darkCyan: "#008080",
140
+ darkGreen: "#008000",
141
+ darkMagenta: "#800080",
142
+ darkRed: "#800000",
143
+ darkYellow: "#808000",
144
+ darkGray: "#808080",
145
+ lightGray: "#C0C0C0",
146
+ };
147
+
148
+ const UNDERLINES: Record<string, string> = {
149
+ double: "double",
150
+ dotted: "dotted",
151
+ dottedHeavy: "dotted",
152
+ dash: "dashed",
153
+ dashedHeavy: "dashed",
154
+ dashLong: "dashed",
155
+ wave: "wavy",
156
+ wavyHeavy: "wavy",
157
+ wavyDouble: "wavy",
158
+ };
159
+
160
+ const ALIGN: Record<string, string> = {
161
+ left: "left",
162
+ start: "left",
163
+ right: "right",
164
+ end: "right",
165
+ center: "center",
166
+ both: "justify",
167
+ distribute: "justify",
168
+ };
169
+
170
+ const BORDER_STYLES: Record<string, string> = {
171
+ double: "double",
172
+ dotted: "dotted",
173
+ dashed: "dashed",
174
+ dashSmallGap: "dashed",
175
+ none: "none",
176
+ nil: "none",
177
+ };
178
+
179
+ /** The one font name a run shows for Latin text. */
180
+ export const latin = (run: RunFormat) => run.font.ascii ?? run.font.hAnsi;
181
+
182
+ /** A line height in CSS for text in `run` (`ratio`: its font's normal line height ratio). */
183
+ export function lineHeight(paragraph: ParagraphFormat, run: RunFormat, ratio: number): string {
184
+ const sizePx = (run.size / 2) * (96 / 72);
185
+ const { line, lineRule } = paragraph.spacing;
186
+ if (line === null) return String(ratio);
187
+ if (lineRule === "exact") return `${line * PX_PER_TWIP}px`;
188
+ if (lineRule === "atLeast") return `${Math.max(line * PX_PER_TWIP, ratio * sizePx)}px`;
189
+ return String((ratio * line) / 240);
190
+ }
191
+
192
+ /** Run formatting as inline CSS on `element`. */
193
+ export function styleRun(element: HTMLElement, run: RunFormat, line: string): void {
194
+ const { style } = element;
195
+ style.fontFamily = fontStack(latin(run));
196
+ style.fontSize = `${run.size / 2}pt`;
197
+ style.lineHeight = line;
198
+ style.fontWeight = run.bold ? "700" : "400";
199
+ style.fontStyle = run.italic ? "italic" : "normal";
200
+ const decorations = [];
201
+ if (run.underline) decorations.push("underline");
202
+ if (run.strike || run.doubleStrike) decorations.push("line-through");
203
+ if (decorations.length) {
204
+ style.textDecorationLine = decorations.join(" ");
205
+ if (run.doubleStrike || run.underline === "double") style.textDecorationStyle = "double";
206
+ else if (run.underline && UNDERLINES[run.underline])
207
+ style.textDecorationStyle = UNDERLINES[run.underline] as string;
208
+ if (run.underlineColor && run.underlineColor !== "auto")
209
+ style.textDecorationColor = `#${run.underlineColor}`;
210
+ }
211
+ if (run.caps) style.textTransform = "uppercase";
212
+ if (run.smallCaps) style.fontVariant = "small-caps";
213
+ if (run.color) style.color = `#${run.color}`;
214
+ const background = run.highlight ? HIGHLIGHTS[run.highlight] : run.shading && `#${run.shading}`;
215
+ if (background) style.backgroundColor = background;
216
+ if (run.verticalAlign !== "baseline") {
217
+ // Word raises or lowers a smaller copy without growing the line.
218
+ style.verticalAlign = run.verticalAlign === "superscript" ? "super" : "sub";
219
+ style.fontSize = `${(run.size / 2) * (2 / 3)}pt`;
220
+ style.lineHeight = "0";
221
+ }
222
+ if (run.characterSpacing) style.letterSpacing = `${run.characterSpacing * PX_PER_TWIP}px`;
223
+ if (run.hidden) style.display = "none";
224
+ }
225
+
226
+ /** Paragraph properties as inline CSS on `element` (spacing is the flow's). */
227
+ export function styleParagraph(element: HTMLElement, paragraph: ParagraphFormat): void {
228
+ const { style } = element;
229
+ style.margin = "0";
230
+ style.whiteSpace = "pre-wrap";
231
+ style.overflowWrap = "break-word";
232
+ // Word's default tab stops: every half inch.
233
+ style.tabSize = `${720 * PX_PER_TWIP}px`;
234
+ const { left, right, firstLine, hanging } = paragraph.indent;
235
+ style.paddingLeft = `${left * PX_PER_TWIP}px`;
236
+ style.paddingRight = `${right * PX_PER_TWIP}px`;
237
+ style.textIndent = `${(firstLine - hanging) * PX_PER_TWIP}px`;
238
+ const align = paragraph.justification && ALIGN[paragraph.justification];
239
+ if (align) style.textAlign = align;
240
+ if (paragraph.shading?.fill && paragraph.shading.fill !== "auto")
241
+ style.backgroundColor = `#${paragraph.shading.fill}`;
242
+ for (const [side, border] of Object.entries(paragraph.borders ?? {})) {
243
+ if (!border || side === "between" || side === "bar") continue;
244
+ const kind = BORDER_STYLES[border.style] ?? "solid";
245
+ // Sizes in eighths of a point; the space between text and border in points.
246
+ const width = kind === "none" ? 0 : Math.max(((border.size ?? 4) / 8) * (96 / 72), 1);
247
+ const color = border.color && border.color !== "auto" ? `#${border.color}` : "currentColor";
248
+ style.setProperty(`border-${side}`, `${width}px ${kind} ${color}`);
249
+ style.setProperty(`padding-${side}`, `${((border.space ?? 0) * 96) / 72}px`);
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Opaque XML not shown in the line: a text box's content (it floats; shortcut: not shown until
255
+ * Phase 11 lays out drawings) and the fallback copy of alternate content (`mc:Fallback`, the
256
+ * same drawing again for older readers).
257
+ */
258
+ const NOT_INLINE = new Set(["txbxContent", "Fallback"]);
259
+
260
+ /** Text a run of opaque XML shows: its `w:t` elements (field results, content controls). */
261
+ export function opaqueText(element: Element): string {
262
+ let text = "";
263
+ for (const node of element.children) {
264
+ if (NOT_INLINE.has(node.localName)) continue;
265
+ if (node.localName === "t") text += node.textContent;
266
+ else if (node.localName === "tab") text += "\t";
267
+ else text += opaqueText(node);
268
+ }
269
+ return text;
270
+ }
271
+
272
+ /** Opaque XML's text, a line per paragraph (`w:p`), or its runs' text when it has none. */
273
+ export function opaqueParagraphsText(element: Element): string {
274
+ const paragraphs = [...element.getElementsByTagName("*")].filter((e) => e.localName === "p");
275
+ if (element.localName === "p") paragraphs.unshift(element);
276
+ return paragraphs.length ? paragraphs.map(opaqueText).join("\n") : opaqueText(element);
277
+ }
278
+
279
+ /**
280
+ * The outermost descendants of opaque XML with one of `names` (local names), in order: not those
281
+ * inside a match (a run's text box, a cell's nested table) or content not shown in the line.
282
+ */
283
+ function outermost(element: Element, names: ReadonlySet<string>): Element[] {
284
+ const found: Element[] = [];
285
+ for (const node of element.children) {
286
+ if (names.has(node.localName)) found.push(node);
287
+ else if (!NOT_INLINE.has(node.localName)) found.push(...outermost(node, names));
288
+ }
289
+ return found;
290
+ }
291
+ const PARAGRAPHS = new Set(["p"]);
292
+ const RUNS = new Set(["r"]);
293
+ const ROWS = new Set(["tr"]);
294
+ const CELLS = new Set(["tc"]);
295
+ const CELL_CONTENT = new Set(["p", "tbl"]);
296
+
297
+ /**
298
+ * Parses verbatim WordprocessingML (opaque content) into an inert XML document, declaring the
299
+ * prefixes it uses; null when it is not well-formed.
300
+ */
301
+ export function parseOpaque(xml: string, doc: Document): Element | null {
302
+ const view = doc.defaultView;
303
+ if (!view?.DOMParser) return null;
304
+ const prefixes = new Set<string>();
305
+ for (const match of xml.matchAll(/<\/?([A-Za-z_][\w.-]*):|\s([A-Za-z_][\w.-]*):[\w.-]+\s*=/g)) {
306
+ const prefix = match[1] ?? match[2];
307
+ if (prefix && prefix !== "xml" && prefix !== "xmlns") prefixes.add(prefix);
308
+ }
309
+ const declarations = [...prefixes].map((p) => ` xmlns:${p}="urn:foli:${p}"`).join("");
310
+ const parsed = new view.DOMParser().parseFromString(
311
+ `<foli${declarations}>${xml}</foli>`,
312
+ "application/xml",
313
+ );
314
+ const root = parsed.documentElement;
315
+ if (root.localName !== "foli" || parsed.getElementsByTagName("parsererror").length) return null;
316
+ return root.firstElementChild;
317
+ }
318
+
319
+ /**
320
+ * Renders a document's blocks. `final` review merges a paragraph whose mark was deleted into
321
+ * the next one, as accepting the deletion does.
322
+ */
323
+ export function renderBlocks(
324
+ document: FoliDocument,
325
+ doc: Document,
326
+ options: BlockOptions = {},
327
+ ): WordBlock[] {
328
+ const review = options.review ?? "markup";
329
+ const ratios = new Map<string, number>();
330
+ const ratio = (family: string) => {
331
+ let value = ratios.get(family);
332
+ if (value === undefined) {
333
+ value = options.lineRatio?.(family) ?? 1.2;
334
+ ratios.set(family, value);
335
+ }
336
+ return value;
337
+ };
338
+ const resolver = new Resolver(document);
339
+ const content = document.content.content ?? [];
340
+ const attrsOf = (node: NodeJSON) => (node.attrs ?? {}) as Record<string, unknown>;
341
+ // In the final and simple views a paragraph whose mark was deleted joins the next paragraph
342
+ // (not a table, and the document's last mark cannot be deleted).
343
+ const joins = (index: number) => {
344
+ const node = content[index];
345
+ const revision = node && (attrsOf(node).revision as { deletion?: unknown } | null | undefined);
346
+ return (
347
+ review !== "markup" &&
348
+ node?.type === "paragraph" &&
349
+ !!revision?.deletion &&
350
+ content[index + 1]?.type === "paragraph"
351
+ );
352
+ };
353
+ // A joined paragraph is numbered once, with the first paragraph's marker.
354
+ const markers = resolver.markers(
355
+ content.map((node, index) =>
356
+ node.type === "paragraph" && !joins(index - 1) ? attrsOf(node) : { numbering: { id: 0 } },
357
+ ),
358
+ );
359
+ const blocks: WordBlock[] = [];
360
+ let carried: { nodes: number[]; inline: NodeJSON[] } | null = null;
361
+ /** Comment ranges open at this point of the document. */
362
+ const comments = new Set<number>();
363
+
364
+ content.forEach((node, index) => {
365
+ if (node.type !== "paragraph") {
366
+ blocks.push(opaqueBlock(node, index, resolver, doc, ratio));
367
+ return;
368
+ }
369
+ const attrs = attrsOf(node);
370
+ if (joins(index)) {
371
+ const previous: { nodes: number[]; inline: NodeJSON[] } = carried ?? {
372
+ nodes: [],
373
+ inline: [],
374
+ };
375
+ carried = {
376
+ nodes: [...previous.nodes, index],
377
+ inline: [...previous.inline, ...(node.content ?? [])],
378
+ };
379
+ return;
380
+ }
381
+ const merged: { nodes: number[]; inline: NodeJSON[] } = carried ?? { nodes: [], inline: [] };
382
+ carried = null;
383
+ const { paragraph, run } = resolver.paragraph(attrs);
384
+ const element = doc.createElement(tagOf(paragraph));
385
+ styleParagraph(element, paragraph);
386
+ styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
387
+ const marker = markers[index];
388
+ const firstMerged = merged.nodes[0];
389
+ const shownMarker = firstMerged !== undefined ? (markers[firstMerged] ?? null) : marker;
390
+ if (shownMarker) element.append(markerElement(shownMarker, paragraph, doc, ratio));
391
+ const inline = [...merged.inline, ...(node.content ?? [])];
392
+ renderInline(element, inline, run, paragraph, {
393
+ resolver,
394
+ doc,
395
+ review,
396
+ comments,
397
+ ratio,
398
+ });
399
+ // An empty paragraph, or one ending in a line break, shows its last (empty) line; after a
400
+ // page break the paragraph mark stays on the break's line, as in Word.
401
+ const last = element.lastChild as Element | null;
402
+ const endsInBreak = last?.nodeName === "BR";
403
+ if (
404
+ (endsInBreak && !last?.hasAttribute(WORD_PAGE_BREAK_ATTR)) ||
405
+ (!endsInBreak && !element.textContent)
406
+ )
407
+ element.append(doc.createElement("br"));
408
+ const pt = (twips: number) => twips * PX_PER_TWIP;
409
+ const { before, after } = paragraph.spacing;
410
+ // Word's automatic spacing (HTML): 14 pt.
411
+ const spaceBefore = paragraph.spacing.beforeAutospacing ? 280 : before;
412
+ const spaceAfter = paragraph.spacing.afterAutospacing ? 280 : after;
413
+ blocks.push({
414
+ element,
415
+ nodes: [...merged.nodes, index],
416
+ before: pt(spaceBefore),
417
+ after: pt(spaceAfter),
418
+ keepNext: paragraph.keepNext,
419
+ keepLines: paragraph.keepLines,
420
+ pageBreakBefore: paragraph.pageBreakBefore,
421
+ section: (attrs.section as SectionJSON | null | undefined) ?? null,
422
+ });
423
+ element.dataset.style = paragraph.style ?? "";
424
+ if (paragraph.contextualSpacing) element.dataset.contextual = "";
425
+ });
426
+ applyContextualSpacing(blocks);
427
+ return blocks;
428
+ }
429
+
430
+ /** A paragraph's element: a heading of its outline level (1-6), else a paragraph. */
431
+ export function tagOf(paragraph: ParagraphFormat): string {
432
+ const level = paragraph.outlineLevel;
433
+ return level !== null && level >= 0 && level < 6 ? `h${level + 1}` : "p";
434
+ }
435
+
436
+ /** Word ignores the space between paragraphs of the same style that ask for it. */
437
+ function applyContextualSpacing(blocks: WordBlock[]): void {
438
+ for (let i = 1; i < blocks.length; i++) {
439
+ const a = blocks[i - 1] as WordBlock;
440
+ const b = blocks[i] as WordBlock;
441
+ const style = a.element.dataset.style;
442
+ if (style === undefined || style !== b.element.dataset.style) continue;
443
+ if ("contextual" in a.element.dataset) a.after = 0;
444
+ if ("contextual" in b.element.dataset) b.before = 0;
445
+ }
446
+ }
447
+
448
+ /** Symbol and Wingdings bullets (`w:lvlText`, private-use code points) as Unicode. */
449
+ const SYMBOLS: Record<string, string> = {
450
+ "\uF0B7": "\u2022", // Symbol: bullet
451
+ "\uF0A7": "\u25AA", // Wingdings: small black square
452
+ "\uF0A8": "\u25FB", // Wingdings: white medium square
453
+ "\uF06C": "\u25CF", // Wingdings: black circle
454
+ "\uF06E": "\u25A0", // Wingdings: black square
455
+ "\uF071": "\u2751", // Wingdings: shadowed white square
456
+ "\uF075": "\u25C6", // Wingdings: black diamond
457
+ "\uF076": "\u2756", // Wingdings: black diamond minus white X
458
+ "\uF0D8": "\u27A2", // Wingdings: arrowhead
459
+ "\uF0FC": "\u2713", // Wingdings: check mark
460
+ };
461
+
462
+ /** A list marker: its text, then what follows it (a tab to the text's indent, a space). */
463
+ export function markerElement(
464
+ marker: ListMarker,
465
+ paragraph: ParagraphFormat,
466
+ doc: Document,
467
+ ratio: (family: string) => number,
468
+ ): HTMLElement {
469
+ const span = doc.createElement("span");
470
+ span.dataset.foliMarker = "";
471
+ span.setAttribute("aria-hidden", "true");
472
+ styleRun(
473
+ span,
474
+ marker.run,
475
+ lineHeight(paragraph, marker.run, ratio(fontStack(latin(marker.run)))),
476
+ );
477
+ span.textContent = marker.text;
478
+ // Bullets in Symbol and Wingdings are private-use code points: shown as the Unicode
479
+ // character they draw, in a font that has it.
480
+ const font = latin(marker.run)?.toLowerCase();
481
+ const glyph =
482
+ font === "symbol" || font?.startsWith("wingdings") ? SYMBOLS[marker.text] : undefined;
483
+ if (glyph) {
484
+ span.textContent = glyph;
485
+ span.style.fontFamily = "sans-serif";
486
+ }
487
+ const hanging = paragraph.indent.hanging * PX_PER_TWIP;
488
+ if (marker.suffix === "tab" && hanging > 0) {
489
+ // shortcut: a marker wider than the hanging indent goes to the next default tab stop in
490
+ // Word; here the text follows it directly.
491
+ span.style.display = "inline-block";
492
+ span.style.minWidth = `${hanging}px`;
493
+ span.style.textIndent = "0";
494
+ } else if (marker.suffix === "tab") span.textContent += "\t";
495
+ else if (marker.suffix === "space") span.textContent += " ";
496
+ return span;
497
+ }
498
+
499
+ interface InlineContext {
500
+ resolver: Resolver;
501
+ doc: Document;
502
+ review: ReviewView;
503
+ comments: Set<number>;
504
+ ratio: (family: string) => number;
505
+ }
506
+
507
+ /** A paragraph's inline content: runs as spans, breaks, comment anchors, opaque inline content. */
508
+ function renderInline(
509
+ parent: HTMLElement,
510
+ inline: readonly NodeJSON[],
511
+ paragraphRun: RunFormat,
512
+ paragraph: ParagraphFormat,
513
+ context: InlineContext,
514
+ ): void {
515
+ const { resolver, doc, review, comments, ratio } = context;
516
+ for (const node of inline) {
517
+ const marks = (node.marks ?? []) as MarkJSON[];
518
+ const inserted = marks.some((m) => m.type === "insertion");
519
+ const deleted = marks.some((m) => m.type === "deletion");
520
+ if (deleted && review !== "markup") continue;
521
+ const attrs = (node.attrs ?? {}) as Record<string, unknown>;
522
+ switch (node.type) {
523
+ case "commentStart":
524
+ comments.add(attrs.id as number);
525
+ continue;
526
+ case "commentEnd":
527
+ comments.delete(attrs.id as number);
528
+ continue;
529
+ case "commentReference": {
530
+ const anchor = doc.createElement("span");
531
+ anchor.dataset.foliCommentReference = String(attrs.id);
532
+ parent.append(anchor);
533
+ continue;
534
+ }
535
+ case "bookmarkStart":
536
+ case "bookmarkEnd":
537
+ continue;
538
+ case "hardBreak":
539
+ case "columnBreak":
540
+ // shortcut: a column break ends the line; Foli lays out one column.
541
+ parent.append(doc.createElement("br"));
542
+ continue;
543
+ case "pageBreak": {
544
+ const br = doc.createElement("br");
545
+ br.setAttribute(WORD_PAGE_BREAK_ATTR, "");
546
+ parent.append(br);
547
+ continue;
548
+ }
549
+ default:
550
+ }
551
+ let text: string;
552
+ if (node.type === "text") text = node.text ?? "";
553
+ else if (node.type === "tab") text = "\t";
554
+ else if (node.type === "opaqueInline") {
555
+ const xml = parseOpaque(String(attrs.xml ?? ""), doc);
556
+ // A run's content (a drawing, a field character) shows as nothing; a content control or
557
+ // simple field as its text.
558
+ text = xml ? opaqueText(xml) : "";
559
+ if (!text) {
560
+ const placeholder = doc.createElement("span");
561
+ placeholder.dataset.foliOpaque = String(attrs.label ?? "");
562
+ parent.append(placeholder);
563
+ continue;
564
+ }
565
+ } else continue;
566
+ const run = resolver.run(paragraphRun, marks);
567
+ let element: HTMLElement = doc.createElement("span");
568
+ styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
569
+ element.textContent = text;
570
+ const link = marks.find((m) => m.type === "link");
571
+ if (link) element.dataset.href = String(link.attrs?.href ?? `#${String(link.attrs?.anchor)}`);
572
+ if (comments.size) {
573
+ element.dataset.foliComments = [...comments].join(" ");
574
+ if (!run.highlight && !run.shading)
575
+ element.style.backgroundColor = "rgba(255, 213, 79, 0.35)";
576
+ }
577
+ if (review === "markup" && (inserted || deleted)) {
578
+ // Inserted, then deleted: shown as deleted, in the deleting author's color.
579
+ const change = marks.find((m) => m.type === (deleted ? "deletion" : "insertion"))?.attrs;
580
+ const author = String(change?.author ?? "");
581
+ const date = (change?.date as string | null | undefined) ?? null;
582
+ const wrapper = changeElement(doc, !deleted, author, date, review);
583
+ wrapper.append(element);
584
+ element = wrapper;
585
+ }
586
+ parent.append(element);
587
+ }
588
+ }
589
+
590
+ /**
591
+ * A block the model keeps opaque (tables until Phase 10, block content controls), shown from
592
+ * its XML: a table as a table of its cells' paragraphs, anything else as its paragraphs. Only
593
+ * text is read: no formatting beyond the paragraph styles.
594
+ */
595
+ export function opaqueBlock(
596
+ node: NodeJSON,
597
+ index: number,
598
+ resolver: Resolver,
599
+ doc: Document,
600
+ ratio: (family: string) => number,
601
+ ): WordBlock {
602
+ const attrs = (node.attrs ?? {}) as Record<string, unknown>;
603
+ const element = doc.createElement("div");
604
+ element.dataset.foliOpaque = String(attrs.label ?? "");
605
+ element.style.margin = "0";
606
+ element.style.display = "flow-root";
607
+ const xml = parseOpaque(String(attrs.xml ?? ""), doc);
608
+ let after = 0;
609
+ if (xml?.localName === "tbl") element.append(opaqueTable(xml, resolver, doc, ratio));
610
+ else if (xml) {
611
+ const paragraphs = outermost(xml, PARAGRAPHS);
612
+ paragraphs.forEach((p, i) => {
613
+ const rendered = opaqueParagraph(p, resolver, doc, ratio);
614
+ if (i < paragraphs.length - 1) rendered.element.style.marginBottom = `${rendered.after}px`;
615
+ else after = rendered.after;
616
+ element.append(rendered.element);
617
+ });
618
+ }
619
+ if (!element.firstChild) {
620
+ // Nothing to show: a placeholder line.
621
+ element.style.minHeight = "1em";
622
+ element.style.outline = "1px dashed #999";
623
+ }
624
+ return {
625
+ element,
626
+ nodes: [index],
627
+ before: 0,
628
+ after,
629
+ keepNext: false,
630
+ keepLines: false,
631
+ pageBreakBefore: false,
632
+ section: null,
633
+ };
634
+ }
635
+
636
+ /** The value of a WordprocessingML child's `w:val` (by local names). */
637
+ function childValue(element: Element | null | undefined, name: string, attribute = "val") {
638
+ for (const child of element?.children ?? []) {
639
+ if (child.localName !== name) continue;
640
+ for (const a of child.attributes) if (a.localName === attribute) return a.value;
641
+ }
642
+ return undefined;
643
+ }
644
+ function child(element: Element | null | undefined, name: string): Element | undefined {
645
+ for (const c of element?.children ?? []) if (c.localName === name) return c;
646
+ return undefined;
647
+ }
648
+
649
+ /** A paragraph of opaque XML: its style's formatting and its text. */
650
+ function opaqueParagraph(
651
+ p: Element,
652
+ resolver: Resolver,
653
+ doc: Document,
654
+ ratio: (family: string) => number,
655
+ ): { element: HTMLElement; after: number } {
656
+ const pPr = child(p, "pPr");
657
+ const style = childValue(pPr, "pStyle");
658
+ const justification = childValue(pPr, "jc");
659
+ const { paragraph, run } = resolver.paragraph({
660
+ ...(style ? { style } : {}),
661
+ ...(justification ? { justification } : {}),
662
+ });
663
+ const element = doc.createElement(tagOf(paragraph));
664
+ styleParagraph(element, paragraph);
665
+ styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
666
+ for (const r of outermost(p, RUNS)) {
667
+ // Deleted text is `w:delText`: not read, in markup too (shortcut: shown as accepted).
668
+ const text = opaqueText(r);
669
+ const formatted = resolver.run(run, runMarks(child(r, "rPr")));
670
+ const span = doc.createElement("span");
671
+ styleRun(span, formatted, lineHeight(paragraph, formatted, ratio(fontStack(latin(formatted)))));
672
+ span.textContent = text;
673
+ element.append(span);
674
+ }
675
+ if (!element.textContent) element.append(doc.createElement("br"));
676
+ if (paragraph.spacing.before)
677
+ element.style.marginTop = `${paragraph.spacing.before * PX_PER_TWIP}px`;
678
+ return { element, after: paragraph.spacing.after * PX_PER_TWIP };
679
+ }
680
+
681
+ /** The run properties of verbatim XML Foli reads for showing it (`w:rPr`) as marks. */
682
+ function runMarks(rPr: Element | undefined): MarkJSON[] {
683
+ const marks: MarkJSON[] = [];
684
+ const on = (name: string) => {
685
+ const value = childValue(rPr, name);
686
+ return value === undefined || !["0", "false", "off"].includes(value);
687
+ };
688
+ const style = childValue(rPr, "rStyle");
689
+ if (style) marks.push({ type: "characterStyle", attrs: { id: style } });
690
+ for (const [name, type] of [
691
+ ["b", "bold"],
692
+ ["i", "italic"],
693
+ ["caps", "caps"],
694
+ ["smallCaps", "smallCaps"],
695
+ ["strike", "strike"],
696
+ ] as const)
697
+ if (child(rPr, name)) marks.push({ type, attrs: { value: on(name) } });
698
+ const underline = childValue(rPr, "u");
699
+ if (underline) marks.push({ type: "underline", attrs: { style: underline } });
700
+ const color = childValue(rPr, "color");
701
+ if (color) marks.push({ type: "color", attrs: { value: color } });
702
+ const size = Number(childValue(rPr, "sz"));
703
+ if (size > 0) marks.push({ type: "fontSize", attrs: { value: size } });
704
+ const highlight = childValue(rPr, "highlight");
705
+ if (highlight) marks.push({ type: "highlight", attrs: { value: highlight } });
706
+ return marks;
707
+ }
708
+
709
+ /** A WordprocessingML border (`w:top`, `w:insideH`…) as CSS; undefined when it says none. */
710
+ function borderCss(border: Element | undefined): string | undefined {
711
+ if (!border) return undefined;
712
+ const value = childValueOf(border, "val") ?? "single";
713
+ if (value === "nil" || value === "none") return "none";
714
+ const size = Number(childValueOf(border, "sz") ?? 4);
715
+ const color = childValueOf(border, "color");
716
+ const kind = BORDER_STYLES[value] ?? "solid";
717
+ // Sizes in eighths of a point.
718
+ const width = Math.max((size / 8) * (96 / 72), 0.5);
719
+ return `${width}px ${kind} ${color && color !== "auto" ? `#${color}` : "#000"}`;
720
+ }
721
+
722
+ /** Cell margins (`w:tblCellMar`, `w:tcMar`) in px by side, over `base`. */
723
+ function margins(element: Element | undefined, base: Record<string, number>) {
724
+ const out = { ...base };
725
+ for (const side of element?.children ?? []) {
726
+ const name =
727
+ side.localName === "start" ? "left" : side.localName === "end" ? "right" : side.localName;
728
+ const width = Number(childValueOf(side, "w"));
729
+ if (name in out && Number.isFinite(width)) out[name] = width * PX_PER_TWIP;
730
+ }
731
+ return out;
732
+ }
733
+
734
+ /** A table of opaque XML: rows, cells (spans, widths, margins, borders, shading) and their paragraphs. */
735
+ function opaqueTable(
736
+ tbl: Element,
737
+ resolver: Resolver,
738
+ doc: Document,
739
+ ratio: (family: string) => number,
740
+ ): HTMLElement {
741
+ const table = doc.createElement("table");
742
+ const { style } = table;
743
+ style.borderCollapse = "collapse";
744
+ style.tableLayout = "fixed";
745
+ const tblPr = child(tbl, "tblPr");
746
+ const borders = child(tblPr, "tblBorders");
747
+ for (const side of ["top", "left", "bottom", "right"]) {
748
+ const css = borderCss(child(borders, side));
749
+ if (css) style.setProperty(`border-${side}`, css);
750
+ }
751
+ // Word's default cell margins: 0.08 inch left and right.
752
+ const tableMargins = margins(child(tblPr, "tblCellMar"), {
753
+ top: 0,
754
+ bottom: 0,
755
+ left: 108 * PX_PER_TWIP,
756
+ right: 108 * PX_PER_TWIP,
757
+ });
758
+ const grid = [...(child(tbl, "tblGrid")?.children ?? [])]
759
+ .filter((c) => c.localName === "gridCol")
760
+ .map((c) => Number(childValueOf(c, "w")) || 0);
761
+ const total = grid.reduce((a, b) => a + b, 0);
762
+ if (total) style.width = `${total * PX_PER_TWIP}px`;
763
+ const colgroup = doc.createElement("colgroup");
764
+ for (const width of grid) {
765
+ const col = doc.createElement("col");
766
+ col.style.width = `${width * PX_PER_TWIP}px`;
767
+ colgroup.append(col);
768
+ }
769
+ table.append(colgroup);
770
+ const inside = {
771
+ horizontal: borderCss(child(borders, "insideH")),
772
+ vertical: borderCss(child(borders, "insideV")),
773
+ };
774
+ const body = doc.createElement("tbody");
775
+ for (const tr of outermost(tbl, ROWS)) {
776
+ const row = doc.createElement("tr");
777
+ const trPr = child(tr, "trPr");
778
+ // A header row, repeated at the top of each page the table continues on.
779
+ const header = childValue(trPr, "tblHeader");
780
+ if (child(trPr, "tblHeader") && header !== "0" && header !== "false")
781
+ row.dataset.foliHeader = "";
782
+ const rowMargins = margins(child(child(tr, "tblPrEx"), "tblCellMar"), tableMargins);
783
+ for (const tc of outermost(tr, CELLS)) {
784
+ const tcPr = child(tc, "tcPr");
785
+ const cell = doc.createElement("td");
786
+ const span = Number(childValue(tcPr, "gridSpan"));
787
+ if (span > 1) cell.colSpan = span;
788
+ const fill = childValue(tcPr, "shd", "fill");
789
+ if (fill && fill !== "auto") cell.style.backgroundColor = `#${fill}`;
790
+ const m = margins(child(tcPr, "tcMar"), rowMargins);
791
+ cell.style.padding = `${m.top}px ${m.right}px ${m.bottom}px ${m.left}px`;
792
+ cell.style.verticalAlign = "top";
793
+ if (inside.horizontal) cell.style.borderTop = cell.style.borderBottom = inside.horizontal;
794
+ if (inside.vertical) cell.style.borderLeft = cell.style.borderRight = inside.vertical;
795
+ const own = child(tcPr, "tcBorders");
796
+ for (const side of ["top", "left", "bottom", "right"]) {
797
+ const css = borderCss(child(own, side));
798
+ if (css) cell.style.setProperty(`border-${side}`, css);
799
+ }
800
+ // A cell merged into the one above shows nothing of its own.
801
+ if (child(tcPr, "vMerge") && childValue(tcPr, "vMerge") !== "restart") {
802
+ row.append(cell);
803
+ continue;
804
+ }
805
+ for (const p of outermost(tc, CELL_CONTENT)) {
806
+ if (p.localName === "tbl") {
807
+ cell.append(opaqueTable(p, resolver, doc, ratio));
808
+ continue;
809
+ }
810
+ // Word counts the space after a cell's last paragraph in the row's height too.
811
+ const rendered = opaqueParagraph(p, resolver, doc, ratio);
812
+ rendered.element.style.marginBottom = `${rendered.after}px`;
813
+ cell.append(rendered.element);
814
+ }
815
+ row.append(cell);
816
+ }
817
+ body.append(row);
818
+ }
819
+ table.append(body);
820
+ return table;
821
+ }
822
+
823
+ function childValueOf(element: Element, attribute: string): string | undefined {
824
+ for (const a of element.attributes) if (a.localName === attribute) return a.value;
825
+ return undefined;
826
+ }