@folijs/view 0.3.0 → 0.5.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.
package/src/word/edit.ts CHANGED
@@ -4,11 +4,13 @@
4
4
  * fragments at content offsets like the v2 blocks (`render.ts`), and what the page flow needs
5
5
  * of each: Word's paragraph spacing and keep rules. Built with createElement/textContent only.
6
6
  *
7
- * Tracked changes are shown as markup (inserted and deleted text both shown). Content the model
7
+ * Tracked changes show as the view's review mode says (deleted text hidden, not left out, in the
8
+ * simple and final views: positions map through it). Content the model
8
9
  * keeps opaque is shown from its XML and cannot be edited: an opaque block is a block leaf, an
9
10
  * opaque inline node a leaf element.
10
11
  */
11
12
  import {
13
+ type CellFormat,
12
14
  isSafeHref,
13
15
  type ListMarker,
14
16
  type Mark,
@@ -19,7 +21,14 @@ import {
19
21
  } from "@folijs/core";
20
22
  import type { BlockDesc, LeafDesc } from "../render.js";
21
23
  import {
24
+ CHANGE_BAR,
25
+ changeElement,
26
+ type FloatGeometry,
27
+ floatElements,
28
+ floatGeometry,
22
29
  fontStack,
30
+ type ImageSource,
31
+ imageSource,
23
32
  latin,
24
33
  lineHeight,
25
34
  markerElement,
@@ -27,12 +36,26 @@ import {
27
36
  opaqueText,
28
37
  PX_PER_TWIP,
29
38
  parseOpaque,
39
+ pictureElement,
40
+ type ReviewView,
30
41
  styleParagraph,
31
42
  styleRun,
32
43
  tagOf,
33
44
  WORD_PAGE_BREAK_ATTR,
34
45
  } from "./blocks.js";
35
46
 
47
+ const REVIEW_MARKS = new Set(["insertion", "deletion", "formatChange"]);
48
+
49
+ /** Whether a paragraph has tracked changes: in its text, its mark or its formatting. */
50
+ function hasChanges(node: ModelNode): boolean {
51
+ if (node.attrs.revision || node.attrs.formatChange) return true;
52
+ let found = false;
53
+ node.forEach((child) => {
54
+ if (child.marks.some((m) => REVIEW_MARKS.has(m.type.name))) found = true;
55
+ });
56
+ return found;
57
+ }
58
+
36
59
  /** What the page flow needs to know about a v3 block. */
37
60
  export interface WordInfo {
38
61
  /** Space before and after in CSS px (Word adds them: the flow places them). */
@@ -53,6 +76,12 @@ export interface WordBlockDesc extends BlockDesc {
53
76
  readonly key: string;
54
77
  }
55
78
 
79
+ /**
80
+ * A floating picture's holder (drawn first in its paragraph, the view's own DOM) to its anchor:
81
+ * the empty, non-editable span at the picture's place in the text, which positions map to.
82
+ */
83
+ export const FLOAT_ANCHORS = new WeakMap<Element, HTMLElement>();
84
+
56
85
  /**
57
86
  * Renders the blocks of one v3 document for the editable view. `prepare` runs before each
58
87
  * render: list numbers and comment ranges depend on the blocks before.
@@ -63,6 +92,10 @@ export class WordRenderer {
63
92
  readonly #ratio: (family: string) => number;
64
93
  /** For the clipboard (`clipboardBlocks`): links as links, list numbers as Word's HTML has them. */
65
94
  readonly #clipboard: boolean;
95
+ /** How tracked changes show. */
96
+ readonly #review: ReviewView;
97
+ /** Where pictures' images are shown from. */
98
+ readonly #image: ImageSource | undefined;
66
99
  #markers: (ListMarker | null)[] = [];
67
100
  /** Comment ranges open at the start of each block. */
68
101
  #comments: number[][] = [];
@@ -72,23 +105,30 @@ export class WordRenderer {
72
105
  doc: Document,
73
106
  ratio: (family: string) => number,
74
107
  clipboard = false,
108
+ review: ReviewView = "markup",
109
+ image?: ImageSource,
75
110
  ) {
76
111
  this.#context = context;
77
112
  this.#doc = doc;
78
113
  this.#ratio = ratio;
79
114
  this.#clipboard = clipboard;
115
+ this.#review = review;
116
+ this.#image = image ?? imageSource(context.envelope.resources);
80
117
  }
81
118
 
82
119
  get context(): WordContext {
83
120
  return this.#context;
84
121
  }
85
122
 
86
- /** Numbering and comment state per top-level node of `doc`. */
87
- prepare(doc: ModelNode): void {
123
+ /**
124
+ * 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).
126
+ */
127
+ prepare(blocks: readonly ModelNode[]): void {
88
128
  const attrs: Record<string, unknown>[] = [];
89
129
  const comments: number[][] = [];
90
130
  const open = new Set<number>();
91
- doc.forEach((node) => {
131
+ for (const node of blocks) {
92
132
  attrs.push(node.type.name === "paragraph" ? node.attrs : { numbering: { id: 0 } });
93
133
  comments.push([...open]);
94
134
  node.forEach((child) => {
@@ -96,27 +136,35 @@ export class WordRenderer {
96
136
  if (child.type.name === "commentStart") open.add(id);
97
137
  else if (child.type.name === "commentEnd") open.delete(id);
98
138
  });
99
- });
139
+ }
100
140
  this.#markers = this.#context.resolver.markers(attrs);
101
141
  this.#comments = comments;
102
142
  }
103
143
 
104
- /** Whether the top-level block at `index` shows a list number. */
144
+ /** Whether the block at `index` (of those prepared) shows a list number. */
105
145
  hasMarker(index: number): boolean {
106
146
  return !!this.#markers[index];
107
147
  }
108
148
 
109
- /** What a block's rendering depends on at `index`, besides its node. */
110
- key(index: number): string {
111
- return `${this.#markers[index]?.text ?? ""}|${(this.#comments[index] ?? []).join(" ")}`;
149
+ /** What a block's rendering depends on at `index`, besides its node (and its cell's format). */
150
+ key(index: number, cell?: CellFormat | null): string {
151
+ const inCell = cell ? `|${cell.style ?? ""}:${cell.conditions.join(",")}` : "";
152
+ return `${this.#markers[index]?.text ?? ""}|${(this.#comments[index] ?? []).join(" ")}${inCell}`;
112
153
  }
113
154
 
114
- render(node: ModelNode, index: number, splits: readonly number[] = []): WordBlockDesc {
155
+ /** A block; `cell` is the format of the table cell it is in, if any. */
156
+ render(
157
+ node: ModelNode,
158
+ index: number,
159
+ splits: readonly number[] = [],
160
+ cell?: CellFormat | null,
161
+ ): WordBlockDesc {
115
162
  if (node.type.name !== "paragraph") return this.#opaque(node, index);
116
163
  const { resolver } = this.#context;
117
- const { paragraph, run } = resolver.paragraph(node.attrs);
164
+ const { paragraph, run } = resolver.paragraph(node.attrs, cell ?? undefined);
118
165
  const line = (r: RunFormat) => lineHeight(paragraph, r, this.#ratio(fontStack(latin(r))));
119
166
  const doc = this.#doc;
167
+ const changed = this.#review !== "final" && hasChanges(node);
120
168
  const fragments = [0, ...splits].map((_, i, all) => {
121
169
  const fragment = doc.createElement(tagOf(paragraph));
122
170
  styleParagraph(fragment, paragraph);
@@ -130,6 +178,7 @@ export class WordRenderer {
130
178
  if (i < all.length - 1 && fragment.style.textAlign === "justify")
131
179
  fragment.style.textAlignLast = "justify";
132
180
  }
181
+ if (changed && !this.#clipboard) fragment.style.boxShadow = CHANGE_BAR;
133
182
  return fragment;
134
183
  });
135
184
  const dom = fragments[0] as HTMLElement;
@@ -148,6 +197,9 @@ export class WordRenderer {
148
197
  return fragments[i] as HTMLElement;
149
198
  };
150
199
  const leaves: LeafDesc[] = [];
200
+ // Floating pictures go first in the fragment their anchor is in, in order.
201
+ const floats = new Map<HTMLElement, HTMLElement[]>();
202
+ let geometry: FloatGeometry | undefined;
151
203
  const comments = new Set(this.#comments[index] ?? []);
152
204
  node.forEach((child, offset) => {
153
205
  const name = child.type.name;
@@ -155,7 +207,7 @@ export class WordRenderer {
155
207
  if (name === "commentEnd") comments.delete(child.attrs.id as number);
156
208
  const leafElement = (element: HTMLElement) => {
157
209
  leaves.push({ dom: element, offset, size: child.nodeSize });
158
- fragmentAt(offset).append(this.#wrap(element, child.marks, comments.size > 0));
210
+ fragmentAt(offset).append(this.#wrap(element, child.marks, comments));
159
211
  };
160
212
  switch (name) {
161
213
  case "text":
@@ -176,7 +228,24 @@ export class WordRenderer {
176
228
  const tab = doc.createTextNode("\t");
177
229
  span.append(tab);
178
230
  leaves.push({ dom: tab, offset, size: 1 });
179
- fragmentAt(offset).append(this.#wrap(span, child.marks, comments.size > 0));
231
+ fragmentAt(offset).append(this.#wrap(span, child.marks, comments));
232
+ return;
233
+ }
234
+ case "picture": {
235
+ // Not editable inside (no browser resize handles); one position, like opaque content.
236
+ const span = doc.createElement("span");
237
+ span.setAttribute("contenteditable", "false");
238
+ if (child.attrs.float && !this.#clipboard) {
239
+ // Floating: drawn at the fragment's start (ADR-0006), its place in the text an
240
+ // empty anchor.
241
+ geometry ??= floatGeometry(this.#context.envelope.section);
242
+ const { nodes, holder } = floatElements(child.attrs, doc, this.#image, geometry);
243
+ for (const node of nodes) node.setAttribute("contenteditable", "false");
244
+ FLOAT_ANCHORS.set(holder, span);
245
+ const fragment = fragmentAt(offset);
246
+ floats.set(fragment, [...(floats.get(fragment) ?? []), ...nodes]);
247
+ } else span.append(pictureElement(child.attrs, doc, this.#image));
248
+ leafElement(span);
180
249
  return;
181
250
  }
182
251
  case "opaqueInline": {
@@ -206,16 +275,21 @@ export class WordRenderer {
206
275
  leaves.push({ dom: leaf, offset: from, size: to - from });
207
276
  const span = this.#run(run, child.marks, line);
208
277
  span.append(leaf);
209
- fragmentAt(from).append(this.#wrap(span, child.marks, comments.size > 0));
278
+ fragmentAt(from).append(this.#wrap(span, child.marks, comments));
210
279
  from = to;
211
280
  }
212
281
  });
282
+ for (const [fragment, nodes] of floats) fragment.prepend(...nodes);
213
283
  // An empty paragraph, or one ending in a line break, shows its last line; after a page
214
284
  // break the paragraph mark stays on the break's line, as in Word.
215
285
  let last: ModelNode | null = null;
216
286
  for (let i = node.childCount - 1; i >= 0 && !last; i--) {
217
287
  const child = node.child(i);
218
- if (!["bookmarkStart", "bookmarkEnd", "commentStart", "commentEnd"].includes(child.type.name))
288
+ // A floating picture is not in the line: a paragraph holding only one shows its empty line.
289
+ if (
290
+ !["bookmarkStart", "bookmarkEnd", "commentStart", "commentEnd"].includes(child.type.name) &&
291
+ !(child.type.name === "picture" && child.attrs.float)
292
+ )
219
293
  last = child;
220
294
  }
221
295
  if (!last || last.type.name === "hardBreak" || last.type.name === "columnBreak")
@@ -231,6 +305,13 @@ export class WordRenderer {
231
305
  style: paragraph.style,
232
306
  contextual: paragraph.contextualSpacing,
233
307
  };
308
+ if (cell && !this.#clipboard) {
309
+ // In a cell its spacing is its margins (the page flow spaces top-level blocks); a
310
+ // fragment continued on the next page has none at the split.
311
+ // shortcut: contextual spacing between paragraphs in a cell is not applied.
312
+ dom.style.marginTop = `${word.before}px`;
313
+ (fragments[fragments.length - 1] as HTMLElement).style.marginBottom = `${word.after}px`;
314
+ }
234
315
  if (this.#clipboard) {
235
316
  // The flow places the spacing in the editor; elsewhere it is the paragraph's margins.
236
317
  dom.style.marginTop = `${word.before}px`;
@@ -242,7 +323,7 @@ export class WordRenderer {
242
323
  dom.setAttribute("style", `${styleOf(dom)}mso-list:${list}`);
243
324
  }
244
325
  }
245
- return { node, dom, fragments, splits, leaves, word, key: this.key(index) };
326
+ return { node, dom, fragments, splits, leaves, word, key: this.key(index, cell) };
246
327
  }
247
328
 
248
329
  /** A span for text with `marks` over its paragraph's run formatting. */
@@ -259,17 +340,22 @@ export class WordRenderer {
259
340
  }
260
341
 
261
342
  /** Tracked changes and comment shading around a rendered run. */
262
- #wrap(element: HTMLElement, marks: readonly Mark[], commented: boolean): HTMLElement {
263
- if (commented && !this.#clipboard && !element.style.backgroundColor)
264
- element.style.backgroundColor = "rgba(255, 213, 79, 0.35)";
343
+ #wrap(element: HTMLElement, marks: readonly Mark[], comments: ReadonlySet<number>): HTMLElement {
344
+ if (comments.size && !this.#clipboard) {
345
+ // The comments whose range holds this text: the comments pane finds and marks it.
346
+ element.dataset.foliComments = [...comments].join(" ");
347
+ if (!element.style.backgroundColor)
348
+ element.style.backgroundColor = "rgba(255, 213, 79, 0.35)";
349
+ }
265
350
  let outer = element;
266
- const change = marks.find((m) => m.type.name === "insertion" || m.type.name === "deletion");
351
+ // Text inserted, then deleted, shows as deleted (in the deleting author's color).
352
+ const change =
353
+ marks.find((m) => m.type.name === "deletion") ??
354
+ marks.find((m) => m.type.name === "insertion");
267
355
  if (change) {
356
+ const { author, date } = change.attrs as { author: string; date: string | null };
268
357
  const inserted = change.type.name === "insertion";
269
- outer = this.#doc.createElement(inserted ? "ins" : "del");
270
- if (change.attrs.author) outer.title = String(change.attrs.author);
271
- outer.style.color = "#B5082E";
272
- outer.style.textDecorationLine = inserted ? "underline" : "line-through";
358
+ outer = changeElement(this.#doc, inserted, author, date, this.#review);
273
359
  outer.append(element);
274
360
  }
275
361
  // Schema v3 keeps any target (`file:`…): only a safe one is a link in the page or on the
@@ -286,7 +372,15 @@ export class WordRenderer {
286
372
 
287
373
  /** An opaque block, shown from its XML: a block leaf, not editable inside. */
288
374
  #opaque(node: ModelNode, index: number): WordBlockDesc {
289
- const shown = opaqueBlock(node.toJSON(), index, this.#context.resolver, this.#doc, this.#ratio);
375
+ const shown = opaqueBlock(
376
+ node.toJSON(),
377
+ index,
378
+ this.#context.resolver,
379
+ this.#doc,
380
+ this.#ratio,
381
+ this.#image,
382
+ floatGeometry(this.#context.envelope.section),
383
+ );
290
384
  const dom = shown.element;
291
385
  dom.setAttribute("contenteditable", "false");
292
386
  return {
@@ -329,7 +423,11 @@ export function clipboardBlocks(
329
423
  ratio: (family: string) => number,
330
424
  ): HTMLElement[] {
331
425
  const renderer = new WordRenderer(context, ownerDocument, ratio, true);
332
- renderer.prepare(doc);
426
+ const top: ModelNode[] = [];
427
+ doc.forEach((node) => {
428
+ top.push(node);
429
+ });
430
+ renderer.prepare(top);
333
431
  return nodes.map((node, i) => {
334
432
  const { dom } = renderer.render(node, first < 0 ? -1 : first + i);
335
433
  for (const element of [dom, ...dom.querySelectorAll("*")])
package/src/word/pages.ts CHANGED
@@ -29,6 +29,11 @@ export interface DocumentPages {
29
29
  * where the top-level node at `index` starts, as Word numbers lines; undefined if not shown.
30
30
  */
31
31
  lineOf(index: number): number | undefined;
32
+ /**
33
+ * Every paragraph in table cells, in document order (nested tables' included; none for a cell
34
+ * a vertical merge covers, as Word lists none), with the page (0-based) it starts on.
35
+ */
36
+ cellParagraphs(): { page: number; text: string }[];
32
37
  /** Removes the pages. */
33
38
  destroy(): void;
34
39
  }
@@ -73,6 +78,8 @@ function createPage(doc: Document, g: Geometry): { page: HTMLElement; body: HTML
73
78
  const { style } = page;
74
79
  style.boxSizing = "border-box";
75
80
  style.position = "relative";
81
+ // The stacking context pictures behind text are drawn in (over the page's background).
82
+ style.isolation = "isolate";
76
83
  style.width = `${g.width}px`;
77
84
  style.height = `${g.height}px`;
78
85
  style.padding = `${g.top}px ${g.right}px ${g.bottom}px ${g.left}px`;
@@ -155,6 +162,23 @@ export function lineBottoms(element: HTMLElement): number[] {
155
162
  return bottoms;
156
163
  }
157
164
 
165
+ /**
166
+ * A table block's line ends without those inside a row that may not split (`cantSplit`), unless
167
+ * the row is taller than a page.
168
+ */
169
+ function keepRows(element: HTMLElement, bottoms: number[], pageHeight: number): number[] {
170
+ const rows = element.querySelectorAll(":scope > table > tbody > tr[data-foli-cant-split]");
171
+ if (!rows.length) return bottoms;
172
+ const top = element.getBoundingClientRect().top;
173
+ const kept = [...rows]
174
+ .map((row) => {
175
+ const box = row.getBoundingClientRect();
176
+ return [box.top - top, box.bottom - top] as const;
177
+ })
178
+ .filter(([from, to]) => to - from <= pageHeight);
179
+ return bottoms.filter((y) => !kept.some(([from, to]) => y > from + 0.5 && y < to - 0.5));
180
+ }
181
+
158
182
  /** The height of a table's leading header rows (repeated on each page it continues on), or 0. */
159
183
  function headerHeight(element: HTMLElement): number {
160
184
  let bottom = 0;
@@ -214,6 +238,7 @@ export function renderDocument(
214
238
  const firstPage = new Map<number, number>();
215
239
  /** Every fragment placed, in order: its page and how many lines it shows (measured lazily). */
216
240
  const placements: { page: number; nodes: number[] | null; lines: () => number }[] = [];
241
+ const cellPages: { page: number; text: string }[] = [];
217
242
  for (const group of groups) {
218
243
  const g = group.geometry;
219
244
  // Measure in a page of the section's width, out of view.
@@ -224,16 +249,30 @@ export function renderDocument(
224
249
  container.append(measuring.page);
225
250
  for (const block of group.blocks) measuring.body.append(block.element);
226
251
  const lines = new Map<WordBlock, number[]>();
252
+ const pageHeight = g.height - g.top - g.bottom;
227
253
  const linesOf = (block: WordBlock) => {
228
254
  let value = lines.get(block);
229
255
  if (!value) {
230
- value = lineBottoms(block.element);
256
+ value = keepRows(block.element, lineBottoms(block.element), pageHeight);
231
257
  lines.set(block, value);
232
258
  }
233
259
  return value;
234
260
  };
261
+ // Each cell paragraph's top in its block, measured while the blocks are laid out whole.
262
+ const cellTops = new Map<WordBlock, { top: number; text: string }[]>();
263
+ for (const block of group.blocks) {
264
+ const cells = block.element.querySelectorAll("[data-foli-cell]");
265
+ if (!cells.length) continue;
266
+ const top = block.element.getBoundingClientRect().top;
267
+ cellTops.set(
268
+ block,
269
+ [...cells].map((cell) => ({
270
+ top: cell.getBoundingClientRect().top - top,
271
+ text: cell.textContent ?? "",
272
+ })),
273
+ );
274
+ }
235
275
  const headers = new Map<WordBlock, number>();
236
- const pageHeight = g.height - g.top - g.bottom;
237
276
  const boxes: BlockBox[] = group.blocks.map((block, i) => {
238
277
  const height = block.element.getBoundingClientRect().height;
239
278
  const repeat = block.element.querySelector("tr") ? headerHeight(block.element) : 0;
@@ -248,6 +287,8 @@ export function renderDocument(
248
287
  marginTop: block.before,
249
288
  marginBottom: block.after,
250
289
  repeat,
290
+ // A table splits at any line: no widow and orphan control across its rows.
291
+ anyLine: !!block.element.querySelector(":scope > table"),
251
292
  keepWithNext: block.keepNext,
252
293
  lines: () => (kept ? [height] : linesOf(block)),
253
294
  breaksAfter: () => {
@@ -337,6 +378,15 @@ export function renderDocument(
337
378
  : fragment.toLine) - fragment.fromLine,
338
379
  });
339
380
  });
381
+ // Its cell paragraphs: on the page of the fragment their top is in.
382
+ for (const cell of cellTops.get(block) ?? []) {
383
+ let at = placed[0]?.page ?? 0;
384
+ for (const fragment of placed) {
385
+ const start = fragment.fromLine ? (bottoms[fragment.fromLine - 1] ?? 0) : 0;
386
+ if (cell.top + 0.5 >= start) at = fragment.page;
387
+ }
388
+ cellPages.push({ page: pages.length + at, text: cell.text });
389
+ }
340
390
  const first = placed[0];
341
391
  if (first) for (const index of block.nodes) firstPage.set(index, pages.length + first.page);
342
392
  });
@@ -365,6 +415,7 @@ export function renderDocument(
365
415
  }
366
416
  return firstLine.get(index);
367
417
  },
418
+ cellParagraphs: () => cellPages,
368
419
  destroy: () => {
369
420
  for (const page of pages) page.remove();
370
421
  },