@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
package/src/word/edit.ts CHANGED
@@ -10,15 +10,30 @@
10
10
  * opaque inline node a leaf element.
11
11
  */
12
12
  import {
13
- type CellFormat,
13
+ type FieldDisplay,
14
+ fieldDisplay,
14
15
  isSafeHref,
15
- type ListMarker,
16
16
  type Mark,
17
17
  type MarkJSON,
18
18
  type Node as ModelNode,
19
+ } from "@folijs/core";
20
+ import {
21
+ type CellFormat,
22
+ type ListMarker,
19
23
  type RunFormat,
24
+ referencesIn,
20
25
  type WordContext,
21
- } from "@folijs/core";
26
+ } from "@folijs/core/internal";
27
+ import {
28
+ applyAttrs,
29
+ type Decoration,
30
+ type Drawn,
31
+ type NodeView,
32
+ type NodeViewDOM,
33
+ nodeViewDOM,
34
+ reportError,
35
+ type Views,
36
+ } from "../extension.js";
22
37
  import type { BlockDesc, LeafDesc } from "../render.js";
23
38
  import {
24
39
  CHANGE_BAR,
@@ -31,9 +46,14 @@ import {
31
46
  imageSource,
32
47
  latin,
33
48
  lineHeight,
49
+ marginAbove,
34
50
  markerElement,
51
+ NOTE_NUMBER_ATTR,
52
+ NOTE_REF_ATTR,
53
+ onlyPictures,
35
54
  opaqueBlock,
36
55
  opaqueText,
56
+ PICTURE_ATTR,
37
57
  PX_PER_TWIP,
38
58
  parseOpaque,
39
59
  pictureElement,
@@ -41,9 +61,24 @@ import {
41
61
  styleParagraph,
42
62
  styleRun,
43
63
  tagOf,
64
+ WORD_COLUMN_BREAK_ATTR,
44
65
  WORD_PAGE_BREAK_ATTR,
45
66
  } from "./blocks.js";
46
67
 
68
+ /** Inline nodes with nothing to show: a line holding only these is still an empty line. */
69
+ const NOT_IN_LINE = new Set([
70
+ "bookmarkStart",
71
+ "bookmarkEnd",
72
+ "commentStart",
73
+ "commentEnd",
74
+ "controlStart",
75
+ "controlEnd",
76
+ "fieldStart",
77
+ "fieldCode",
78
+ "fieldSeparator",
79
+ "fieldEnd",
80
+ ]);
81
+
47
82
  const REVIEW_MARKS = new Set(["insertion", "deletion", "formatChange"]);
48
83
 
49
84
  /** Whether a paragraph has tracked changes: in its text, its mark or its formatting. */
@@ -56,7 +91,10 @@ function hasChanges(node: ModelNode): boolean {
56
91
  return found;
57
92
  }
58
93
 
59
- /** What the page flow needs to know about a v3 block. */
94
+ /**
95
+ * What the page flow needs to know about a v3 block.
96
+ * @internal
97
+ */
60
98
  export interface WordInfo {
61
99
  /** Space before and after in CSS px (Word adds them: the flow places them). */
62
100
  before: number;
@@ -67,27 +105,50 @@ export interface WordInfo {
67
105
  /** The paragraph's style and whether it drops spacing next to the same style. */
68
106
  style: string | null;
69
107
  contextual: boolean;
108
+ /** A paragraph with nothing to show in its line. */
109
+ empty: boolean;
110
+ }
111
+
112
+ /** A paragraph's inline nodes, by type name. */
113
+ function childTypes(node: ModelNode): string[] {
114
+ const types: string[] = [];
115
+ if (node.type.name === "paragraph")
116
+ node.forEach((child) => {
117
+ types.push(child.type.name);
118
+ });
119
+ return types;
70
120
  }
71
121
 
72
- /** A rendered v3 block: a view block plus its flow information and what it was rendered for. */
122
+ /**
123
+ * A rendered v3 block: a view block plus its flow information and what it was rendered for.
124
+ * @internal
125
+ */
73
126
  export interface WordBlockDesc extends BlockDesc {
74
127
  readonly word: WordInfo;
75
128
  /** What the rendering depends on besides the node (its marker, open comments). */
76
129
  readonly key: string;
130
+ /**
131
+ * A custom block's node view that may split: where it may break, as the bottoms of its root's
132
+ * children from its top (client px; the last is its height). Its `splits` are then the layout
133
+ * px from its top where each fragment after the first starts, not content offsets.
134
+ */
135
+ readonly parts?: () => number[];
77
136
  }
78
137
 
79
138
  /**
80
139
  * A floating picture's holder (drawn first in its paragraph, the view's own DOM) to its anchor:
81
140
  * the empty, non-editable span at the picture's place in the text, which positions map to.
141
+ * @internal
82
142
  */
83
143
  export const FLOAT_ANCHORS = new WeakMap<Element, HTMLElement>();
84
144
 
85
145
  /**
86
146
  * Renders the blocks of one v3 document for the editable view. `prepare` runs before each
87
147
  * render: list numbers and comment ranges depend on the blocks before.
148
+ * @internal
88
149
  */
89
150
  export class WordRenderer {
90
- readonly #context: WordContext;
151
+ #context: WordContext;
91
152
  readonly #doc: Document;
92
153
  readonly #ratio: (family: string) => number;
93
154
  /** For the clipboard (`clipboardBlocks`): links as links, list numbers as Word's HTML has them. */
@@ -99,6 +160,25 @@ export class WordRenderer {
99
160
  #markers: (ListMarker | null)[] = [];
100
161
  /** Comment ranges open at the start of each block. */
101
162
  #comments: number[][] = [];
163
+ /** Where a document adds paragraph spacing: the space after the paragraph above, in a cell. */
164
+ #above: number[] = [];
165
+ /** Whether fields show their codes. */
166
+ readonly #codes: boolean;
167
+ /** What each block shows of its fields. */
168
+ #fields: FieldDisplay[] = [];
169
+ /** What note references show, by story, and what a note's own mark shows. */
170
+ #notes: ReadonlyMap<string, string> = new Map();
171
+ #noteMark = "";
172
+ /** The numbers each block shows. */
173
+ #noteKeys: string[] = [];
174
+ /** Node and mark views (`ViewExtension`), none on the clipboard. */
175
+ views: Views | null = null;
176
+ /** Where node views' drawings are recorded, for their `destroy` (the view's list). */
177
+ drawn: Drawn[] | null = null;
178
+ readonly #dom: NodeViewDOM;
179
+ /** Each block's decorations, relative to its content (`decorationsByBlock`), and as keys. */
180
+ #decorations: readonly (readonly Decoration[] | undefined)[] = [];
181
+ #decorationKeys: string[] = [];
102
182
 
103
183
  constructor(
104
184
  context: WordContext,
@@ -107,9 +187,12 @@ export class WordRenderer {
107
187
  clipboard = false,
108
188
  review: ReviewView = "markup",
109
189
  image?: ImageSource,
190
+ codes = false,
110
191
  ) {
192
+ this.#codes = codes;
111
193
  this.#context = context;
112
194
  this.#doc = doc;
195
+ this.#dom = nodeViewDOM(doc);
113
196
  this.#ratio = ratio;
114
197
  this.#clipboard = clipboard;
115
198
  this.#review = review;
@@ -120,11 +203,42 @@ export class WordRenderer {
120
203
  return this.#context;
121
204
  }
122
205
 
206
+ /** The envelope moved on without touching what blocks look like (a story was edited). */
207
+ set context(context: WordContext) {
208
+ this.#context = context;
209
+ }
210
+
211
+ /** Decorations by block index (of those prepared): set before `key` and `render`. */
212
+ set decorations(list: readonly (readonly Decoration[] | undefined)[]) {
213
+ this.#decorations = list;
214
+ this.#decorationKeys = list.map((own) => (own ? JSON.stringify(own) : ""));
215
+ }
216
+
217
+ /** What notes show: set before `prepare`. */
218
+ setNotes(references: ReadonlyMap<string, string>, mark = ""): void {
219
+ this.#notes = references;
220
+ this.#noteMark = mark;
221
+ }
222
+
123
223
  /**
124
224
  * Numbering and comment state for `blocks`, the blocks rendered, in document order (the
125
- * paragraphs in table cells among them: Word numbers lists through tables).
225
+ * paragraphs in table cells among them: Word numbers lists through tables). `aboveInCell`
226
+ * gives the paragraph before one in its table cell, with that cell's format.
126
227
  */
127
- prepare(blocks: readonly ModelNode[]): void {
228
+ prepare(
229
+ blocks: readonly ModelNode[],
230
+ aboveInCell?: (index: number) => { node: ModelNode; cell: CellFormat } | null,
231
+ ): void {
232
+ const { resolver } = this.#context;
233
+ this.#above =
234
+ resolver.addsParagraphSpacing && aboveInCell
235
+ ? blocks.map((_, i) => {
236
+ const previous = aboveInCell(i);
237
+ if (previous?.node.type.name !== "paragraph") return 0;
238
+ const { spacing } = resolver.paragraph(previous.node.attrs, previous.cell).paragraph;
239
+ return (spacing.afterAutospacing ? 280 : spacing.after) * PX_PER_TWIP;
240
+ })
241
+ : [];
128
242
  const attrs: Record<string, unknown>[] = [];
129
243
  const comments: number[][] = [];
130
244
  const open = new Set<number>();
@@ -139,6 +253,14 @@ export class WordRenderer {
139
253
  }
140
254
  this.#markers = this.#context.resolver.markers(attrs);
141
255
  this.#comments = comments;
256
+ this.#fields = fieldDisplay(blocks.map(childTypes), this.#codes);
257
+ this.#noteKeys = this.#notes.size
258
+ ? blocks.map((node) =>
259
+ referencesIn(node)
260
+ .map((ref) => this.#notes.get(ref.story) ?? "")
261
+ .join(" "),
262
+ )
263
+ : [];
142
264
  }
143
265
 
144
266
  /** Whether the block at `index` (of those prepared) shows a list number. */
@@ -149,7 +271,13 @@ export class WordRenderer {
149
271
  /** What a block's rendering depends on at `index`, besides its node (and its cell's format). */
150
272
  key(index: number, cell?: CellFormat | null): string {
151
273
  const inCell = cell ? `|${cell.style ?? ""}:${cell.conditions.join(",")}` : "";
152
- return `${this.#markers[index]?.text ?? ""}|${(this.#comments[index] ?? []).join(" ")}${inCell}`;
274
+ const above = this.#above[index] ? `|${this.#above[index]}` : "";
275
+ // A field opened or closed in an earlier block changes what shows here.
276
+ const field = this.#fields[index];
277
+ const fields = field?.hidden.size || field?.gone ? `|${[...field.hidden]}${field.gone}` : "";
278
+ const notes = this.#noteKeys[index] ? `|${this.#noteKeys[index]}` : "";
279
+ const decorations = this.#decorationKeys[index] ? `|${this.#decorationKeys[index]}` : "";
280
+ return `${this.#markers[index]?.text ?? ""}|${(this.#comments[index] ?? []).join(" ")}${inCell}${above}${fields}${notes}|${this.#noteMark}${decorations}`;
153
281
  }
154
282
 
155
283
  /** A block; `cell` is the format of the table cell it is in, if any. */
@@ -159,16 +287,24 @@ export class WordRenderer {
159
287
  splits: readonly number[] = [],
160
288
  cell?: CellFormat | null,
161
289
  ): WordBlockDesc {
162
- if (node.type.name !== "paragraph") return this.#opaque(node, index);
290
+ const decorations = this.#decorations[index] ?? [];
291
+ if (node.type.name !== "paragraph") return this.#opaque(node, index, splits, !!cell);
163
292
  const { resolver } = this.#context;
164
293
  const { paragraph, run } = resolver.paragraph(node.attrs, cell ?? undefined);
165
294
  const line = (r: RunFormat) => lineHeight(paragraph, r, this.#ratio(fontStack(latin(r))));
166
295
  const doc = this.#doc;
296
+ const codes = this.#codes;
297
+ // On the clipboard a block stands by itself.
298
+ const display = this.#clipboard
299
+ ? (fieldDisplay([childTypes(node)], false)[0] as FieldDisplay)
300
+ : (this.#fields[index] ?? (fieldDisplay([[]], false)[0] as FieldDisplay));
167
301
  const changed = this.#review !== "final" && hasChanges(node);
302
+ // The line's own height is the paragraph mark's, as in `renderBlocks`.
303
+ const mark = resolver.run(run, (node.attrs.markFormat ?? []) as MarkJSON[]);
168
304
  const fragments = [0, ...splits].map((_, i, all) => {
169
305
  const fragment = doc.createElement(tagOf(paragraph));
170
306
  styleParagraph(fragment, paragraph);
171
- styleRun(fragment, run, line(run));
307
+ styleRun(fragment, mark, line(mark));
172
308
  if (all.length > 1) {
173
309
  fragment.dataset.fragment = String(i);
174
310
  // The first-line indent is the paragraph's first line only.
@@ -179,6 +315,8 @@ export class WordRenderer {
179
315
  fragment.style.textAlignLast = "justify";
180
316
  }
181
317
  if (changed && !this.#clipboard) fragment.style.boxShadow = CHANGE_BAR;
318
+ if (display.gone) fragment.style.display = "none";
319
+ for (const d of decorations) if (d.node && d.from < 0) applyAttrs(fragment, d.attrs);
182
320
  return fragment;
183
321
  });
184
322
  const dom = fragments[0] as HTMLElement;
@@ -201,13 +339,30 @@ export class WordRenderer {
201
339
  const floats = new Map<HTMLElement, HTMLElement[]>();
202
340
  let geometry: FloatGeometry | undefined;
203
341
  const comments = new Set(this.#comments[index] ?? []);
204
- node.forEach((child, offset) => {
342
+ /** Inline decorations over content `from`..`to`, and node ones on a leaf there. */
343
+ const decorate = (element: HTMLElement, from: number, to: number, leaf: boolean) => {
344
+ for (const d of decorations)
345
+ if (d.node ? leaf && d.from === from : d.from <= from && d.to >= to)
346
+ applyAttrs(element, d.attrs);
347
+ };
348
+ node.forEach((child, offset, childIndex) => {
205
349
  const name = child.type.name;
206
350
  if (name === "commentStart") comments.add(child.attrs.id as number);
207
351
  if (name === "commentEnd") comments.delete(child.attrs.id as number);
352
+ const hidden = display.hidden.has(childIndex);
353
+ /** Where this node's DOM goes: out of sight when it is hidden, as hidden deletions are. */
354
+ const holder = (at: number): HTMLElement => {
355
+ const fragment = fragmentAt(at);
356
+ if (!hidden) return fragment;
357
+ const span = doc.createElement("span");
358
+ span.style.display = "none";
359
+ fragment.append(span);
360
+ return span;
361
+ };
208
362
  const leafElement = (element: HTMLElement) => {
363
+ decorate(element, offset, offset + child.nodeSize, true);
209
364
  leaves.push({ dom: element, offset, size: child.nodeSize });
210
- fragmentAt(offset).append(this.#wrap(element, child.marks, comments));
365
+ holder(offset).append(this.#wrap(element, child.marks, comments));
211
366
  };
212
367
  switch (name) {
213
368
  case "text":
@@ -215,27 +370,28 @@ export class WordRenderer {
215
370
  case "hardBreak":
216
371
  case "columnBreak":
217
372
  case "pageBreak": {
218
- // shortcut: a column break ends the line; Foli lays out one column.
219
373
  const br = doc.createElement("br");
220
374
  if (name === "pageBreak") br.setAttribute(WORD_PAGE_BREAK_ATTR, "");
375
+ if (name === "columnBreak") br.setAttribute(WORD_COLUMN_BREAK_ATTR, "");
221
376
  leaves.push({ dom: br, offset, size: 1 });
222
- fragmentAt(offset).append(br);
377
+ holder(offset).append(br);
223
378
  return;
224
379
  }
225
380
  case "tab": {
226
381
  // A tab is text to the line layout (tab stops) and to the read-back.
227
382
  const span = this.#run(run, child.marks, line);
383
+ decorate(span, offset, offset + 1, true);
228
384
  const tab = doc.createTextNode("\t");
229
385
  span.append(tab);
230
386
  leaves.push({ dom: tab, offset, size: 1 });
231
- fragmentAt(offset).append(this.#wrap(span, child.marks, comments));
387
+ holder(offset).append(this.#wrap(span, child.marks, comments));
232
388
  return;
233
389
  }
234
390
  case "picture": {
235
391
  // Not editable inside (no browser resize handles); one position, like opaque content.
236
392
  const span = doc.createElement("span");
237
393
  span.setAttribute("contenteditable", "false");
238
- if (child.attrs.float && !this.#clipboard) {
394
+ if (child.attrs.float && !this.#clipboard && !hidden) {
239
395
  // Floating: drawn at the fragment's start (ADR-0006), its place in the text an
240
396
  // empty anchor.
241
397
  geometry ??= floatGeometry(this.#context.envelope.section);
@@ -248,6 +404,18 @@ export class WordRenderer {
248
404
  leafElement(span);
249
405
  return;
250
406
  }
407
+ case "noteReference":
408
+ case "noteMark": {
409
+ // Drawn, never document text: the number comes from where the note is.
410
+ const span = this.#run(run, child.marks, line);
411
+ const story = String(child.attrs.story);
412
+ span.textContent = name === "noteMark" ? this.#noteMark : (this.#notes.get(story) ?? "");
413
+ span.setAttribute("contenteditable", "false");
414
+ span.setAttribute(NOTE_NUMBER_ATTR, "");
415
+ if (name === "noteReference") span.setAttribute(NOTE_REF_ATTR, story);
416
+ leafElement(span);
417
+ return;
418
+ }
251
419
  case "opaqueInline": {
252
420
  const span = this.#run(run, child.marks, line);
253
421
  const xml = parseOpaque(String(child.attrs.xml ?? ""), doc);
@@ -258,37 +426,87 @@ export class WordRenderer {
258
426
  return;
259
427
  }
260
428
  default: {
429
+ const stands = child.type.spec.text;
430
+ if (stands) {
431
+ // A custom or foreign node (ADR-0008): its node view or its text, one position, as
432
+ // opaque content.
433
+ const span = this.#run(run, child.marks, line);
434
+ const view = this.#clipboard ? undefined : this.views?.nodes.get(name);
435
+ const drawn = view && this.#draw(view, child, span);
436
+ if (drawn) span.append(drawn);
437
+ else span.textContent = stands(child.attrs);
438
+ span.dataset.foliCustom = String(child.attrs.type ?? name);
439
+ span.setAttribute("contenteditable", "false");
440
+ leafElement(span);
441
+ return;
442
+ }
443
+ // A field's code and braces, when codes show: drawn, not document text.
444
+ const shown =
445
+ display.braces.get(childIndex) ??
446
+ (codes && !hidden && name === "fieldCode" ? String(child.attrs.text ?? "") : "");
447
+ if (shown) {
448
+ const span = this.#run(run, child.marks, line);
449
+ span.textContent = shown;
450
+ span.dataset.foliFieldCode = "";
451
+ span.setAttribute("contenteditable", "false");
452
+ leaves.push({ dom: span, offset, size: child.nodeSize });
453
+ fragmentAt(offset).append(span);
454
+ return;
455
+ }
261
456
  // Bookmarks, comment anchors and reference marks: nothing to see, a place to map to.
262
457
  const span = doc.createElement("span");
263
458
  if (name === "commentReference")
264
459
  span.dataset.foliCommentReference = String(child.attrs.id);
265
460
  leaves.push({ dom: span, offset, size: child.nodeSize });
266
- fragmentAt(offset).append(span);
461
+ holder(offset).append(span);
267
462
  return;
268
463
  }
269
464
  }
270
465
  const text = child.text ?? "";
271
- const cuts = splits.filter((split) => split > offset && split < offset + text.length);
466
+ const inside = (at: number) => at > offset && at < offset + text.length;
467
+ const cuts = splits.filter(inside);
468
+ // Inline decorations start and end runs of their own.
469
+ for (const d of decorations)
470
+ if (!d.node)
471
+ for (const at of [d.from, d.to]) if (inside(at) && !cuts.includes(at)) cuts.push(at);
472
+ cuts.sort((a, b) => a - b);
272
473
  let from = offset;
273
474
  for (const to of [...cuts, offset + text.length]) {
274
475
  const leaf = doc.createTextNode(text.slice(from - offset, to - offset));
275
476
  leaves.push({ dom: leaf, offset: from, size: to - from });
276
477
  const span = this.#run(run, child.marks, line);
478
+ decorate(span, from, to, false);
277
479
  span.append(leaf);
278
- fragmentAt(from).append(this.#wrap(span, child.marks, comments));
480
+ holder(from).append(this.#wrap(span, child.marks, comments));
279
481
  from = to;
280
482
  }
281
483
  });
282
484
  for (const [fragment, nodes] of floats) fragment.prepend(...nodes);
485
+ const inline: ModelNode[] = [];
486
+ node.forEach((child) => {
487
+ inline.push(child);
488
+ });
489
+ if (
490
+ onlyPictures(
491
+ inline,
492
+ (child) => child.type.name,
493
+ (child) => !!child.attrs.float,
494
+ )
495
+ )
496
+ for (const fragment of fragments)
497
+ for (const picture of fragment.querySelectorAll<HTMLElement>(`[${PICTURE_ATTR}]`))
498
+ picture.style.verticalAlign = "bottom";
283
499
  // An empty paragraph, or one ending in a line break, shows its last line; after a page
284
500
  // break the paragraph mark stays on the break's line, as in Word.
285
501
  let last: ModelNode | null = null;
286
502
  for (let i = node.childCount - 1; i >= 0 && !last; i--) {
287
503
  const child = node.child(i);
504
+ if (display.hidden.has(i)) continue;
288
505
  // A floating picture is not in the line: a paragraph holding only one shows its empty line.
289
506
  if (
290
- !["bookmarkStart", "bookmarkEnd", "commentStart", "commentEnd"].includes(child.type.name) &&
291
- !(child.type.name === "picture" && child.attrs.float)
507
+ display.braces.has(i) ||
508
+ (codes && child.type.name === "fieldCode") ||
509
+ (!NOT_IN_LINE.has(child.type.name) && !(child.type.name === "picture" && child.attrs.float))
292
510
  )
293
511
  last = child;
294
512
  }
@@ -297,19 +515,20 @@ export class WordRenderer {
297
515
  const { before, after } = paragraph.spacing;
298
516
  // Word's automatic spacing (HTML): 14 pt.
299
517
  const word: WordInfo = {
300
- before: (paragraph.spacing.beforeAutospacing ? 280 : before) * PX_PER_TWIP,
301
- after: (paragraph.spacing.afterAutospacing ? 280 : after) * PX_PER_TWIP,
518
+ before: display.gone ? 0 : (paragraph.spacing.beforeAutospacing ? 280 : before) * PX_PER_TWIP,
519
+ after: display.gone ? 0 : (paragraph.spacing.afterAutospacing ? 280 : after) * PX_PER_TWIP,
302
520
  keepNext: paragraph.keepNext,
303
521
  keepLines: paragraph.keepLines,
304
522
  pageBreakBefore: paragraph.pageBreakBefore,
305
523
  style: paragraph.style,
306
524
  contextual: paragraph.contextualSpacing,
525
+ empty: !last && !marker,
307
526
  };
308
527
  if (cell && !this.#clipboard) {
309
528
  // In a cell its spacing is its margins (the page flow spaces top-level blocks); a
310
529
  // fragment continued on the next page has none at the split.
311
530
  // shortcut: contextual spacing between paragraphs in a cell is not applied.
312
- dom.style.marginTop = `${word.before}px`;
531
+ dom.style.marginTop = `${marginAbove(word.before, this.#above[index] ?? 0, resolver)}px`;
313
532
  (fragments[fragments.length - 1] as HTMLElement).style.marginBottom = `${word.after}px`;
314
533
  }
315
534
  if (this.#clipboard) {
@@ -336,6 +555,20 @@ export class WordRenderer {
336
555
  const run = this.#context.resolver.run(paragraphRun, json);
337
556
  const span = this.#doc.createElement("span");
338
557
  styleRun(span, run, line(run));
558
+ // Custom marks (ADR-0008): named for CSS, styled by their mark views.
559
+ const custom: string[] = [];
560
+ for (const mark of marks) {
561
+ const type = mark.type.name === "foreign" ? String(mark.attrs.type) : mark.type.name;
562
+ if (!type.includes(":")) continue;
563
+ custom.push(type);
564
+ const view = this.views?.marks.get(mark.type.name);
565
+ try {
566
+ if (view) applyAttrs(span, view(mark));
567
+ } catch (error) {
568
+ reportError(error);
569
+ }
570
+ }
571
+ if (custom.length) span.dataset.foliMark = custom.join(" ");
339
572
  return span;
340
573
  }
341
574
 
@@ -370,8 +603,95 @@ export class WordRenderer {
370
603
  return a;
371
604
  }
372
605
 
606
+ /** A node view's drawing of `node` in `box`, recorded; null (reported) when `render` throws. */
607
+ #draw(view: NodeView, node: ModelNode, box: HTMLElement): Node | null {
608
+ try {
609
+ const root = view.render(node, this.#dom);
610
+ this.drawn?.push({ view, root, box });
611
+ return root;
612
+ } catch (error) {
613
+ reportError(error);
614
+ return null;
615
+ }
616
+ }
617
+
618
+ /**
619
+ * A custom block drawn by its node view (ADR-0008): one fragment, or one per page it is split
620
+ * across, each drawing the node again and showing its part (`splits`, layout px) through a clip.
621
+ */
622
+ #nodeView(
623
+ node: ModelNode,
624
+ index: number,
625
+ view: NodeView,
626
+ splits: readonly number[],
627
+ inCell: boolean,
628
+ ): WordBlockDesc {
629
+ const doc = this.#doc;
630
+ const tops = [0, ...splits];
631
+ let root: Node | undefined;
632
+ const fragments = tops.map((top, i) => {
633
+ const box = doc.createElement("div");
634
+ box.dataset.foliCustom = node.type.name;
635
+ box.setAttribute("contenteditable", "false");
636
+ // Its root's margins stay inside it: measured as the flow places it.
637
+ box.style.display = "flow-root";
638
+ const drawn =
639
+ this.#draw(view, node, box) ?? doc.createTextNode(node.type.spec.text?.(node.attrs) ?? "");
640
+ root ??= drawn;
641
+ if (tops.length > 1) {
642
+ box.dataset.fragment = String(i);
643
+ box.style.overflow = "hidden";
644
+ const next = tops[i + 1];
645
+ if (next !== undefined) box.style.height = `${next - top}px`;
646
+ // The parts after the first are drawn again: read once.
647
+ if (i > 0) {
648
+ box.setAttribute("aria-hidden", "true");
649
+ box.setAttribute("inert", "");
650
+ }
651
+ const inner = doc.createElement("div");
652
+ inner.style.marginTop = `${-top}px`;
653
+ inner.append(drawn);
654
+ box.append(inner);
655
+ } else box.append(drawn);
656
+ for (const d of this.#decorations[index] ?? [])
657
+ if (d.node && d.from < 0) applyAttrs(box, d.attrs);
658
+ return box;
659
+ });
660
+ const dom = fragments[0] as HTMLElement;
661
+ // shortcut: a custom block in a table cell is kept whole (cells split at their lines); split it there when a node view needs it.
662
+ const split = view.split !== false && !inCell;
663
+ const parts = () => {
664
+ const { top, height } = dom.getBoundingClientRect();
665
+ const bottoms: number[] = [];
666
+ const children = root?.nodeType === Node.ELEMENT_NODE ? (root as Element).children : [];
667
+ for (const child of children) {
668
+ const bottom = child.getBoundingClientRect().bottom - top;
669
+ if (bottom > (bottoms[bottoms.length - 1] ?? 0) && bottom < height) bottoms.push(bottom);
670
+ }
671
+ bottoms.push(height);
672
+ return bottoms;
673
+ };
674
+ return {
675
+ node,
676
+ dom,
677
+ fragments,
678
+ splits,
679
+ leaves: [],
680
+ key: this.key(index),
681
+ word: leafInfo(!split),
682
+ ...(split ? { parts } : {}),
683
+ };
684
+ }
685
+
373
686
  /** An opaque block, shown from its XML: a block leaf, not editable inside. */
374
- #opaque(node: ModelNode, index: number): WordBlockDesc {
687
+ #opaque(
688
+ node: ModelNode,
689
+ index: number,
690
+ splits: readonly number[],
691
+ inCell: boolean,
692
+ ): WordBlockDesc {
693
+ const view = this.#clipboard ? undefined : this.views?.nodes.get(node.type.name);
694
+ if (view) return this.#nodeView(node, index, view, splits, inCell);
375
695
  const shown = opaqueBlock(
376
696
  node.toJSON(),
377
697
  index,
@@ -383,6 +703,14 @@ export class WordRenderer {
383
703
  );
384
704
  const dom = shown.element;
385
705
  dom.setAttribute("contenteditable", "false");
706
+ const stands = node.type.spec.text;
707
+ if (stands) {
708
+ // A custom or foreign block (ADR-0008): its text in a box.
709
+ dom.textContent = stands(node.attrs);
710
+ dom.dataset.foliCustom = String(node.attrs.type ?? node.type.name);
711
+ }
712
+ for (const d of this.#decorations[index] ?? [])
713
+ if (d.node && d.from < 0) applyAttrs(dom, d.attrs);
386
714
  return {
387
715
  node,
388
716
  dom,
@@ -398,11 +726,26 @@ export class WordRenderer {
398
726
  pageBreakBefore: false,
399
727
  style: null,
400
728
  contextual: false,
729
+ empty: false,
401
730
  },
402
731
  };
403
732
  }
404
733
  }
405
734
 
735
+ /** What the flow needs of a block that is not a paragraph: no spacing, keep rules or breaks. */
736
+ function leafInfo(keepLines: boolean): WordInfo {
737
+ return {
738
+ before: 0,
739
+ after: 0,
740
+ keepNext: false,
741
+ keepLines,
742
+ pageBreakBefore: false,
743
+ style: null,
744
+ contextual: false,
745
+ empty: false,
746
+ };
747
+ }
748
+
406
749
  /** An element's style attribute, ready for one more declaration. */
407
750
  function styleOf(element: Element): string {
408
751
  const style = element.getAttribute("style")?.trim() ?? "";
@@ -413,6 +756,7 @@ function styleOf(element: Element): string {
413
756
  * The HTML of copied v3 blocks `nodes`: drawn as the editor draws them, with their list numbers
414
757
  * in `doc` (from top-level block `first`; -1 for text from inside one paragraph, which takes no
415
758
  * number), without what only the editor needs (comment shading, `contenteditable`).
759
+ * @internal
416
760
  */
417
761
  export function clipboardBlocks(
418
762
  context: WordContext,
@@ -443,16 +787,22 @@ export function clipboardBlocks(
443
787
 
444
788
  /**
445
789
  * A block's space before and after next to its neighbours: Word ignores the space between
446
- * paragraphs of the same style that ask for it (contextual spacing).
790
+ * paragraphs of the same style that ask for it (contextual spacing). When only the first asks,
791
+ * its space after still eats into the second's space before, unless the document adds the two
792
+ * (`adds`).
793
+ * @internal
447
794
  */
448
795
  export function spacing(
449
796
  above: WordInfo | undefined,
450
797
  block: WordInfo,
451
798
  below: WordInfo | undefined,
799
+ adds = false,
452
800
  ): { before: number; after: number } {
453
801
  const same = (other: WordInfo | undefined) => other !== undefined && other.style === block.style;
454
- return {
455
- before: same(above) && block.contextual ? 0 : block.before,
456
- after: same(below) && block.contextual ? 0 : block.after,
457
- };
802
+ let { before } = block;
803
+ if (above && same(above)) {
804
+ if (block.contextual) before = 0;
805
+ else if (above.contextual && !adds) before = Math.max(0, block.before - above.after);
806
+ }
807
+ return { before, after: same(below) && block.contextual ? 0 : block.after };
458
808
  }