@folijs/view 0.4.0 → 0.6.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/clipboard.d.ts +3 -1
  3. package/dist/clipboard.d.ts.map +1 -1
  4. package/dist/clipboard.js.map +1 -1
  5. package/dist/index.d.ts +2 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/layout/flow.d.ts +195 -20
  10. package/dist/layout/flow.d.ts.map +1 -1
  11. package/dist/layout/flow.js +790 -102
  12. package/dist/layout/flow.js.map +1 -1
  13. package/dist/print.d.ts +22 -0
  14. package/dist/print.d.ts.map +1 -0
  15. package/dist/print.js +31 -0
  16. package/dist/print.js.map +1 -0
  17. package/dist/view.d.ts +407 -8
  18. package/dist/view.d.ts.map +1 -1
  19. package/dist/view.js +2956 -263
  20. package/dist/view.js.map +1 -1
  21. package/dist/word/blocks.d.ts +99 -2
  22. package/dist/word/blocks.d.ts.map +1 -1
  23. package/dist/word/blocks.js +535 -31
  24. package/dist/word/blocks.js.map +1 -1
  25. package/dist/word/columns.d.ts +23 -0
  26. package/dist/word/columns.d.ts.map +1 -0
  27. package/dist/word/columns.js +51 -0
  28. package/dist/word/columns.js.map +1 -0
  29. package/dist/word/controls.d.ts +63 -0
  30. package/dist/word/controls.d.ts.map +1 -0
  31. package/dist/word/controls.js +411 -0
  32. package/dist/word/controls.js.map +1 -0
  33. package/dist/word/edit.d.ts +32 -11
  34. package/dist/word/edit.d.ts.map +1 -1
  35. package/dist/word/edit.js +215 -33
  36. package/dist/word/edit.js.map +1 -1
  37. package/dist/word/matches.d.ts +23 -0
  38. package/dist/word/matches.d.ts.map +1 -0
  39. package/dist/word/matches.js +97 -0
  40. package/dist/word/matches.js.map +1 -0
  41. package/dist/word/notes.d.ts +105 -0
  42. package/dist/word/notes.d.ts.map +1 -0
  43. package/dist/word/notes.js +392 -0
  44. package/dist/word/notes.js.map +1 -0
  45. package/dist/word/pages.d.ts +26 -13
  46. package/dist/word/pages.d.ts.map +1 -1
  47. package/dist/word/pages.js +439 -203
  48. package/dist/word/pages.js.map +1 -1
  49. package/dist/word/regions.d.ts +113 -0
  50. package/dist/word/regions.d.ts.map +1 -0
  51. package/dist/word/regions.js +374 -0
  52. package/dist/word/regions.js.map +1 -0
  53. package/dist/word/table.d.ts +79 -0
  54. package/dist/word/table.d.ts.map +1 -0
  55. package/dist/word/table.js +210 -0
  56. package/dist/word/table.js.map +1 -0
  57. package/package.json +2 -2
  58. package/src/clipboard.ts +3 -0
  59. package/src/index.ts +8 -1
  60. package/src/layout/flow.ts +948 -111
  61. package/src/print.ts +48 -0
  62. package/src/view.ts +3291 -273
  63. package/src/word/blocks.ts +611 -28
  64. package/src/word/columns.ts +66 -0
  65. package/src/word/controls.ts +447 -0
  66. package/src/word/edit.ts +253 -30
  67. package/src/word/matches.ts +99 -0
  68. package/src/word/notes.ts +451 -0
  69. package/src/word/pages.ts +524 -192
  70. package/src/word/regions.ts +469 -0
  71. package/src/word/table.ts +267 -0
@@ -4,11 +4,227 @@
4
4
  * anchors, and content the model keeps opaque shown as text. Read-only: built with
5
5
  * createElement/textContent only (never innerHTML); the page layout is in `pages.ts`.
6
6
  */
7
- import { Resolver, } from "@folijs/core";
7
+ import { fieldDisplay, Resolver, } from "@folijs/core";
8
8
  /** Marks the <br> of an explicit page break (the page flow ends the page after its line). */
9
9
  export const WORD_PAGE_BREAK_ATTR = "data-page-break";
10
+ /** Marks the <br> of an explicit column break (the flow ends the column after its line). */
11
+ export const WORD_COLUMN_BREAK_ATTR = "data-column-break";
10
12
  /** CSS px per twip (1/1440 inch; CSS: 96 px per inch). */
11
13
  export const PX_PER_TWIP = 96 / 1440;
