@folijs/view 0.5.0 → 1.0.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 (82) hide show
  1. package/CHANGELOG.md +194 -0
  2. package/README.md +1 -1
  3. package/dist/clipboard.d.ts +1 -49
  4. package/dist/clipboard.d.ts.map +1 -1
  5. package/dist/clipboard.js +65 -13
  6. package/dist/clipboard.js.map +1 -1
  7. package/dist/extension.d.ts +90 -0
  8. package/dist/extension.d.ts.map +1 -0
  9. package/dist/extension.js +152 -0
  10. package/dist/extension.js.map +1 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/layout/flow.d.ts +1 -109
  15. package/dist/layout/flow.d.ts.map +1 -1
  16. package/dist/layout/flow.js +808 -103
  17. package/dist/layout/flow.js.map +1 -1
  18. package/dist/print.d.ts +6 -0
  19. package/dist/print.d.ts.map +1 -0
  20. package/dist/print.js +35 -0
  21. package/dist/print.js.map +1 -0
  22. package/dist/render.d.ts +1 -24
  23. package/dist/render.d.ts.map +1 -1
  24. package/dist/render.js +4 -1
  25. package/dist/render.js.map +1 -1
  26. package/dist/view.d.ts +244 -64
  27. package/dist/view.d.ts.map +1 -1
  28. package/dist/view.js +1945 -215
  29. package/dist/view.js.map +1 -1
  30. package/dist/word/blocks.d.ts +0 -146
  31. package/dist/word/blocks.d.ts.map +1 -1
  32. package/dist/word/blocks.js +294 -59
  33. package/dist/word/blocks.js.map +1 -1
  34. package/dist/word/columns.d.ts +2 -0
  35. package/dist/word/columns.d.ts.map +1 -0
  36. package/dist/word/columns.js +63 -0
  37. package/dist/word/columns.js.map +1 -0
  38. package/dist/word/controls.d.ts +2 -0
  39. package/dist/word/controls.d.ts.map +1 -0
  40. package/dist/word/controls.js +416 -0
  41. package/dist/word/controls.js.map +1 -0
  42. package/dist/word/edit.d.ts +1 -71
  43. package/dist/word/edit.d.ts.map +1 -1
  44. package/dist/word/edit.js +338 -29
  45. package/dist/word/edit.js.map +1 -1
  46. package/dist/word/matches.d.ts +2 -0
  47. package/dist/word/matches.d.ts.map +1 -0
  48. package/dist/word/matches.js +102 -0
  49. package/dist/word/matches.js.map +1 -0
  50. package/dist/word/notes.d.ts +2 -0
  51. package/dist/word/notes.d.ts.map +1 -0
  52. package/dist/word/notes.js +403 -0
  53. package/dist/word/notes.js.map +1 -0
  54. package/dist/word/pages.d.ts +30 -20
  55. package/dist/word/pages.d.ts.map +1 -1
  56. package/dist/word/pages.js +421 -229
  57. package/dist/word/pages.js.map +1 -1
  58. package/dist/word/regions.d.ts +2 -0
  59. package/dist/word/regions.d.ts.map +1 -0
  60. package/dist/word/regions.js +388 -0
  61. package/dist/word/regions.js.map +1 -0
  62. package/dist/word/table.d.ts +1 -78
  63. package/dist/word/table.d.ts.map +1 -1
  64. package/dist/word/table.js +13 -3
  65. package/dist/word/table.js.map +1 -1
  66. package/package.json +6 -3
  67. package/src/clipboard.ts +93 -20
  68. package/src/extension.ts +267 -0
  69. package/src/index.ts +10 -0
  70. package/src/layout/flow.ts +997 -116
  71. package/src/print.ts +55 -0
  72. package/src/render.ts +6 -1
  73. package/src/view.ts +2178 -245
  74. package/src/word/blocks.ts +339 -62
  75. package/src/word/columns.ts +81 -0
  76. package/src/word/controls.ts +457 -0
  77. package/src/word/edit.ts +381 -31
  78. package/src/word/matches.ts +104 -0
  79. package/src/word/notes.ts +464 -0
  80. package/src/word/pages.ts +518 -221
  81. package/src/word/regions.ts +488 -0
  82. package/src/word/table.ts +33 -8
@@ -5,37 +5,64 @@
5
5
  * createElement/textContent only (never innerHTML); the page layout is in `pages.ts`.
6
6
  */
7
7
  import {
8
+ type FieldDisplay,
8
9
  type FoliDocument,
9
- type ListMarker,
10
+ fieldDisplay,
10
11
  type MarkJSON,
11
12
  type NodeJSON,
12
- type ParagraphFormat,
13
- Resolver,
14
13
  type ResourceJSON,
15
- type RunFormat,
16
14
  type SectionJSON,
17
15
  } from "@folijs/core";
16
+ import {
17
+ CUSTOM_TYPE,
18
+ foreignTextOf,
19
+ type ListMarker,
20
+ type ParagraphFormat,
21
+ Resolver,
22
+ type RunFormat,
23
+ } from "@folijs/core/internal";
18
24
 
19
- /** Marks the <br> of an explicit page break (the page flow ends the page after its line). */
25
+ /**
26
+ * Marks the <br> of an explicit page break (the page flow ends the page after its line).
27
+ * @internal
28
+ */
20
29
  export const WORD_PAGE_BREAK_ATTR = "data-page-break";
30
+ /**
31
+ * Marks the <br> of an explicit column break (the flow ends the column after its line).
32
+ * @internal
33
+ */
34
+ export const WORD_COLUMN_BREAK_ATTR = "data-column-break";
21
35
 
22
- /** CSS px per twip (1/1440 inch; CSS: 96 px per inch). */
36
+ /**
37
+ * CSS px per twip (1/1440 inch; CSS: 96 px per inch).
38
+ * @internal
39
+ */
23
40
  export const PX_PER_TWIP = 96 / 1440;
24
41
  /** EMU (DrawingML's unit: 914 400 per inch) per CSS px. */
25
42
  export const EMU_PER_PX = 914_400 / 96;
26
43
 
27
- /** The URL to show a picture's image from (its resource key), if one is known. */
44
+ /**
45
+ * The URL to show a picture's image from (its resource key), if one is known.
46
+ * @internal
47
+ */
28
48
  export type ImageSource = (key: string) => string | undefined;
29
49
 
30
- /** Marks a picture's element (its resource key). */
50
+ /**
51
+ * Marks a picture's element (its resource key).
52
+ * @internal
53
+ */
31
54
  export const PICTURE_ATTR = "data-foli-picture";
32
55
 
33
- /** The accessible name of a picture with no alt text that is not decorative. */
56
+ /**
57
+ * The accessible name of a picture with no alt text that is not decorative.
58
+ * @internal
59
+ */
34
60
  export const NO_ALT_LABEL = "Picture without alt text";
35
61
 
36
62
  /**
37
63
  * The URL a resource gives on its own: an image `data:` URL, or a web or `blob:` URL; none for
38
64
  * an image in a package part (the app's resolver gives one) or anything else.
65
+ * @internal
39
66
  */