14
+ /** EMU (DrawingML's unit: 914 400 per inch) per CSS px. */
15
+ export const EMU_PER_PX = 914_400 / 96;
16
+ /** Marks a picture's element (its resource key). */
17
+ export const PICTURE_ATTR = "data-foli-picture";
18
+ /** The accessible name of a picture with no alt text that is not decorative. */
19
+ export const NO_ALT_LABEL = "Picture without alt text";
20
+ /**
21
+ * The URL a resource gives on its own: an image `data:` URL, or a web or `blob:` URL; none for
22
+ * an image in a package part (the app's resolver gives one) or anything else.
23
+ */
24
+ export function ownImageUrl(resource) {
25
+ const data = resource?.data;
26
+ if (data && /^data:image\//i.test(data))
27
+ return data;
28
+ const url = resource?.url;
29
+ return url && /^(https?|blob):/i.test(url) ? url : undefined;
30
+ }
31
+ /**
32
+ * A picture as shown: its image at its size, or, when no URL is known for it, a box of that size
33
+ * with its alt text. A picture with no alt text that is not decorative is marked (`data-foli-
34
+ * no-alt`); a decorative one has an empty alt.
35
+ */
36
+ export function pictureElement(attrs, doc, image) {
37
+ const key = String(attrs.resource ?? "");
38
+ const width = `${Number(attrs.width) / EMU_PER_PX}px`;
39
+ const height = `${Number(attrs.height) / EMU_PER_PX}px`;
40
+ const decorative = attrs.decorative === true;
41
+ const own = String(attrs.alt ?? "");
42
+ // Only a decorative picture is silent; one missing its alt text says so.
43
+ const alt = decorative ? "" : own || NO_ALT_LABEL;
44
+ const src = image?.(key);
45
+ let element;
46
+ if (src) {
47
+ const img = doc.createElement("img");
48
+ img.src = src;
49
+ img.alt = alt;
50
+ img.draggable = false;
51
+ // A web URL in a document is fetched as it is shown: no referrer to go with it.
52
+ img.referrerPolicy = "no-referrer";
53
+ element = img;
54
+ }
55
+ else {
56
+ element = doc.createElement("span");
57
+ element.setAttribute("role", "img");
58
+ if (alt)
59
+ element.setAttribute("aria-label", alt);
60
+ else
61
+ element.setAttribute("aria-hidden", "true");
62
+ element.style.boxSizing = "border-box";
63
+ element.style.border = "1px dashed GrayText";
64
+ }
65
+ element.setAttribute(PICTURE_ATTR, key);
66
+ if (!own && !decorative)
67
+ element.dataset.foliNoAlt = "";
68
+ if (attrs.title)
69
+ element.title = String(attrs.title);
70
+ // In the line at its size, whatever the app's CSS says of images (`display: block`…).
71
+ const style = element.style;
72
+ style.display = src ? "inline" : "inline-block";
73
+ style.verticalAlign = "baseline";
74
+ style.maxWidth = "none";
75
+ style.maxHeight = "none";
76
+ style.width = width;
77
+ style.height = height;
78
+ return element;
79
+ }
80
+ /** Marks the element holding a floating picture (its wrapping), drawn at its paragraph's start. */
81
+ export const FLOAT_ATTR = "data-foli-float";
82
+ /** The page geometry of `section` (Word's Letter page and margins where it does not say). */
83
+ export function floatGeometry(section) {
84
+ const m = section?.margins ?? {};
85
+ const width = section?.pageSize?.width ?? 12_240;
86
+ const height = section?.pageSize?.height ?? 15_840;
87
+ const left = (m.left ?? 1440) + (m.gutter ?? 0);
88
+ const top = Math.abs(m.top ?? 1440);
89
+ return {
90
+ pageWidth: width * PX_PER_TWIP,
91
+ pageHeight: height * PX_PER_TWIP,
92
+ marginLeft: left * PX_PER_TWIP,
93
+ marginTop: top * PX_PER_TWIP,
94
+ textWidth: (width - left - (m.right ?? 1440)) * PX_PER_TWIP,
95
+ textHeight: (height - top - Math.abs(m.bottom ?? 1440)) * PX_PER_TWIP,
96
+ };
97
+ }
98
+ /** Where a float's position is measured from, and the box its alignment is in (px). */
99
+ function horizontalBox(relativeTo, g) {
100
+ const right = g.pageWidth - g.marginLeft - g.textWidth;
101
+ switch (relativeTo) {
102
+ case "page":
103
+ return [0, g.pageWidth];
104
+ case "leftMargin":
105
+ case "insideMargin":
106
+ return [0, g.marginLeft];
107
+ case "rightMargin":
108
+ case "outsideMargin":
109
+ return [g.marginLeft + g.textWidth, right];
110
+ default:
111
+ // margin, column, character (shortcut: the column).
112
+ return [g.marginLeft, g.textWidth];
113
+ }
114
+ }
115
+ function verticalBox(relativeTo, g) {
116
+ const bottom = g.pageHeight - g.marginTop - g.textHeight;
117
+ switch (relativeTo) {
118
+ case "page":
119
+ return [0, g.pageHeight];
120
+ case "topMargin":
121
+ case "insideMargin":
122
+ return [0, g.marginTop];
123
+ case "bottomMargin":
124
+ case "outsideMargin":
125
+ return [g.pageHeight - bottom, bottom];
126
+ default:
127
+ return [g.marginTop, g.textHeight];
128
+ }
129
+ }
130
+ /** Where `size` px goes in `[start, start + box)` by offset (EMU) or alignment. */
131
+ function placed(position, [start, box], size) {
132
+ if (typeof position.offset === "number")
133
+ return start + position.offset / EMU_PER_PX;
134
+ const { align } = position;
135
+ if (align === "right" || align === "bottom" || align === "outside")
136
+ return start + box - size;
137
+ if (align === "center")
138
+ return start + (box - size) / 2;
139
+ return start;
140
+ }
141
+ /** Where a float's left edge is, in px from the column's left edge. */
142
+ function floatLeft(h, width, g) {
143
+ return placed(h, horizontalBox(h.relativeTo, g), width) - g.marginLeft;
144
+ }
145
+ /**
146
+ * Where a float's top edge is: from its paragraph's top (`paragraph`), or from the page's top
147
+ * (`page`) for a position against the page or its margins.
148
+ */
149
+ function floatTop(v, height, g) {
150
+ if (v.relativeTo === "paragraph" || v.relativeTo === "line")
151
+ return { paragraph: typeof v.offset === "number" ? v.offset / EMU_PER_PX : 0 };
152
+ return { page: placed(v, verticalBox(v.relativeTo, g), height) };
153
+ }
154
+ /**
155
+ * A floating picture (10.9, ADR-0006) as CSS floats lay it out, put first in its anchor
156
+ * paragraph: `holder` holds the picture (`FLOAT_ATTR`), `nodes` go in the paragraph (a
157
+ * zero-width spacer float before it gives its offset from the paragraph's top).
158
+ * - Square (tight and through shown as square): a float on the side the picture is on, its
159
+ * distance from the text as its margin; text goes on the other side only.
160
+ * - Top and bottom: a float as wide as the paragraph, the picture in it at its position.
161
+ * - Behind and in front of text: absolutely positioned on the page (z-index -1 or 1; the page is
162
+ * the containing block and its own stacking context).
163
+ * shortcut: a wrapping picture placed against the page or its margins vertically is drawn at
164
+ * its paragraph's top; horizontal positions are against the paragraph's box (its indents in);
165
+ * all against `geometry` (one section's page), not each page's. A float's top is never above an
166
+ * earlier float's (CSS), and `clear` stacks it below earlier floats on its side: several floats
167
+ * in a paragraph, or one above a float of an earlier paragraph, add their offsets down and do
168
+ * not sit side by side.
169
+ */
170
+ export function floatElements(attrs, doc, image, geometry) {
171
+ const float = attrs.float;
172
+ const width = Number(attrs.width) / EMU_PER_PX;
173
+ const height = Number(attrs.height) / EMU_PER_PX;
174
+ const distance = (side) => (float.distance?.[side] ?? 0) / EMU_PER_PX;
175
+ const picture = pictureElement(attrs, doc, image);
176
+ picture.style.display = "block";
177
+ const holder = doc.createElement("span");
178
+ holder.setAttribute(FLOAT_ATTR, float.wrap);
179
+ holder.append(picture);
180
+ const style = holder.style;
181
+ style.display = "block";
182
+ const x = floatLeft(float.horizontal, width, geometry);
183
+ const top = floatTop(float.vertical, height, geometry);
184
+ if (float.wrap === "behind" || float.wrap === "inFront") {
185
+ style.position = "absolute";
186
+ style.zIndex = float.wrap === "behind" ? "-1" : "1";
187
+ style.left = `${geometry.marginLeft + x}px`;
188
+ // Against the paragraph: where it would be (its static position), moved by its offset.
189
+ if (top.page !== undefined)
190
+ style.top = `${top.page}px`;
191
+ else
192
+ style.marginTop = `${top.paragraph}px`;
193
+ return { nodes: [holder], holder };
194
+ }
195
+ // Its distance from the text above and below as its margins: lines there go around it too.
196
+ const above = distance("top");
197
+ const down = (top.paragraph ?? 0) - above;
198
+ const spacer = doc.createElement("span");
199
+ spacer.setAttribute("aria-hidden", "true");
200
+ spacer.style.width = "0";
201
+ spacer.style.height = `${Math.max(0, down)}px`;
202
+ style.marginTop = `${above + Math.min(0, down)}px`;
203
+ style.marginBottom = `${distance("bottom")}px`;
204
+ if (float.wrap === "topAndBottom") {
205
+ spacer.style.float = "left";
206
+ style.float = "left";
207
+ style.clear = "both";
208
+ style.width = "100%";
209
+ picture.style.marginLeft = `${x}px`;
210
+ return { nodes: [spacer, holder], holder };
211
+ }
212
+ // Text on the side with more room (or the side `side` names): the picture floats on the other.
213
+ const right = float.side === "left" || (float.side !== "right" && x + width / 2 > geometry.textWidth / 2);
214
+ const side = right ? "right" : "left";
215
+ spacer.style.float = side;
216
+ style.float = side;
217
+ style.clear = side;
218
+ if (right) {
219
+ style.marginRight = `${geometry.textWidth - x - width}px`;
220
+ style.marginLeft = `${distance("left")}px`;
221
+ }
222
+ else {
223
+ style.marginLeft = `${x}px`;
224
+ style.marginRight = `${distance("right")}px`;
225
+ }
226
+ return { nodes: [spacer, holder], holder };
227
+ }
12
228
  /** Colors for the authors of changes (contrast 4.5:1 or more on white), picked by name. */
13
229
  const AUTHOR_COLORS = [
14
230
  "#B5082E",
@@ -49,6 +265,41 @@ export function changeElement(doc, inserted, author, date, review) {
49
265
  }
50
266
  return element;
51
267
  }
268
+ /** On the element showing a note reference's number: the note's story. */
269
+ export const NOTE_REF_ATTR = "data-foli-note-ref";
270
+ /** On a number drawn for a note, at its reference or its mark: not text of the document. */
271
+ export const NOTE_NUMBER_ATTR = "data-foli-note-number";
272
+ /** Word's footnote separator is two inches long; its continuation line here is the same. */
273
+ const SEPARATOR_WIDTH = 192;
274
+ /** The line a separator run draws, when `xml` is one (`w:separator`, `w:continuationSeparator`). */
275
+ export function separatorElement(xml, doc) {
276
+ if (!xml)
277
+ return null;
278
+ const found = [xml, ...xml.getElementsByTagName("*")].some((e) => e.localName === "separator" || e.localName === "continuationSeparator");
279
+ if (!found)
280
+ return null;
281
+ const line = doc.createElement("span");
282
+ line.dataset.foliSeparator = "";
283
+ const { style } = line;
284
+ style.display = "inline-block";
285
+ style.width = `${SEPARATOR_WIDTH}px`;
286
+ style.maxWidth = "100%";
287
+ style.height = "0";
288
+ style.borderTop = "1px solid #000";
289
+ style.verticalAlign = "middle";
290
+ return line;
291
+ }
292
+ /** The source for a document's pictures: the app's URL, else the resource's own. */
293
+ export function imageSource(resources, resolve) {
294
+ return (key) => {
295
+ const resource = resources && Object.hasOwn(resources, key) ? resources[key] : undefined;
296
+ if (!resource)
297
+ return undefined;
298
+ const url = resolve?.(key, resource);
299
+ // The app's answer stands, a refusal (null, "") included.
300
+ return url === undefined ? ownImageUrl(resource) : url || undefined;
301
+ };
302
+ }
52
303
  /**
53
304
  * Metric-compatible open fonts for Word's common fonts: the same advance widths and line
54
305
  * heights, so text breaks into the same lines where the original is not installed.
@@ -277,6 +528,7 @@ export function parseOpaque(xml, doc) {
277
528
  */
278
529
  export function renderBlocks(document, doc, options = {}) {
279
530
  const review = options.review ?? "markup";
531
+ const codes = options.fieldCodes === true;
280
532
  const ratios = new Map();
281
533
  const ratio = (family) => {
282
534
  let value = ratios.get(family);
@@ -286,7 +538,10 @@ export function renderBlocks(document, doc, options = {}) {
286
538
  }
287
539
  return value;
288
540
  };
289
- const resolver = new Resolver(document);
541
+ const resolver = options.resolver ?? new Resolver(document);
542
+ const image = imageSource(document.resources, options.resource);
543
+ // shortcut: floating pictures are placed against the last section's page.
544
+ const geometry = floatGeometry(document.section);
290
545
  const content = document.content.content ?? [];
291
546
  const attrsOf = (node) => (node.attrs ?? {});
292
547
  // In the final and simple views a paragraph whose mark was deleted joins the next paragraph
@@ -302,32 +557,35 @@ export function renderBlocks(document, doc, options = {}) {
302
557
  // A joined paragraph is numbered once, with the first paragraph's marker.
303
558
  const markers = resolver.markers(content.map((node, index) => node.type === "paragraph" && !joins(index - 1) ? attrsOf(node) : { numbering: { id: 0 } }));
304
559
  const blocks = [];
560
+ const displays = fieldDisplay(content.map(inlineTypes), codes);
305
561
  let carried = null;
306
562
  /** Comment ranges open at this point of the document. */
307
563
  const comments = new Set();
308
564
  content.forEach((node, index) => {
309
565
  if (node.type !== "paragraph") {
310
- blocks.push(opaqueBlock(node, index, resolver, doc, ratio));
566
+ blocks.push(opaqueBlock(node, index, resolver, doc, ratio, image, geometry, codes, options.notes));
311
567
  return;
312
568
  }
313
569
  const attrs = attrsOf(node);
570
+ const own = displays[index];
314
571
  if (joins(index)) {
315
- const previous = carried ?? {
316
- nodes: [],
317
- inline: [],
318
- };
572
+ const previous = carried ?? { nodes: [], inline: [], display: NO_DISPLAY };
319
573
  carried = {
320
574
  nodes: [...previous.nodes, index],
321
575
  inline: [...previous.inline, ...(node.content ?? [])],
576
+ display: joinDisplays(previous.display, previous.inline.length, own),
322
577
  };
323
578
  return;
324
579
  }
325
- const merged = carried ?? { nodes: [], inline: [] };
580
+ const merged = carried ?? { nodes: [], inline: [], display: NO_DISPLAY };
326
581
  carried = null;
582
+ const display = joinDisplays(merged.display, merged.inline.length, own);
327
583
  const { paragraph, run } = resolver.paragraph(attrs);
328
584
  const element = doc.createElement(tagOf(paragraph));
329
585
  styleParagraph(element, paragraph);
330
- styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
586
+ // The line's own height is the paragraph mark's (Word has none but its runs' and the mark's).
587
+ const mark = resolver.run(run, (attrs.markFormat ?? []));
588
+ styleRun(element, mark, lineHeight(paragraph, mark, ratio(fontStack(latin(mark)))));
331
589
  const marker = markers[index];
332
590
  const firstMerged = merged.nodes[0];
333
591
  const shownMarker = firstMerged !== undefined ? (markers[firstMerged] ?? null) : marker;
@@ -340,7 +598,17 @@ export function renderBlocks(document, doc, options = {}) {
340
598
  review,
341
599
  comments,
342
600
  ratio,
601
+ image,
602
+ geometry,
603
+ codes,
604
+ display,
605
+ notes: options.notes,
343
606
  });
607
+ if (display.gone)
608
+ element.style.display = "none";
609
+ if (onlyPictures(inline, (node) => node.type, (node) => !!node.attrs?.float))
610
+ for (const picture of element.querySelectorAll(`[${PICTURE_ATTR}]`))
611
+ picture.style.verticalAlign = "bottom";
344
612
  // An empty paragraph, or one ending in a line break, shows its last (empty) line; after a
345
613
  // page break the paragraph mark stays on the break's line, as in Word.
346
614
  const last = element.lastChild;
@@ -356,8 +624,8 @@ export function renderBlocks(document, doc, options = {}) {
356
624
  blocks.push({
357
625
  element,
358
626
  nodes: [...merged.nodes, index],
359
- before: pt(spaceBefore),
360
- after: pt(spaceAfter),
627
+ before: display.gone ? 0 : pt(spaceBefore),
628
+ after: display.gone ? 0 : pt(spaceAfter),
361
629
  keepNext: paragraph.keepNext,
362
630
  keepLines: paragraph.keepLines,
363
631
  pageBreakBefore: paragraph.pageBreakBefore,
@@ -367,26 +635,86 @@ export function renderBlocks(document, doc, options = {}) {
367
635
  if (paragraph.contextualSpacing)
368
636
  element.dataset.contextual = "";
369
637
  });
370
- applyContextualSpacing(blocks);
638
+ applyContextualSpacing(blocks, resolver.addsParagraphSpacing);
371
639
  return blocks;
372
640
  }
641
+ const NO_DISPLAY = fieldDisplay([[]], false)[0];
642
+ const inlineTypes = (node) => node.type === "paragraph" ? (node.content ?? []).map((child) => child.type) : [];
643
+ /** `after`, whose nodes follow `length` others, added to `before` (paragraphs drawn as one). */
644
+ function joinDisplays(before, length, after) {
645
+ if (!length)
646
+ return after;
647
+ return {
648
+ hidden: new Set([...before.hidden, ...[...after.hidden].map((i) => i + length)]),
649
+ braces: new Map([
650
+ ...before.braces,
651
+ ...[...after.braces].map(([i, b]) => [i + length, b]),
652
+ ]),
653
+ gone: before.gone && after.gone,
654
+ };
655
+ }
656
+ /**
657
+ * Whether a paragraph's line holds nothing but inline pictures: Word's line then ends at the
658
+ * picture's foot (its PDFs of the corpus: no room below it for the text it does not have).
659
+ */
660
+ export function onlyPictures(inline, type, floats) {
661
+ let found = false;
662
+ for (const node of inline) {
663
+ const name = type(node);
664
+ if (name === "picture")
665
+ found ||= !floats(node);
666
+ else if (!INVISIBLE.has(name))
667
+ return false;
668
+ }
669
+ return found;
670
+ }
671
+ const INVISIBLE = new Set([
672
+ "bookmarkStart",
673
+ "bookmarkEnd",
674
+ "commentStart",
675
+ "commentEnd",
676
+ "commentReference",
677
+ "controlStart",
678
+ "controlEnd",
679
+ "fieldStart",
680
+ "fieldCode",
681
+ "fieldSeparator",
682
+ "fieldEnd",
683
+ ]);
684
+ /**
685
+ * The top margin of a paragraph after another (whose space after is `above`) in a box the page
686
+ * flow does not lay out (a table cell). Adjacent margins collapse to the larger: Word's rule. In
687
+ * a document where the two spaces add up this margin holds both, so the collapse gives the sum
688
+ * and no paragraph's shading or border grows.
689
+ */
690
+ export function marginAbove(before, above, resolver) {
691
+ return resolver.addsParagraphSpacing ? before + above : before;
692
+ }
373
693
  /** A paragraph's element: a heading of its outline level (1-6), else a paragraph. */
374
694
  export function tagOf(paragraph) {
375
695
  const level = paragraph.outlineLevel;
376
696
  return level !== null && level >= 0 && level < 6 ? `h${level + 1}` : "p";
377
697
  }
378
- /** Word ignores the space between paragraphs of the same style that ask for it. */
379
- function applyContextualSpacing(blocks) {
698
+ /**
699
+ * Word ignores the space between paragraphs of the same style that ask for it. When only the
700
+ * first asks, its space after still eats into the second's space before, unless the document
701
+ * adds the two (`adds`).
702
+ */
703
+ function applyContextualSpacing(blocks, adds) {
380
704
  for (let i = 1; i < blocks.length; i++) {
381
705
  const a = blocks[i - 1];
382
706
  const b = blocks[i];
383
707
  const style = a.element.dataset.style;
384
708
  if (style === undefined || style !== b.element.dataset.style)
385
709
  continue;
386
- if ("contextual" in a.element.dataset)
387
- a.after = 0;
388
- if ("contextual" in b.element.dataset)
710
+ const first = "contextual" in a.element.dataset;
711
+ const second = "contextual" in b.element.dataset;
712
+ if (second)
389
713
  b.before = 0;
714
+ else if (first && !adds)
715
+ b.before = Math.max(0, b.before - a.after);
716
+ if (first)
717
+ a.after = 0;
390
718
  }
391
719
  }
392
720
  /** Symbol and Wingdings bullets (`w:lvlText`, private-use code points) as Unicode. */
@@ -433,8 +761,11 @@ export function markerElement(marker, paragraph, doc, ratio) {
433
761
  }
434
762
  /** A paragraph's inline content: runs as spans, breaks, comment anchors, opaque inline content. */
435
763
  function renderInline(parent, inline, paragraphRun, paragraph, context) {
436
- const { resolver, doc, review, comments, ratio } = context;
437
- for (const node of inline) {
764
+ const { resolver, doc, review, comments, ratio, image, codes, display } = context;
765
+ const floats = [];
766
+ for (const [index, node] of inline.entries()) {
767
+ if (display.hidden.has(index))
768
+ continue;
438
769
  const marks = (node.marks ?? []);
439
770
  const inserted = marks.some((m) => m.type === "insertion");
440
771
  const deleted = marks.some((m) => m.type === "deletion");
@@ -454,14 +785,33 @@ function renderInline(parent, inline, paragraphRun, paragraph, context) {
454
785
  parent.append(anchor);
455
786
  continue;
456
787
  }
457
- case "bookmarkStart":
788
+ case "bookmarkStart": {
789
+ // Where a link to it goes (`@folijs/pdf`); out of the flow, so no line changes.
790
+ const mark = doc.createElement("span");
791
+ mark.dataset.foliBookmark = String(attrs.name ?? "");
792
+ mark.style.position = "absolute";
793
+ parent.append(mark);
794
+ continue;
795
+ }
458
796
  case "bookmarkEnd":
797
+ case "controlStart":
798
+ case "controlEnd":
799
+ continue;
800
+ case "picture":
801
+ if (attrs.float)
802
+ floats.push(...floatElements(attrs, doc, image, context.geometry).nodes);
803
+ else
804
+ parent.append(pictureElement(attrs, doc, image));
459
805
  continue;
460
806
  case "hardBreak":
461
- case "columnBreak":
462
- // shortcut: a column break ends the line; Foli lays out one column.
463
807
  parent.append(doc.createElement("br"));
464
808
  continue;
809
+ case "columnBreak": {
810
+ const br = doc.createElement("br");
811
+ br.setAttribute(WORD_COLUMN_BREAK_ATTR, "");
812
+ parent.append(br);
813
+ continue;
814
+ }
465
815
  case "pageBreak": {
466
816
  const br = doc.createElement("br");
467
817
  br.setAttribute(WORD_PAGE_BREAK_ATTR, "");
@@ -470,13 +820,25 @@ function renderInline(parent, inline, paragraphRun, paragraph, context) {
470
820
  }
471
821
  default:
472
822
  }
823
+ const code = display.braces.get(index) ?? (codes && node.type === "fieldCode" ? String(attrs.text) : "");
473
824
  let text;
474
- if (node.type === "text")
825
+ if (code)
826
+ text = code;
827
+ else if (node.type === "text")
475
828
  text = node.text ?? "";
476
829
  else if (node.type === "tab")
477
830
  text = "\t";
831
+ else if (node.type === "noteReference")
832
+ text = context.notes?.references?.get(String(attrs.story)) ?? "";
833
+ else if (node.type === "noteMark")
834
+ text = context.notes?.mark ?? "";
478
835
  else if (node.type === "opaqueInline") {
479
836
  const xml = parseOpaque(String(attrs.xml ?? ""), doc);
837
+ const separator = separatorElement(xml, doc);
838
+ if (separator) {
839
+ parent.append(separator);
840
+ continue;
841
+ }
480
842
  // A run's content (a drawing, a field character) shows as nothing; a content control or
481
843
  // simple field as its text.
482
844
  text = xml ? opaqueText(xml) : "";
@@ -493,6 +855,10 @@ function renderInline(parent, inline, paragraphRun, paragraph, context) {
493
855
  let element = doc.createElement("span");
494
856
  styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
495
857
  element.textContent = text;
858
+ if (node.type === "noteReference")
859
+ element.setAttribute(NOTE_REF_ATTR, String(attrs.story));
860
+ if (node.type === "noteReference" || node.type === "noteMark")
861
+ element.setAttribute(NOTE_NUMBER_ATTR, "");
496
862
  const link = marks.find((m) => m.type === "link");
497
863
  if (link)
498
864
  element.dataset.href = String(link.attrs?.href ?? `#${String(link.attrs?.anchor)}`);
@@ -512,30 +878,38 @@ function renderInline(parent, inline, paragraphRun, paragraph, context) {
512
878
  }
513
879
  parent.append(element);
514
880
  }
881
+ // Floating pictures first in the paragraph, in order: lines from its top go around them.
882
+ parent.prepend(...floats);
515
883
  }
516
884
  /**
517
885
  * A block the model keeps opaque (tables until Phase 10, block content controls), shown from
518
886
  * its XML: a table as a table of its cells' paragraphs, anything else as its paragraphs. Only
519
887
  * text is read: no formatting beyond the paragraph styles.
520
888
  */
521
- export function opaqueBlock(node, index, resolver, doc, ratio) {
889
+ export function opaqueBlock(node, index, resolver, doc, ratio, image,
890
+ /** The page floating pictures in its cells are placed against. */
891
+ geometry = floatGeometry(undefined), codes = false, notes) {
522
892
  const attrs = (node.attrs ?? {});
523
893
  const element = doc.createElement("div");
524
894
  element.dataset.foliOpaque = String(attrs.label ?? "");
525
895
  element.style.margin = "0";
526
896
  element.style.display = "flow-root";
527
- const xml = parseOpaque(String(attrs.xml ?? ""), doc);
897
+ const xml = node.type === "table" ? null : parseOpaque(String(attrs.xml ?? ""), doc);
528
898
  let after = 0;
529
- if (xml?.localName === "tbl")
899
+ if (node.type === "table")
900
+ element.append(modelTable(node, resolver, doc, ratio, image, geometry, codes, notes));
901
+ else if (xml?.localName === "tbl")
530
902
  element.append(opaqueTable(xml, resolver, doc, ratio));
531
903
  else if (xml) {
532
904
  const paragraphs = outermost(xml, PARAGRAPHS);
905
+ let above = 0;
533
906
  paragraphs.forEach((p, i) => {
534
- const rendered = opaqueParagraph(p, resolver, doc, ratio);
907
+ const rendered = opaqueParagraph(p, resolver, doc, ratio, above);
535
908
  if (i < paragraphs.length - 1)
536
909
  rendered.element.style.marginBottom = `${rendered.after}px`;
537
910
  else
538
911
  after = rendered.after;
912
+ above = rendered.after;
539
913
  element.append(rendered.element);
540
914
  });
541
915
  }
@@ -573,7 +947,9 @@ function child(element, name) {
573
947
  return undefined;
574
948
  }
575
949
  /** A paragraph of opaque XML: its style's formatting and its text. */
576
- function opaqueParagraph(p, resolver, doc, ratio) {
950
+ function opaqueParagraph(p, resolver, doc, ratio,
951
+ /** The space after the paragraph before it in its box. */
952
+ above = 0) {
577
953
  const pPr = child(p, "pPr");
578
954
  const style = childValue(pPr, "pStyle");
579
955
  const justification = childValue(pPr, "jc");
@@ -595,8 +971,9 @@ function opaqueParagraph(p, resolver, doc, ratio) {
595
971
  }
596
972
  if (!element.textContent)
597
973
  element.append(doc.createElement("br"));
598
- if (paragraph.spacing.before)
599
- element.style.marginTop = `${paragraph.spacing.before * PX_PER_TWIP}px`;
974
+ const top = marginAbove(paragraph.spacing.before * PX_PER_TWIP, above, resolver);
975
+ if (top)
976
+ element.style.marginTop = `${top}px`;
600
977
  return { element, after: paragraph.spacing.after * PX_PER_TWIP };
601
978
  }
602
979
  /** The run properties of verbatim XML Foli reads for showing it (`w:rPr`) as marks. */
@@ -730,14 +1107,17 @@ function opaqueTable(tbl, resolver, doc, ratio) {
730
1107
  row.append(cell);
731
1108
  continue;
732
1109
  }
1110
+ let above = 0;
733
1111
  for (const p of outermost(tc, CELL_CONTENT)) {
734
1112
  if (p.localName === "tbl") {
735
1113
  cell.append(opaqueTable(p, resolver, doc, ratio));
1114
+ above = 0;
736
1115
  continue;
737
1116
  }
738
1117
  // Word counts the space after a cell's last paragraph in the row's height too.
739
- const rendered = opaqueParagraph(p, resolver, doc, ratio);
1118
+ const rendered = opaqueParagraph(p, resolver, doc, ratio, above);
740
1119
  rendered.element.style.marginBottom = `${rendered.after}px`;
1120
+ above = rendered.after;
741
1121
  cell.append(rendered.element);
742
1122
  }
743
1123
  row.append(cell);
@@ -747,6 +1127,130 @@ function opaqueTable(tbl, resolver, doc, ratio) {
747
1127
  table.append(body);
748
1128
  return table;
749
1129
  }
1130
+ /** A border of the model (`BorderJSON`) as CSS; undefined when it says none. */
1131
+ export function borderJsonCss(border) {
1132
+ if (!border)
1133
+ return undefined;
1134
+ if (border.style === "nil" || border.style === "none")
1135
+ return "none";
1136
+ const width = Math.max(((border.size ?? 4) / 8) * (96 / 72), 0.5);
1137
+ const color = border.color && border.color !== "auto" ? `#${border.color}` : "#000";
1138
+ return `${width}px ${BORDER_STYLES[border.style ?? "single"] ?? "solid"} ${color}`;
1139
+ }
1140
+ /**
1141
+ * A table of the model (schema v4), read-only, as opaque tables are shown: rows, cells with
1142
+ * their table style's formatting (`Resolver.cell`), their paragraphs and nested tables.
1143
+ *
1144
+ * shortcut: `renderDocument`'s tables (the editing view draws its own, `table.ts`): one block,
1145
+ * split across pages as clips; a cell merged into the one above is shown empty, as opaque
1146
+ * tables are.
1147
+ */
1148
+ function modelTable(node, resolver, doc, ratio, image, geometry, codes, notes) {
1149
+ const attrs = (node.attrs ?? {});
1150
+ const table = doc.createElement("table");
1151
+ table.style.borderCollapse = "collapse";
1152
+ table.style.tableLayout = "fixed";
1153
+ const grid = attrs.grid ?? [];
1154
+ const total = grid.reduce((a, b) => a + b, 0);
1155
+ if (total)
1156
+ table.style.width = `${total * PX_PER_TWIP}px`;
1157
+ const colgroup = doc.createElement("colgroup");
1158
+ for (const width of grid) {
1159
+ const col = doc.createElement("col");
1160
+ col.style.width = `${width * PX_PER_TWIP}px`;
1161
+ colgroup.append(col);
1162
+ }
1163
+ table.append(colgroup);
1164
+ const body = doc.createElement("tbody");
1165
+ const rows = node.content ?? [];
1166
+ const context = {
1167
+ resolver,
1168
+ doc,
1169
+ review: "markup",
1170
+ comments: new Set(),
1171
+ ratio,
1172
+ image,
1173
+ // shortcut: a floating picture in a cell is placed against the page, not its cell.
1174
+ geometry,
1175
+ codes,
1176
+ };
1177
+ rows.forEach((rowNode, r) => {
1178
+ const rowAttrs = (rowNode.attrs ?? {});
1179
+ const row = doc.createElement("tr");
1180
+ if (rowAttrs.header)
1181
+ row.dataset.foliHeader = "";
1182
+ if (rowAttrs.cantSplit)
1183
+ row.dataset.foliCantSplit = "";
1184
+ const cells = rowNode.content ?? [];
1185
+ cells.forEach((cellNode, c) => {
1186
+ const cellAttrs = (cellNode.attrs ?? {});
1187
+ const format = resolver.cell(attrs, rowAttrs, cellAttrs, {
1188
+ row: r,
1189
+ rows: rows.length,
1190
+ cell: c,
1191
+ cells: cells.length,
1192
+ });
1193
+ const cell = doc.createElement("td");
1194
+ const span = cellAttrs.gridSpan;
1195
+ if (span && span > 1)
1196
+ cell.colSpan = span;
1197
+ if (format.shading)
1198
+ cell.style.backgroundColor = `#${format.shading}`;
1199
+ const m = format.margins;
1200
+ cell.style.padding = `${m.top * PX_PER_TWIP}px ${m.right * PX_PER_TWIP}px ${m.bottom * PX_PER_TWIP}px ${m.left * PX_PER_TWIP}px`;
1201
+ cell.style.verticalAlign =
1202
+ format.verticalAlign === "center" ? "middle" : format.verticalAlign;
1203
+ for (const side of ["top", "left", "bottom", "right"]) {
1204
+ const css = borderJsonCss(format.borders[side]);
1205
+ if (css)
1206
+ cell.style.setProperty(`border-${side}`, css);
1207
+ }
1208
+ row.append(cell);
1209
+ if (cellAttrs.vMerge === "continue")
1210
+ return;
1211
+ let above = 0;
1212
+ const blocks = cellNode.content ?? [];
1213
+ const displays = fieldDisplay(blocks.map(inlineTypes), codes);
1214
+ for (const [b, block] of blocks.entries()) {
1215
+ if (block.type === "table") {
1216
+ cell.append(modelTable(block, resolver, doc, ratio, image, geometry, codes, notes));
1217
+ above = 0;
1218
+ continue;
1219
+ }
1220
+ if (block.type !== "paragraph") {
1221
+ cell.append(opaqueBlock(block, 0, resolver, doc, ratio, image, geometry, codes, notes).element);
1222
+ above = 0;
1223
+ continue;
1224
+ }
1225
+ const { paragraph, run } = resolver.paragraph(block.attrs ?? {}, format);
1226
+ const element = doc.createElement(tagOf(paragraph));
1227
+ // A cell's paragraph: where it is on pages is measured too (`cellParagraphs`).
1228
+ element.dataset.foliCell = "";
1229
+ styleParagraph(element, paragraph);
1230
+ styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
1231
+ const display = displays[b];
1232
+ renderInline(element, block.content ?? [], run, paragraph, {
1233
+ ...context,
1234
+ display,
1235
+ notes,
1236
+ });
1237
+ if (display.gone)
1238
+ element.style.display = "none";
1239
+ if (!element.textContent)
1240
+ element.append(doc.createElement("br"));
1241
+ const before = paragraph.spacing.before * PX_PER_TWIP;
1242
+ element.style.marginTop = `${marginAbove(before, above, resolver)}px`;
1243
+ // Word counts the space after a cell's last paragraph in the row's height too.
1244
+ above = paragraph.spacing.after * PX_PER_TWIP;
1245
+ element.style.marginBottom = `${above}px`;
1246
+ cell.append(element);
1247
+ }
1248
+ });
1249
+ body.append(row);
1250
+ });
1251
+ table.append(body);
1252
+ return table;
1253
+ }
750
1254
  function childValueOf(element, attribute) {
751
1255
  for (const a of element.attributes)
752
1256
  if (a.localName === attribute)