40
67
  export function ownImageUrl(resource: ResourceJSON | undefined): string | undefined {
41
68
  const data = resource?.data;
@@ -48,6 +75,7 @@ export function ownImageUrl(resource: ResourceJSON | undefined): string | undefi
48
75
  * A picture as shown: its image at its size, or, when no URL is known for it, a box of that size
49
76
  * with its alt text. A picture with no alt text that is not decorative is marked (`data-foli-
50
77
  * no-alt`); a decorative one has an empty alt.
78
+ * @internal
51
79
  */
52
80
  export function pictureElement(
53
81
  attrs: Record<string, unknown>,
@@ -93,10 +121,16 @@ export function pictureElement(
93
121
  return element;
94
122
  }
95
123
 
96
- /** Marks the element holding a floating picture (its wrapping), drawn at its paragraph's start. */
124
+ /**
125
+ * Marks the element holding a floating picture (its wrapping), drawn at its paragraph's start.
126
+ * @internal
127
+ */
97
128
  export const FLOAT_ATTR = "data-foli-float";
98
129
 
99
- /** A section's page, in CSS px: what a floating picture is positioned against. */
130
+ /**
131
+ * A section's page, in CSS px: what a floating picture is positioned against.
132
+ * @internal
133
+ */
100
134
  export interface FloatGeometry {
101
135
  readonly pageWidth: number;
102
136
  readonly pageHeight: number;
@@ -106,7 +140,10 @@ export interface FloatGeometry {
106
140
  readonly textHeight: number;
107
141
  }
108
142
 
109
- /** The page geometry of `section` (Word's Letter page and margins where it does not say). */
143
+ /**
144
+ * The page geometry of `section` (Word's Letter page and margins where it does not say).
145
+ * @internal
146
+ */
110
147
  export function floatGeometry(section: SectionJSON | undefined): FloatGeometry {
111
148
  const m = section?.margins ?? {};
112
149
  const width = section?.pageSize?.width ?? 12_240;
@@ -202,6 +239,7 @@ function floatTop(
202
239
  * earlier float's (CSS), and `clear` stacks it below earlier floats on its side: several floats
203
240
  * in a paragraph, or one above a float of an earlier paragraph, add their offsets down and do
204
241
  * not sit side by side.
242
+ * @internal
205
243
  */
206
244
  export function floatElements(
207
245
  attrs: Record<string, unknown>,
@@ -290,20 +328,27 @@ const AUTHOR_COLORS = [
290
328
  "#5D4037",
291
329
  ];
292
330
 
293
- /** The color of `author`'s changes: always the same for a name. */
331
+ /**
332
+ * The color of `author`'s changes: always the same for a name.
333
+ * @internal
334
+ */
294
335
  export function authorColor(author: string): string {
295
336
  let hash = 0;
296
337
  for (const c of author) hash = (hash * 31 + (c.codePointAt(0) ?? 0)) >>> 0;
297
338
  return AUTHOR_COLORS[hash % AUTHOR_COLORS.length] as string;
298
339
  }
299
340
 
300
- /** The bar beside a paragraph with changes (`markup` and `simple`), drawn in the margin. */
341
+ /**
342
+ * The bar beside a paragraph with changes (`markup` and `simple`), drawn in the margin.
343
+ * @internal
344
+ */
301
345
  export const CHANGE_BAR = "-4px 0 0 0 #6B6B6B";
302
346
 
303
347
  /**
304
348
  * The element around an inserted or deleted run: `ins` or `del` (named for screen readers by
305
349
  * its title), styled for `review`. Deleted text not shown is hidden, not left out: the editable
306
350
  * view maps positions through it.
351
+ * @internal
307
352
  */
308
353
  export function changeElement(
309
354
  doc: Document,
@@ -325,9 +370,12 @@ export function changeElement(
325
370
  return element;
326
371
  }
327
372
 
373
+ /** @internal */
328
374
  export interface BlockOptions {
329
375
  /** `markup` (the default): insertions underlined, deletions struck through; `simple`, `final`: as if accepted. */
330
376
  review?: ReviewView;
377
+ /** Fields show their codes instead of their results (Word's Alt+F9). */
378
+ fieldCodes?: boolean;
331
379
  /**
332
380
  * The ratio of a font's normal line height to its size (`fontFamily`: a CSS font-family
333
381
  * list). Word's single line spacing is the font's own line height; multiples scale it.
@@ -340,15 +388,58 @@ export interface BlockOptions {
340
388
  * resource's own image `data:` URL or web URL (fetched as it is shown).
341
389
  */
342
390
  resource?: (key: string, resource: ResourceJSON) => string | null | undefined;
391
+ /** The document's resolver, when the caller has one (a story of it, drawn per page). */
392
+ resolver?: Resolver;
393
+ /** What note references show, by story, and what a note's own mark shows (never stored). */
394
+ notes?: { references?: ReadonlyMap<string, string>; mark?: string };
395
+ }
396
+
397
+ /**
398
+ * On the element showing a note reference's number: the note's story.
399
+ * @internal
400
+ */
401
+ export const NOTE_REF_ATTR = "data-foli-note-ref";
402
+ /**
403
+ * On a number drawn for a note, at its reference or its mark: not text of the document.
404
+ * @internal
405
+ */
406
+ export const NOTE_NUMBER_ATTR = "data-foli-note-number";
407
+
408
+ /** Word's footnote separator is two inches long; its continuation line here is the same. */
409
+ const SEPARATOR_WIDTH = 192;
410
+
411
+ /**
412
+ * The line a separator run draws, when `xml` is one (`w:separator`, `w:continuationSeparator`).
413
+ * @internal
414
+ */
415
+ export function separatorElement(xml: Element | null, doc: Document): HTMLElement | null {
416
+ if (!xml) return null;
417
+ const found = [xml, ...xml.getElementsByTagName("*")].some(
418
+ (e) => e.localName === "separator" || e.localName === "continuationSeparator",
419
+ );
420
+ if (!found) return null;
421
+ const line = doc.createElement("span");
422
+ line.dataset.foliSeparator = "";
423
+ const { style } = line;
424
+ style.display = "inline-block";
425
+ style.width = `${SEPARATOR_WIDTH}px`;
426
+ style.maxWidth = "100%";
427
+ style.height = "0";
428
+ style.borderTop = "1px solid #000";
429
+ style.verticalAlign = "middle";
430
+ return line;
343
431
  }
344
432
 
345
- /** The source for a document's pictures: the app's URL, else the resource's own. */
433
+ /**
434
+ * The source for a document's pictures: the app's URL, else the resource's own.
435
+ * @internal
436
+ */
346
437
  export function imageSource(
347
438
  resources: Readonly<Record<string, ResourceJSON>> | undefined,
348
439
  resolve?: (key: string, resource: ResourceJSON) => string | null | undefined,
349
440
  ): ImageSource {
350
441
  return (key) => {
351
- const resource = resources?.[key];
442
+ const resource = resources && Object.hasOwn(resources, key) ? resources[key] : undefined;
352
443
  if (!resource) return undefined;
353
444
  const url = resolve?.(key, resource);
354
445
  // The app's answer stands, a refusal (null, "") included.
@@ -356,7 +447,10 @@ export function imageSource(
356
447
  };
357
448
  }
358
449
 
359
- /** A rendered block and what the page flow needs to know about it. */
450
+ /**
451
+ * A rendered block and what the page flow needs to know about it.
452
+ * @internal
453
+ */
360
454
  export interface WordBlock {
361
455
  element: HTMLElement;
362
456
  /** Indices in the document's content of the nodes it shows (several when paragraphs merged). */
@@ -386,7 +480,10 @@ const SUBSTITUTES: Record<string, string[]> = {
386
480
  const SERIF = new Set(["cambria", "times new roman", "georgia", "garamond", "book antiqua"]);
387
481
  const MONOSPACE = new Set(["courier new", "consolas", "courier"]);
388
482
 
389
- /** A CSS font-family list for a Word font name: the font, its substitutes, a generic family. */
483
+ /**
484
+ * A CSS font-family list for a Word font name: the font, its substitutes, a generic family.
485
+ * @internal
486
+ */
390
487
  export function fontStack(name: string | null): string {
391
488
  const font = name ?? "Times New Roman";
392
489
  const key = font.toLowerCase();
@@ -447,10 +544,16 @@ const BORDER_STYLES: Record<string, string> = {
447
544
  nil: "none",
448
545
  };
449
546
 
450
- /** The one font name a run shows for Latin text. */
547
+ /**
548
+ * The one font name a run shows for Latin text.
549
+ * @internal
550
+ */
451
551
  export const latin = (run: RunFormat) => run.font.ascii ?? run.font.hAnsi;
452
552
 
453
- /** A line height in CSS for text in `run` (`ratio`: its font's normal line height ratio). */
553
+ /**
554
+ * A line height in CSS for text in `run` (`ratio`: its font's normal line height ratio).
555
+ * @internal
556
+ */
454
557
  export function lineHeight(paragraph: ParagraphFormat, run: RunFormat, ratio: number): string {
455
558
  const sizePx = (run.size / 2) * (96 / 72);
456
559
  const { line, lineRule } = paragraph.spacing;
@@ -460,7 +563,10 @@ export function lineHeight(paragraph: ParagraphFormat, run: RunFormat, ratio: nu
460
563
  return String((ratio * line) / 240);
461
564
  }
462
565
 
463
- /** Run formatting as inline CSS on `element`. */
566
+ /**
567
+ * Run formatting as inline CSS on `element`.
568
+ * @internal
569
+ */
464
570
  export function styleRun(element: HTMLElement, run: RunFormat, line: string): void {
465
571
  const { style } = element;
466
572
  style.fontFamily = fontStack(latin(run));
@@ -494,7 +600,10 @@ export function styleRun(element: HTMLElement, run: RunFormat, line: string): vo
494
600
  if (run.hidden) style.display = "none";
495
601
  }
496
602
 
497
- /** Paragraph properties as inline CSS on `element` (spacing is the flow's). */
603
+ /**
604
+ * Paragraph properties as inline CSS on `element` (spacing is the flow's).
605
+ * @internal
606
+ */
498
607
  export function styleParagraph(element: HTMLElement, paragraph: ParagraphFormat): void {
499
608
  const { style } = element;
500
609
  style.margin = "0";
@@ -528,7 +637,10 @@ export function styleParagraph(element: HTMLElement, paragraph: ParagraphFormat)
528
637
  */
529
638
  const NOT_INLINE = new Set(["txbxContent", "Fallback"]);
530
639
 
531
- /** Text a run of opaque XML shows: its `w:t` elements (field results, content controls). */
640
+ /**
641
+ * Text a run of opaque XML shows: its `w:t` elements (field results, content controls).
642
+ * @internal
643
+ */
532
644
  export function opaqueText(element: Element): string {
533
645
  let text = "";
534
646
  for (const node of element.children) {
@@ -540,7 +652,10 @@ export function opaqueText(element: Element): string {
540
652
  return text;
541
653
  }
542
654
 
543
- /** Opaque XML's text, a line per paragraph (`w:p`), or its runs' text when it has none. */
655
+ /**
656
+ * Opaque XML's text, a line per paragraph (`w:p`), or its runs' text when it has none.
657
+ * @internal
658
+ */
544
659
  export function opaqueParagraphsText(element: Element): string {
545
660
  const paragraphs = [...element.getElementsByTagName("*")].filter((e) => e.localName === "p");
546
661
  if (element.localName === "p") paragraphs.unshift(element);
@@ -568,6 +683,7 @@ const CELL_CONTENT = new Set(["p", "tbl"]);
568
683
  /**
569
684
  * Parses verbatim WordprocessingML (opaque content) into an inert XML document, declaring the
570
685
  * prefixes it uses; null when it is not well-formed.
686
+ * @internal
571
687
  */
572
688
  export function parseOpaque(xml: string, doc: Document): Element | null {
573
689
  const view = doc.defaultView;
@@ -590,6 +706,7 @@ export function parseOpaque(xml: string, doc: Document): Element | null {
590
706
  /**
591
707
  * Renders a document's blocks. `final` review merges a paragraph whose mark was deleted into
592
708
  * the next one, as accepting the deletion does.
709
+ * @internal
593
710
  */
594
711
  export function renderBlocks(
595
712
  document: FoliDocument,
@@ -597,6 +714,7 @@ export function renderBlocks(
597
714
  options: BlockOptions = {},
598
715
  ): WordBlock[] {
599
716
  const review = options.review ?? "markup";
717
+ const codes = options.fieldCodes === true;
600
718
  const ratios = new Map<string, number>();
601
719
  const ratio = (family: string) => {
602
720
  let value = ratios.get(family);
@@ -606,7 +724,7 @@ export function renderBlocks(
606
724
  }
607
725
  return value;
608
726
  };
609
- const resolver = new Resolver(document);
727
+ const resolver = options.resolver ?? new Resolver(document);
610
728
  const image = imageSource(document.resources, options.resource);
611
729
  // shortcut: floating pictures are placed against the last section's page.
612
730
  const geometry = floatGeometry(document.section);
@@ -631,33 +749,38 @@ export function renderBlocks(
631
749
  ),
632
750
  );
633
751
  const blocks: WordBlock[] = [];
634
- let carried: { nodes: number[]; inline: NodeJSON[] } | null = null;
752
+ const displays = fieldDisplay(content.map(inlineTypes), codes);
753
+ let carried: { nodes: number[]; inline: NodeJSON[]; display: FieldDisplay } | null = null;
635
754
  /** Comment ranges open at this point of the document. */
636
755
  const comments = new Set<number>();
637
756
 
638
757
  content.forEach((node, index) => {
639
758
  if (node.type !== "paragraph") {
640
- blocks.push(opaqueBlock(node, index, resolver, doc, ratio, image, geometry));
759
+ blocks.push(
760
+ opaqueBlock(node, index, resolver, doc, ratio, image, geometry, codes, options.notes),
761
+ );
641
762
  return;
642
763
  }
643
764
  const attrs = attrsOf(node);
765
+ const own = displays[index] as FieldDisplay;
644
766
  if (joins(index)) {
645
- const previous: { nodes: number[]; inline: NodeJSON[] } = carried ?? {
646
- nodes: [],
647
- inline: [],
648
- };
767
+ const previous = carried ?? { nodes: [], inline: [], display: NO_DISPLAY };
649
768
  carried = {
650
769
  nodes: [...previous.nodes, index],
651
770
  inline: [...previous.inline, ...(node.content ?? [])],
771
+ display: joinDisplays(previous.display, previous.inline.length, own),
652
772
  };
653
773
  return;
654
774
  }
655
- const merged: { nodes: number[]; inline: NodeJSON[] } = carried ?? { nodes: [], inline: [] };
775
+ const merged = carried ?? { nodes: [], inline: [] as NodeJSON[], display: NO_DISPLAY };
656
776
  carried = null;
777
+ const display = joinDisplays(merged.display, merged.inline.length, own);
657
778
  const { paragraph, run } = resolver.paragraph(attrs);
658
779
  const element = doc.createElement(tagOf(paragraph));
659
780
  styleParagraph(element, paragraph);
660
- styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
781
+ // The line's own height is the paragraph mark's (Word has none but its runs' and the mark's).
782
+ const mark = resolver.run(run, (attrs.markFormat ?? []) as MarkJSON[]);
783
+ styleRun(element, mark, lineHeight(paragraph, mark, ratio(fontStack(latin(mark)))));
661
784
  const marker = markers[index];
662
785
  const firstMerged = merged.nodes[0];
663
786
  const shownMarker = firstMerged !== undefined ? (markers[firstMerged] ?? null) : marker;
@@ -671,7 +794,20 @@ export function renderBlocks(
671
794
  ratio,
672
795
  image,
673
796
  geometry,
797
+ codes,
798
+ display,
799
+ notes: options.notes,
674
800
  });
801
+ if (display.gone) element.style.display = "none";
802
+ if (
803
+ onlyPictures(
804
+ inline,
805
+ (node) => node.type,
806
+ (node) => !!node.attrs?.float,
807
+ )
808
+ )
809
+ for (const picture of element.querySelectorAll<HTMLElement>(`[${PICTURE_ATTR}]`))
810
+ picture.style.verticalAlign = "bottom";
675
811
  // An empty paragraph, or one ending in a line break, shows its last (empty) line; after a
676
812
  // page break the paragraph mark stays on the break's line, as in Word.
677
813
  const last = element.lastChild as Element | null;
@@ -689,8 +825,8 @@ export function renderBlocks(
689
825
  blocks.push({
690
826
  element,
691
827
  nodes: [...merged.nodes, index],
692
- before: pt(spaceBefore),
693
- after: pt(spaceAfter),
828
+ before: display.gone ? 0 : pt(spaceBefore),
829
+ after: display.gone ? 0 : pt(spaceAfter),
694
830
  keepNext: paragraph.keepNext,
695
831
  keepLines: paragraph.keepLines,
696
832
  pageBreakBefore: paragraph.pageBreakBefore,
@@ -699,25 +835,96 @@ export function renderBlocks(
699
835
  element.dataset.style = paragraph.style ?? "";
700
836
  if (paragraph.contextualSpacing) element.dataset.contextual = "";
701
837
  });
702
- applyContextualSpacing(blocks);
838
+ applyContextualSpacing(blocks, resolver.addsParagraphSpacing);
703
839
  return blocks;
704
840
  }
705
841
 
706
- /** A paragraph's element: a heading of its outline level (1-6), else a paragraph. */
842
+ const NO_DISPLAY = fieldDisplay([[]], false)[0] as FieldDisplay;
843
+ const inlineTypes = (node: NodeJSON) =>
844
+ node.type === "paragraph" ? (node.content ?? []).map((child) => child.type) : [];
845
+
846
+ /** `after`, whose nodes follow `length` others, added to `before` (paragraphs drawn as one). */
847
+ function joinDisplays(before: FieldDisplay, length: number, after: FieldDisplay): FieldDisplay {
848
+ if (!length) return after;
849
+ return {
850
+ hidden: new Set([...before.hidden, ...[...after.hidden].map((i) => i + length)]),
851
+ braces: new Map([
852
+ ...before.braces,
853
+ ...[...after.braces].map(([i, b]) => [i + length, b] as const),
854
+ ]),
855
+ gone: before.gone && after.gone,
856
+ };
857
+ }
858
+
859
+ /**
860
+ * Whether a paragraph's line holds nothing but inline pictures: Word's line then ends at the
861
+ * picture's foot (its PDFs of the corpus: no room below it for the text it does not have).
862
+ * @internal
863
+ */
864
+ export function onlyPictures<T>(
865
+ inline: Iterable<T>,
866
+ type: (node: T) => string,
867
+ floats: (node: T) => boolean,
868
+ ): boolean {
869
+ let found = false;
870
+ for (const node of inline) {
871
+ const name = type(node);
872
+ if (name === "picture") found ||= !floats(node);
873
+ else if (!INVISIBLE.has(name)) return false;
874
+ }
875
+ return found;
876
+ }
877
+
878
+ const INVISIBLE = new Set([
879
+ "bookmarkStart",
880
+ "bookmarkEnd",
881
+ "commentStart",
882
+ "commentEnd",
883
+ "commentReference",
884
+ "controlStart",
885
+ "controlEnd",
886
+ "fieldStart",
887
+ "fieldCode",
888
+ "fieldSeparator",
889
+ "fieldEnd",
890
+ ]);
891
+
892
+ /**
893
+ * The top margin of a paragraph after another (whose space after is `above`) in a box the page
894
+ * flow does not lay out (a table cell). Adjacent margins collapse to the larger: Word's rule. In
895
+ * a document where the two spaces add up this margin holds both, so the collapse gives the sum
896
+ * and no paragraph's shading or border grows.
897
+ * @internal
898
+ */
899
+ export function marginAbove(before: number, above: number, resolver: Resolver): number {
900
+ return resolver.addsParagraphSpacing ? before + above : before;
901
+ }
902
+
903
+ /**
904
+ * A paragraph's element: a heading of its outline level (1-6), else a paragraph.
905
+ * @internal
906
+ */
707
907
  export function tagOf(paragraph: ParagraphFormat): string {
708
908
  const level = paragraph.outlineLevel;
709
909
  return level !== null && level >= 0 && level < 6 ? `h${level + 1}` : "p";
710
910
  }
711
911
 
712
- /** Word ignores the space between paragraphs of the same style that ask for it. */
713
- function applyContextualSpacing(blocks: WordBlock[]): void {
912
+ /**
913
+ * Word ignores the space between paragraphs of the same style that ask for it. When only the
914
+ * first asks, its space after still eats into the second's space before, unless the document
915
+ * adds the two (`adds`).
916
+ */
917
+ function applyContextualSpacing(blocks: WordBlock[], adds: boolean): void {
714
918
  for (let i = 1; i < blocks.length; i++) {
715
919
  const a = blocks[i - 1] as WordBlock;
716
920
  const b = blocks[i] as WordBlock;
717
921
  const style = a.element.dataset.style;
718
922
  if (style === undefined || style !== b.element.dataset.style) continue;
719
- if ("contextual" in a.element.dataset) a.after = 0;
720
- if ("contextual" in b.element.dataset) b.before = 0;
923
+ const first = "contextual" in a.element.dataset;
924
+ const second = "contextual" in b.element.dataset;
925
+ if (second) b.before = 0;
926
+ else if (first && !adds) b.before = Math.max(0, b.before - a.after);
927
+ if (first) a.after = 0;
721
928
  }
722
929
  }
723
930
 
@@ -735,7 +942,10 @@ const SYMBOLS: Record<string, string> = {
735
942
  "\uF0FC": "\u2713", // Wingdings: check mark
736
943
  };
737
944
 
738
- /** A list marker: its text, then what follows it (a tab to the text's indent, a space). */
945
+ /**
946
+ * A list marker: its text, then what follows it (a tab to the text's indent, a space).
947
+ * @internal
948
+ */
739
949
  export function markerElement(
740
950
  marker: ListMarker,
741
951
  paragraph: ParagraphFormat,
@@ -781,6 +991,11 @@ interface InlineContext {
781
991
  image?: ImageSource | undefined;
782
992
  /** The page floating pictures are positioned against. */
783
993
  geometry: FloatGeometry;
994
+ /** Whether fields show their codes. */
995
+ codes: boolean;
996
+ /** What these nodes show of their fields. */
997
+ display: FieldDisplay;
998
+ notes: BlockOptions["notes"] | undefined;
784
999
  }
785
1000
 
786
1001
  /** A paragraph's inline content: runs as spans, breaks, comment anchors, opaque inline content. */
@@ -791,9 +1006,10 @@ function renderInline(
791
1006
  paragraph: ParagraphFormat,
792
1007
  context: InlineContext,
793
1008
  ): void {
794
- const { resolver, doc, review, comments, ratio, image } = context;
1009
+ const { resolver, doc, review, comments, ratio, image, codes, display } = context;
795
1010
  const floats: HTMLElement[] = [];
796
- for (const node of inline) {
1011
+ for (const [index, node] of inline.entries()) {
1012
+ if (display.hidden.has(index)) continue;
797
1013
  const marks = (node.marks ?? []) as MarkJSON[];
798
1014
  const inserted = marks.some((m) => m.type === "insertion");
799
1015
  const deleted = marks.some((m) => m.type === "deletion");
@@ -812,18 +1028,31 @@ function renderInline(
812
1028
  parent.append(anchor);
813
1029
  continue;
814
1030
  }
815
- case "bookmarkStart":
1031
+ case "bookmarkStart": {
1032
+ // Where a link to it goes (`@folijs/pdf`); out of the flow, so no line changes.
1033
+ const mark = doc.createElement("span");
1034
+ mark.dataset.foliBookmark = String(attrs.name ?? "");
1035
+ mark.style.position = "absolute";
1036
+ parent.append(mark);
1037
+ continue;
1038
+ }
816
1039
  case "bookmarkEnd":
1040
+ case "controlStart":
1041
+ case "controlEnd":
817
1042
  continue;
818
1043
  case "picture":
819
1044
  if (attrs.float) floats.push(...floatElements(attrs, doc, image, context.geometry).nodes);
820
1045
  else parent.append(pictureElement(attrs, doc, image));
821
1046
  continue;
822
1047
  case "hardBreak":
823
- case "columnBreak":
824
- // shortcut: a column break ends the line; Foli lays out one column.
825
1048
  parent.append(doc.createElement("br"));
826
1049
  continue;
1050
+ case "columnBreak": {
1051
+ const br = doc.createElement("br");
1052
+ br.setAttribute(WORD_COLUMN_BREAK_ATTR, "");
1053
+ parent.append(br);
1054
+ continue;
1055
+ }
827
1056
  case "pageBreak": {
828
1057
  const br = doc.createElement("br");
829
1058
  br.setAttribute(WORD_PAGE_BREAK_ATTR, "");
@@ -832,11 +1061,24 @@ function renderInline(
832
1061
  }
833
1062
  default:
834
1063
  }
1064
+ const code =
1065
+ display.braces.get(index) ?? (codes && node.type === "fieldCode" ? String(attrs.text) : "");
835
1066
  let text: string;
836
- if (node.type === "text") text = node.text ?? "";
1067
+ if (code) text = code;
1068
+ else if (node.type === "text") text = node.text ?? "";
837
1069
  else if (node.type === "tab") text = "\t";
1070
+ else if (node.type === "noteReference")
1071
+ text = context.notes?.references?.get(String(attrs.story)) ?? "";
1072
+ else if (node.type === "noteMark") text = context.notes?.mark ?? "";
1073
+ // A custom node without its extension here (ADR-0008): its `.docx` text, else its type.
1074
+ else if (CUSTOM_TYPE.test(node.type)) text = foreignTextOf(node) ?? `[${node.type}]`;
838
1075
  else if (node.type === "opaqueInline") {
839
1076
  const xml = parseOpaque(String(attrs.xml ?? ""), doc);
1077
+ const separator = separatorElement(xml, doc);
1078
+ if (separator) {
1079
+ parent.append(separator);
1080
+ continue;
1081
+ }
840
1082
  // A run's content (a drawing, a field character) shows as nothing; a content control or
841
1083
  // simple field as its text.
842
1084
  text = xml ? opaqueText(xml) : "";
@@ -851,6 +1093,9 @@ function renderInline(
851
1093
  let element: HTMLElement = doc.createElement("span");
852
1094
  styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
853
1095
  element.textContent = text;
1096
+ if (node.type === "noteReference") element.setAttribute(NOTE_REF_ATTR, String(attrs.story));
1097
+ if (node.type === "noteReference" || node.type === "noteMark")
1098
+ element.setAttribute(NOTE_NUMBER_ATTR, "");
854
1099
  const link = marks.find((m) => m.type === "link");
855
1100
  if (link) element.dataset.href = String(link.attrs?.href ?? `#${String(link.attrs?.anchor)}`);
856
1101
  if (comments.size) {
@@ -877,6 +1122,7 @@ function renderInline(
877
1122
  * A block the model keeps opaque (tables until Phase 10, block content controls), shown from
878
1123
  * its XML: a table as a table of its cells' paragraphs, anything else as its paragraphs. Only
879
1124
  * text is read: no formatting beyond the paragraph styles.
1125
+ * @internal
880
1126
  */
881
1127
  export function opaqueBlock(
882
1128
  node: NodeJSON,
@@ -887,6 +1133,8 @@ export function opaqueBlock(
887
1133
  image?: ImageSource,
888
1134
  /** The page floating pictures in its cells are placed against. */
889
1135
  geometry: FloatGeometry = floatGeometry(undefined),
1136
+ codes = false,
1137
+ notes?: BlockOptions["notes"],
890
1138
  ): WordBlock {
891
1139
  const attrs = (node.attrs ?? {}) as Record<string, unknown>;
892
1140
  const element = doc.createElement("div");
@@ -896,14 +1144,16 @@ export function opaqueBlock(
896
1144
  const xml = node.type === "table" ? null : parseOpaque(String(attrs.xml ?? ""), doc);
897
1145
  let after = 0;
898
1146
  if (node.type === "table")
899
- element.append(modelTable(node, resolver, doc, ratio, image, geometry));
1147
+ element.append(modelTable(node, resolver, doc, ratio, image, geometry, codes, notes));
900
1148
  else if (xml?.localName === "tbl") element.append(opaqueTable(xml, resolver, doc, ratio));
901
1149
  else if (xml) {
902
1150
  const paragraphs = outermost(xml, PARAGRAPHS);
1151
+ let above = 0;
903
1152
  paragraphs.forEach((p, i) => {
904
- const rendered = opaqueParagraph(p, resolver, doc, ratio);
1153
+ const rendered = opaqueParagraph(p, resolver, doc, ratio, above);
905
1154
  if (i < paragraphs.length - 1) rendered.element.style.marginBottom = `${rendered.after}px`;
906
1155
  else after = rendered.after;
1156
+ above = rendered.after;
907
1157
  element.append(rendered.element);
908
1158
  });
909
1159
  }
@@ -943,6 +1193,8 @@ function opaqueParagraph(
943
1193
  resolver: Resolver,
944
1194
  doc: Document,
945
1195
  ratio: (family: string) => number,
1196
+ /** The space after the paragraph before it in its box. */
1197
+ above = 0,
946
1198
  ): { element: HTMLElement; after: number } {
947
1199
  const pPr = child(p, "pPr");
948
1200
  const style = childValue(pPr, "pStyle");
@@ -964,8 +1216,8 @@ function opaqueParagraph(
964
1216
  element.append(span);
965
1217
  }
966
1218
  if (!element.textContent) element.append(doc.createElement("br"));
967
- if (paragraph.spacing.before)
968
- element.style.marginTop = `${paragraph.spacing.before * PX_PER_TWIP}px`;
1219
+ const top = marginAbove(paragraph.spacing.before * PX_PER_TWIP, above, resolver);
1220
+ if (top) element.style.marginTop = `${top}px`;
969
1221
  return { element, after: paragraph.spacing.after * PX_PER_TWIP };
970
1222
  }
971
1223
 
@@ -1093,14 +1345,17 @@ function opaqueTable(
1093
1345
  row.append(cell);
1094
1346
  continue;
1095
1347
  }
1348
+ let above = 0;
1096
1349
  for (const p of outermost(tc, CELL_CONTENT)) {
1097
1350
  if (p.localName === "tbl") {
1098
1351
  cell.append(opaqueTable(p, resolver, doc, ratio));
1352
+ above = 0;
1099
1353
  continue;
1100
1354
  }
1101
1355
  // Word counts the space after a cell's last paragraph in the row's height too.
1102
- const rendered = opaqueParagraph(p, resolver, doc, ratio);
1356
+ const rendered = opaqueParagraph(p, resolver, doc, ratio, above);
1103
1357
  rendered.element.style.marginBottom = `${rendered.after}px`;
1358
+ above = rendered.after;
1104
1359
  cell.append(rendered.element);
1105
1360
  }
1106
1361
  row.append(cell);
@@ -1111,7 +1366,10 @@ function opaqueTable(
1111
1366
  return table;
1112
1367
  }
1113
1368
 
1114
- /** A border of the model (`BorderJSON`) as CSS; undefined when it says none. */
1369
+ /**
1370
+ * A border of the model (`BorderJSON`) as CSS; undefined when it says none.
1371
+ * @internal
1372
+ */
1115
1373
  export function borderJsonCss(
1116
1374
  border: { style?: string; size?: number; color?: string } | undefined,
1117
1375
  ) {
@@ -1126,8 +1384,9 @@ export function borderJsonCss(
1126
1384
  * A table of the model (schema v4), read-only, as opaque tables are shown: rows, cells with
1127
1385
  * their table style's formatting (`Resolver.cell`), their paragraphs and nested tables.
1128
1386
  *
1129
- * shortcut: a stopgap until tables are laid out on pages and edited (10.5, 10.6): one block,
1130
- * not split across pages; a cell merged into the one above is shown empty, as opaque tables are.
1387
+ * shortcut: `renderDocument`'s tables (the editing view draws its own, `table.ts`): one block,
1388
+ * split across pages as clips; a cell merged into the one above is shown empty, as opaque
1389
+ * tables are.
1131
1390
  */
1132
1391
  function modelTable(
1133
1392
  node: NodeJSON,
@@ -1136,6 +1395,8 @@ function modelTable(
1136
1395
  ratio: (family: string) => number,
1137
1396
  image: ImageSource | undefined,
1138
1397
  geometry: FloatGeometry,
1398
+ codes: boolean,
1399
+ notes: BlockOptions["notes"],
1139
1400
  ): HTMLElement {
1140
1401
  const attrs = (node.attrs ?? {}) as Record<string, unknown>;
1141
1402
  const table = doc.createElement("table");
@@ -1162,6 +1423,7 @@ function modelTable(
1162
1423
  image,
1163
1424
  // shortcut: a floating picture in a cell is placed against the page, not its cell.
1164
1425
  geometry,
1426
+ codes,
1165
1427
  };
1166
1428
  rows.forEach((rowNode, r) => {
1167
1429
  const rowAttrs = (rowNode.attrs ?? {}) as Record<string, unknown>;
@@ -1191,13 +1453,20 @@ function modelTable(
1191
1453
  }
1192
1454
  row.append(cell);
1193
1455
  if (cellAttrs.vMerge === "continue") return;
1194
- for (const block of cellNode.content ?? []) {
1456
+ let above = 0;
1457
+ const blocks = cellNode.content ?? [];
1458
+ const displays = fieldDisplay(blocks.map(inlineTypes), codes);
1459
+ for (const [b, block] of blocks.entries()) {
1195
1460
  if (block.type === "table") {
1196
- cell.append(modelTable(block, resolver, doc, ratio, image, geometry));
1461
+ cell.append(modelTable(block, resolver, doc, ratio, image, geometry, codes, notes));
1462
+ above = 0;
1197
1463
  continue;
1198
1464
  }
1199
1465
  if (block.type !== "paragraph") {
1200
- cell.append(opaqueBlock(block, 0, resolver, doc, ratio, image, geometry).element);
1466
+ cell.append(
1467
+ opaqueBlock(block, 0, resolver, doc, ratio, image, geometry, codes, notes).element,
1468
+ );
1469
+ above = 0;
1201
1470
  continue;
1202
1471
  }
1203
1472
  const { paragraph, run } = resolver.paragraph(block.attrs ?? {}, format);
@@ -1206,11 +1475,19 @@ function modelTable(
1206
1475
  element.dataset.foliCell = "";
1207
1476
  styleParagraph(element, paragraph);
1208
1477
  styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
1209
- renderInline(element, block.content ?? [], run, paragraph, context);
1478
+ const display = displays[b] as FieldDisplay;
1479
+ renderInline(element, block.content ?? [], run, paragraph, {
1480
+ ...context,
1481
+ display,
1482
+ notes,
1483
+ });
1484
+ if (display.gone) element.style.display = "none";
1210
1485
  if (!element.textContent) element.append(doc.createElement("br"));
1211
- element.style.marginTop = `${paragraph.spacing.before * PX_PER_TWIP}px`;
1486
+ const before = paragraph.spacing.before * PX_PER_TWIP;
1487
+ element.style.marginTop = `${marginAbove(before, above, resolver)}px`;
1212
1488
  // Word counts the space after a cell's last paragraph in the row's height too.
1213
- element.style.marginBottom = `${paragraph.spacing.after * PX_PER_TWIP}px`;
1489
+ above = paragraph.spacing.after * PX_PER_TWIP;
1490
+ element.style.marginBottom = `${above}px`;
1214
1491
  cell.append(element);
1215
1492
  }
1216
1493
  });