@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.
@@ -11,6 +11,7 @@ import {
11
11
  type NodeJSON,
12
12
  type ParagraphFormat,
13
13
  Resolver,
14
+ type ResourceJSON,
14
15
  type RunFormat,
15
16
  type SectionJSON,
16
17
  } from "@folijs/core";
@@ -20,12 +21,312 @@ export const WORD_PAGE_BREAK_ATTR = "data-page-break";
20
21
 
21
22
  /** CSS px per twip (1/1440 inch; CSS: 96 px per inch). */
22
23
  export const PX_PER_TWIP = 96 / 1440;
24
+ /** EMU (DrawingML's unit: 914 400 per inch) per CSS px. */
25
+ export const EMU_PER_PX = 914_400 / 96;
26
+
27
+ /** The URL to show a picture's image from (its resource key), if one is known. */
28
+ export type ImageSource = (key: string) => string | undefined;
29
+
30
+ /** Marks a picture's element (its resource key). */
31
+ export const PICTURE_ATTR = "data-foli-picture";
32
+
33
+ /** The accessible name of a picture with no alt text that is not decorative. */
34
+ export const NO_ALT_LABEL = "Picture without alt text";
35
+
36
+ /**
37
+ * The URL a resource gives on its own: an image `data:` URL, or a web or `blob:` URL; none for
38
+ * an image in a package part (the app's resolver gives one) or anything else.
39
+ */
40
+ export function ownImageUrl(resource: ResourceJSON | undefined): string | undefined {
41
+ const data = resource?.data;
42
+ if (data && /^data:image\//i.test(data)) return data;
43
+ const url = resource?.url;
44
+ return url && /^(https?|blob):/i.test(url) ? url : undefined;
45
+ }
46
+
47
+ /**
48
+ * A picture as shown: its image at its size, or, when no URL is known for it, a box of that size
49
+ * with its alt text. A picture with no alt text that is not decorative is marked (`data-foli-
50
+ * no-alt`); a decorative one has an empty alt.
51
+ */
52
+ export function pictureElement(
53
+ attrs: Record<string, unknown>,
54
+ doc: Document,
55
+ image?: ImageSource,
56
+ ): HTMLElement {
57
+ const key = String(attrs.resource ?? "");
58
+ const width = `${Number(attrs.width) / EMU_PER_PX}px`;
59
+ const height = `${Number(attrs.height) / EMU_PER_PX}px`;
60
+ const decorative = attrs.decorative === true;
61
+ const own = String(attrs.alt ?? "");
62
+ // Only a decorative picture is silent; one missing its alt text says so.
63
+ const alt = decorative ? "" : own || NO_ALT_LABEL;
64
+ const src = image?.(key);
65
+ let element: HTMLElement;
66
+ if (src) {
67
+ const img = doc.createElement("img");
68
+ img.src = src;
69
+ img.alt = alt;
70
+ img.draggable = false;
71
+ // A web URL in a document is fetched as it is shown: no referrer to go with it.
72
+ img.referrerPolicy = "no-referrer";
73
+ element = img;
74
+ } else {
75
+ element = doc.createElement("span");
76
+ element.setAttribute("role", "img");
77
+ if (alt) element.setAttribute("aria-label", alt);
78
+ else element.setAttribute("aria-hidden", "true");
79
+ element.style.boxSizing = "border-box";
80
+ element.style.border = "1px dashed GrayText";
81
+ }
82
+ element.setAttribute(PICTURE_ATTR, key);
83
+ if (!own && !decorative) element.dataset.foliNoAlt = "";
84
+ if (attrs.title) element.title = String(attrs.title);
85
+ // In the line at its size, whatever the app's CSS says of images (`display: block`…).
86
+ const style = element.style;
87
+ style.display = src ? "inline" : "inline-block";
88
+ style.verticalAlign = "baseline";
89
+ style.maxWidth = "none";
90
+ style.maxHeight = "none";
91
+ style.width = width;
92
+ style.height = height;
93
+ return element;
94
+ }
95
+
96
+ /** Marks the element holding a floating picture (its wrapping), drawn at its paragraph's start. */
97
+ export const FLOAT_ATTR = "data-foli-float";
98
+
99
+ /** A section's page, in CSS px: what a floating picture is positioned against. */
100
+ export interface FloatGeometry {
101
+ readonly pageWidth: number;
102
+ readonly pageHeight: number;
103
+ readonly marginLeft: number;
104
+ readonly marginTop: number;
105
+ readonly textWidth: number;
106
+ readonly textHeight: number;
107
+ }
108
+
109
+ /** The page geometry of `section` (Word's Letter page and margins where it does not say). */
110
+ export function floatGeometry(section: SectionJSON | undefined): FloatGeometry {
111
+ const m = section?.margins ?? {};
112
+ const width = section?.pageSize?.width ?? 12_240;
113
+ const height = section?.pageSize?.height ?? 15_840;
114
+ const left = (m.left ?? 1440) + (m.gutter ?? 0);
115
+ const top = Math.abs(m.top ?? 1440);
116
+ return {
117
+ pageWidth: width * PX_PER_TWIP,
118
+ pageHeight: height * PX_PER_TWIP,
119
+ marginLeft: left * PX_PER_TWIP,
120
+ marginTop: top * PX_PER_TWIP,
121
+ textWidth: (width - left - (m.right ?? 1440)) * PX_PER_TWIP,
122
+ textHeight: (height - top - Math.abs(m.bottom ?? 1440)) * PX_PER_TWIP,
123
+ };
124
+ }
125
+
126
+ type FloatPosition = { relativeTo: string; offset?: number; align?: string };
127
+
128
+ /** Where a float's position is measured from, and the box its alignment is in (px). */
129
+ function horizontalBox(relativeTo: string, g: FloatGeometry): [start: number, size: number] {
130
+ const right = g.pageWidth - g.marginLeft - g.textWidth;
131
+ switch (relativeTo) {
132
+ case "page":
133
+ return [0, g.pageWidth];
134
+ case "leftMargin":
135
+ case "insideMargin":
136
+ return [0, g.marginLeft];
137
+ case "rightMargin":
138
+ case "outsideMargin":
139
+ return [g.marginLeft + g.textWidth, right];
140
+ default:
141
+ // margin, column, character (shortcut: the column).
142
+ return [g.marginLeft, g.textWidth];
143
+ }
144
+ }
145
+
146
+ function verticalBox(relativeTo: string, g: FloatGeometry): [start: number, size: number] {
147
+ const bottom = g.pageHeight - g.marginTop - g.textHeight;
148
+ switch (relativeTo) {
149
+ case "page":
150
+ return [0, g.pageHeight];
151
+ case "topMargin":
152
+ case "insideMargin":
153
+ return [0, g.marginTop];
154
+ case "bottomMargin":
155
+ case "outsideMargin":
156
+ return [g.pageHeight - bottom, bottom];
157
+ default:
158
+ return [g.marginTop, g.textHeight];
159
+ }
160
+ }
161
+
162
+ /** Where `size` px goes in `[start, start + box)` by offset (EMU) or alignment. */
163
+ function placed(position: FloatPosition, [start, box]: [number, number], size: number): number {
164
+ if (typeof position.offset === "number") return start + position.offset / EMU_PER_PX;
165
+ const { align } = position;
166
+ if (align === "right" || align === "bottom" || align === "outside") return start + box - size;
167
+ if (align === "center") return start + (box - size) / 2;
168
+ return start;
169
+ }
170
+
171
+ /** Where a float's left edge is, in px from the column's left edge. */
172
+ function floatLeft(h: FloatPosition, width: number, g: FloatGeometry): number {
173
+ return placed(h, horizontalBox(h.relativeTo, g), width) - g.marginLeft;
174
+ }
175
+
176
+ /**
177
+ * Where a float's top edge is: from its paragraph's top (`paragraph`), or from the page's top
178
+ * (`page`) for a position against the page or its margins.
179
+ */
180
+ function floatTop(
181
+ v: FloatPosition,
182
+ height: number,
183
+ g: FloatGeometry,
184
+ ): { paragraph?: number; page?: number } {
185
+ if (v.relativeTo === "paragraph" || v.relativeTo === "line")
186
+ return { paragraph: typeof v.offset === "number" ? v.offset / EMU_PER_PX : 0 };
187
+ return { page: placed(v, verticalBox(v.relativeTo, g), height) };
188
+ }
189
+
190
+ /**
191
+ * A floating picture (10.9, ADR-0006) as CSS floats lay it out, put first in its anchor
192
+ * paragraph: `holder` holds the picture (`FLOAT_ATTR`), `nodes` go in the paragraph (a
193
+ * zero-width spacer float before it gives its offset from the paragraph's top).
194
+ * - Square (tight and through shown as square): a float on the side the picture is on, its
195
+ * distance from the text as its margin; text goes on the other side only.
196
+ * - Top and bottom: a float as wide as the paragraph, the picture in it at its position.
197
+ * - Behind and in front of text: absolutely positioned on the page (z-index -1 or 1; the page is
198
+ * the containing block and its own stacking context).
199
+ * shortcut: a wrapping picture placed against the page or its margins vertically is drawn at
200
+ * its paragraph's top; horizontal positions are against the paragraph's box (its indents in);
201
+ * all against `geometry` (one section's page), not each page's. A float's top is never above an
202
+ * earlier float's (CSS), and `clear` stacks it below earlier floats on its side: several floats
203
+ * in a paragraph, or one above a float of an earlier paragraph, add their offsets down and do
204
+ * not sit side by side.
205
+ */
206
+ export function floatElements(
207
+ attrs: Record<string, unknown>,
208
+ doc: Document,
209
+ image: ImageSource | undefined,
210
+ geometry: FloatGeometry,
211
+ ): { nodes: HTMLElement[]; holder: HTMLElement } {
212
+ const float = attrs.float as {
213
+ horizontal: FloatPosition;
214
+ vertical: FloatPosition;
215
+ wrap: string;
216
+ side?: string;
217
+ distance?: { top?: number; bottom?: number; left?: number; right?: number };
218
+ };
219
+ const width = Number(attrs.width) / EMU_PER_PX;
220
+ const height = Number(attrs.height) / EMU_PER_PX;
221
+ const distance = (side: "top" | "bottom" | "left" | "right") =>
222
+ (float.distance?.[side] ?? 0) / EMU_PER_PX;
223
+ const picture = pictureElement(attrs, doc, image);
224
+ picture.style.display = "block";
225
+ const holder = doc.createElement("span");
226
+ holder.setAttribute(FLOAT_ATTR, float.wrap);
227
+ holder.append(picture);
228
+ const style = holder.style;
229
+ style.display = "block";
230
+ const x = floatLeft(float.horizontal, width, geometry);
231
+ const top = floatTop(float.vertical, height, geometry);
232
+ if (float.wrap === "behind" || float.wrap === "inFront") {
233
+ style.position = "absolute";
234
+ style.zIndex = float.wrap === "behind" ? "-1" : "1";
235
+ style.left = `${geometry.marginLeft + x}px`;
236
+ // Against the paragraph: where it would be (its static position), moved by its offset.
237
+ if (top.page !== undefined) style.top = `${top.page}px`;
238
+ else style.marginTop = `${top.paragraph}px`;
239
+ return { nodes: [holder], holder };
240
+ }
241
+ // Its distance from the text above and below as its margins: lines there go around it too.
242
+ const above = distance("top");
243
+ const down = (top.paragraph ?? 0) - above;
244
+ const spacer = doc.createElement("span");
245
+ spacer.setAttribute("aria-hidden", "true");
246
+ spacer.style.width = "0";
247
+ spacer.style.height = `${Math.max(0, down)}px`;
248
+ style.marginTop = `${above + Math.min(0, down)}px`;
249
+ style.marginBottom = `${distance("bottom")}px`;
250
+ if (float.wrap === "topAndBottom") {
251
+ spacer.style.float = "left";
252
+ style.float = "left";
253
+ style.clear = "both";
254
+ style.width = "100%";
255
+ picture.style.marginLeft = `${x}px`;
256
+ return { nodes: [spacer, holder], holder };
257
+ }
258
+ // Text on the side with more room (or the side `side` names): the picture floats on the other.
259
+ const right =
260
+ float.side === "left" || (float.side !== "right" && x + width / 2 > geometry.textWidth / 2);
261
+ const side = right ? "right" : "left";
262
+ spacer.style.float = side;
263
+ style.float = side;
264
+ style.clear = side;
265
+ if (right) {
266
+ style.marginRight = `${geometry.textWidth - x - width}px`;
267
+ style.marginLeft = `${distance("left")}px`;
268
+ } else {
269
+ style.marginLeft = `${x}px`;
270
+ style.marginRight = `${distance("right")}px`;
271
+ }
272
+ return { nodes: [spacer, holder], holder };
273
+ }
23
274
 
24
275
  /** Which version of tracked changes to show. */
25
- export type ReviewView = "markup" | "final";
276
+ /** How tracked changes show (`@folijs/core`'s, for `renderDocument` too). */
277
+ export type { ReviewView } from "@folijs/core";
278
+
279
+ import type { ReviewView } from "@folijs/core";
280
+
281
+ /** Colors for the authors of changes (contrast 4.5:1 or more on white), picked by name. */
282
+ const AUTHOR_COLORS = [
283
+ "#B5082E",
284
+ "#1F5FAD",
285
+ "#2E7D32",
286
+ "#8E24AA",
287
+ "#A64B00",
288
+ "#00737F",
289
+ "#AD1457",
290
+ "#5D4037",
291
+ ];
292
+
293
+ /** The color of `author`'s changes: always the same for a name. */
294
+ export function authorColor(author: string): string {
295
+ let hash = 0;
296
+ for (const c of author) hash = (hash * 31 + (c.codePointAt(0) ?? 0)) >>> 0;
297
+ return AUTHOR_COLORS[hash % AUTHOR_COLORS.length] as string;
298
+ }
299
+
300
+ /** The bar beside a paragraph with changes (`markup` and `simple`), drawn in the margin. */
301
+ export const CHANGE_BAR = "-4px 0 0 0 #6B6B6B";
302
+
303
+ /**
304
+ * The element around an inserted or deleted run: `ins` or `del` (named for screen readers by
305
+ * its title), styled for `review`. Deleted text not shown is hidden, not left out: the editable
306
+ * view maps positions through it.
307
+ */
308
+ export function changeElement(
309
+ doc: Document,
310
+ inserted: boolean,
311
+ author: string,
312
+ date: string | null,
313
+ review: ReviewView,
314
+ ): HTMLElement {
315
+ const element = doc.createElement(inserted ? "ins" : "del");
316
+ const when = date ? `, ${date.slice(0, 10)}` : "";
317
+ element.title = `${inserted ? "Inserted" : "Deleted"} by ${author || "an unknown author"}${when}`;
318
+ if (review === "markup") {
319
+ element.style.color = authorColor(author);
320
+ element.style.textDecorationLine = inserted ? "underline" : "line-through";
321
+ } else {
322
+ element.style.textDecorationLine = "none";
323
+ if (!inserted) element.style.display = "none";
324
+ }
325
+ return element;
326
+ }
26
327
 
27
328
  export interface BlockOptions {
28
- /** `markup` (the default): insertions underlined, deletions struck through. `final`: as if accepted. */
329
+ /** `markup` (the default): insertions underlined, deletions struck through; `simple`, `final`: as if accepted. */
29
330
  review?: ReviewView;
30
331
  /**
31
332
  * The ratio of a font's normal line height to its size (`fontFamily`: a CSS font-family
@@ -33,6 +334,26 @@ export interface BlockOptions {
33
334
  * Measured by the page layout; 1.2 when nothing measures (no layout engine).
34
335
  */
35
336
  lineRatio?: (fontFamily: string) => number;
337
+ /**
338
+ * The URL to show a picture's image from (`key` in `resources`): the app's (a package part's
339
+ * object URL…); `null` (or "") shows the picture's box. Left out, or undefined for a key: the
340
+ * resource's own image `data:` URL or web URL (fetched as it is shown).
341
+ */
342
+ resource?: (key: string, resource: ResourceJSON) => string | null | undefined;
343
+ }
344
+
345
+ /** The source for a document's pictures: the app's URL, else the resource's own. */
346
+ export function imageSource(
347
+ resources: Readonly<Record<string, ResourceJSON>> | undefined,
348
+ resolve?: (key: string, resource: ResourceJSON) => string | null | undefined,
349
+ ): ImageSource {
350
+ return (key) => {
351
+ const resource = resources?.[key];
352
+ if (!resource) return undefined;
353
+ const url = resolve?.(key, resource);
354
+ // The app's answer stands, a refusal (null, "") included.
355
+ return url === undefined ? ownImageUrl(resource) : url || undefined;
356
+ };
36
357
  }
37
358
 
38
359
  /** A rendered block and what the page flow needs to know about it. */
@@ -286,15 +607,18 @@ export function renderBlocks(
286
607
  return value;
287
608
  };
288
609
  const resolver = new Resolver(document);
610
+ const image = imageSource(document.resources, options.resource);
611
+ // shortcut: floating pictures are placed against the last section's page.
612
+ const geometry = floatGeometry(document.section);
289
613
  const content = document.content.content ?? [];
290
614
  const attrsOf = (node: NodeJSON) => (node.attrs ?? {}) as Record<string, unknown>;
291
- // In the final view a paragraph whose mark was deleted joins the next paragraph (not a
292
- // table, and the document's last mark cannot be deleted).
615
+ // In the final and simple views a paragraph whose mark was deleted joins the next paragraph
616
+ // (not a table, and the document's last mark cannot be deleted).
293
617
  const joins = (index: number) => {
294
618
  const node = content[index];
295
619
  const revision = node && (attrsOf(node).revision as { deletion?: unknown } | null | undefined);
296
620
  return (
297
- review === "final" &&
621
+ review !== "markup" &&
298
622
  node?.type === "paragraph" &&
299
623
  !!revision?.deletion &&
300
624
  content[index + 1]?.type === "paragraph"
@@ -313,7 +637,7 @@ export function renderBlocks(
313
637
 
314
638
  content.forEach((node, index) => {
315
639
  if (node.type !== "paragraph") {
316
- blocks.push(opaqueBlock(node, index, resolver, doc, ratio));
640
+ blocks.push(opaqueBlock(node, index, resolver, doc, ratio, image, geometry));
317
641
  return;
318
642
  }
319
643
  const attrs = attrsOf(node);
@@ -345,6 +669,8 @@ export function renderBlocks(
345
669
  review,
346
670
  comments,
347
671
  ratio,
672
+ image,
673
+ geometry,
348
674
  });
349
675
  // An empty paragraph, or one ending in a line break, shows its last (empty) line; after a
350
676
  // page break the paragraph mark stays on the break's line, as in Word.
@@ -452,6 +778,9 @@ interface InlineContext {
452
778
  review: ReviewView;
453
779
  comments: Set<number>;
454
780
  ratio: (family: string) => number;
781
+ image?: ImageSource | undefined;
782
+ /** The page floating pictures are positioned against. */
783
+ geometry: FloatGeometry;
455
784
  }
456
785
 
457
786
  /** A paragraph's inline content: runs as spans, breaks, comment anchors, opaque inline content. */
@@ -462,12 +791,13 @@ function renderInline(
462
791
  paragraph: ParagraphFormat,
463
792
  context: InlineContext,
464
793
  ): void {
465
- const { resolver, doc, review, comments, ratio } = context;
794
+ const { resolver, doc, review, comments, ratio, image } = context;
795
+ const floats: HTMLElement[] = [];
466
796
  for (const node of inline) {
467
797
  const marks = (node.marks ?? []) as MarkJSON[];
468
798
  const inserted = marks.some((m) => m.type === "insertion");
469
799
  const deleted = marks.some((m) => m.type === "deletion");
470
- if (deleted && review === "final") continue;
800
+ if (deleted && review !== "markup") continue;
471
801
  const attrs = (node.attrs ?? {}) as Record<string, unknown>;
472
802
  switch (node.type) {
473
803
  case "commentStart":
@@ -485,6 +815,10 @@ function renderInline(
485
815
  case "bookmarkStart":
486
816
  case "bookmarkEnd":
487
817
  continue;
818
+ case "picture":
819
+ if (attrs.float) floats.push(...floatElements(attrs, doc, image, context.geometry).nodes);
820
+ else parent.append(pictureElement(attrs, doc, image));
821
+ continue;
488
822
  case "hardBreak":
489
823
  case "columnBreak":
490
824
  // shortcut: a column break ends the line; Foli lays out one column.
@@ -525,17 +859,18 @@ function renderInline(
525
859
  element.style.backgroundColor = "rgba(255, 213, 79, 0.35)";
526
860
  }
527
861
  if (review === "markup" && (inserted || deleted)) {
528
- const wrapper = doc.createElement(inserted ? "ins" : "del");
529
- const author = marks.find((m) => m.type === (inserted ? "insertion" : "deletion"))?.attrs
530
- ?.author;
531
- if (author) wrapper.title = String(author);
532
- wrapper.style.color = "#B5082E";
533
- wrapper.style.textDecorationLine = inserted ? "underline" : "line-through";
862
+ // Inserted, then deleted: shown as deleted, in the deleting author's color.
863
+ const change = marks.find((m) => m.type === (deleted ? "deletion" : "insertion"))?.attrs;
864
+ const author = String(change?.author ?? "");
865
+ const date = (change?.date as string | null | undefined) ?? null;
866
+ const wrapper = changeElement(doc, !deleted, author, date, review);
534
867
  wrapper.append(element);
535
868
  element = wrapper;
536
869
  }
537
870
  parent.append(element);
538
871
  }
872
+ // Floating pictures first in the paragraph, in order: lines from its top go around them.
873
+ parent.prepend(...floats);
539
874
  }
540
875
 
541
876
  /**
@@ -549,15 +884,20 @@ export function opaqueBlock(
549
884
  resolver: Resolver,
550
885
  doc: Document,
551
886
  ratio: (family: string) => number,
887
+ image?: ImageSource,
888
+ /** The page floating pictures in its cells are placed against. */
889
+ geometry: FloatGeometry = floatGeometry(undefined),
552
890
  ): WordBlock {
553
891
  const attrs = (node.attrs ?? {}) as Record<string, unknown>;
554
892
  const element = doc.createElement("div");
555
893
  element.dataset.foliOpaque = String(attrs.label ?? "");
556
894
  element.style.margin = "0";
557
895
  element.style.display = "flow-root";
558
- const xml = parseOpaque(String(attrs.xml ?? ""), doc);
896
+ const xml = node.type === "table" ? null : parseOpaque(String(attrs.xml ?? ""), doc);
559
897
  let after = 0;
560
- if (xml?.localName === "tbl") element.append(opaqueTable(xml, resolver, doc, ratio));
898
+ if (node.type === "table")
899
+ element.append(modelTable(node, resolver, doc, ratio, image, geometry));
900
+ else if (xml?.localName === "tbl") element.append(opaqueTable(xml, resolver, doc, ratio));
561
901
  else if (xml) {
562
902
  const paragraphs = outermost(xml, PARAGRAPHS);
563
903
  paragraphs.forEach((p, i) => {
@@ -771,6 +1111,115 @@ function opaqueTable(
771
1111
  return table;
772
1112
  }
773
1113
 
1114
+ /** A border of the model (`BorderJSON`) as CSS; undefined when it says none. */
1115
+ export function borderJsonCss(
1116
+ border: { style?: string; size?: number; color?: string } | undefined,
1117
+ ) {
1118
+ if (!border) return undefined;
1119
+ if (border.style === "nil" || border.style === "none") return "none";
1120
+ const width = Math.max(((border.size ?? 4) / 8) * (96 / 72), 0.5);
1121
+ const color = border.color && border.color !== "auto" ? `#${border.color}` : "#000";
1122
+ return `${width}px ${BORDER_STYLES[border.style ?? "single"] ?? "solid"} ${color}`;
1123
+ }
1124
+
1125
+ /**
1126
+ * A table of the model (schema v4), read-only, as opaque tables are shown: rows, cells with
1127
+ * their table style's formatting (`Resolver.cell`), their paragraphs and nested tables.
1128
+ *
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.
1131
+ */
1132
+ function modelTable(
1133
+ node: NodeJSON,
1134
+ resolver: Resolver,
1135
+ doc: Document,
1136
+ ratio: (family: string) => number,
1137
+ image: ImageSource | undefined,
1138
+ geometry: FloatGeometry,
1139
+ ): HTMLElement {
1140
+ const attrs = (node.attrs ?? {}) as Record<string, unknown>;
1141
+ const table = doc.createElement("table");
1142
+ table.style.borderCollapse = "collapse";
1143
+ table.style.tableLayout = "fixed";
1144
+ const grid = (attrs.grid as number[] | undefined) ?? [];
1145
+ const total = grid.reduce((a, b) => a + b, 0);
1146
+ if (total) table.style.width = `${total * PX_PER_TWIP}px`;
1147
+ const colgroup = doc.createElement("colgroup");
1148
+ for (const width of grid) {
1149
+ const col = doc.createElement("col");
1150
+ col.style.width = `${width * PX_PER_TWIP}px`;
1151
+ colgroup.append(col);
1152
+ }
1153
+ table.append(colgroup);
1154
+ const body = doc.createElement("tbody");
1155
+ const rows = node.content ?? [];
1156
+ const context = {
1157
+ resolver,
1158
+ doc,
1159
+ review: "markup" as const,
1160
+ comments: new Set<number>(),
1161
+ ratio,
1162
+ image,
1163
+ // shortcut: a floating picture in a cell is placed against the page, not its cell.
1164
+ geometry,
1165
+ };
1166
+ rows.forEach((rowNode, r) => {
1167
+ const rowAttrs = (rowNode.attrs ?? {}) as Record<string, unknown>;
1168
+ const row = doc.createElement("tr");
1169
+ if (rowAttrs.header) row.dataset.foliHeader = "";
1170
+ if (rowAttrs.cantSplit) row.dataset.foliCantSplit = "";
1171
+ const cells = rowNode.content ?? [];
1172
+ cells.forEach((cellNode, c) => {
1173
+ const cellAttrs = (cellNode.attrs ?? {}) as Record<string, unknown>;
1174
+ const format = resolver.cell(attrs, rowAttrs, cellAttrs, {
1175
+ row: r,
1176
+ rows: rows.length,
1177
+ cell: c,
1178
+ cells: cells.length,
1179
+ });
1180
+ const cell = doc.createElement("td");
1181
+ const span = cellAttrs.gridSpan as number | undefined;
1182
+ if (span && span > 1) cell.colSpan = span;
1183
+ if (format.shading) cell.style.backgroundColor = `#${format.shading}`;
1184
+ const m = format.margins;
1185
+ cell.style.padding = `${m.top * PX_PER_TWIP}px ${m.right * PX_PER_TWIP}px ${m.bottom * PX_PER_TWIP}px ${m.left * PX_PER_TWIP}px`;
1186
+ cell.style.verticalAlign =
1187
+ format.verticalAlign === "center" ? "middle" : format.verticalAlign;
1188
+ for (const side of ["top", "left", "bottom", "right"] as const) {
1189
+ const css = borderJsonCss(format.borders[side]);
1190
+ if (css) cell.style.setProperty(`border-${side}`, css);
1191
+ }
1192
+ row.append(cell);
1193
+ if (cellAttrs.vMerge === "continue") return;
1194
+ for (const block of cellNode.content ?? []) {
1195
+ if (block.type === "table") {
1196
+ cell.append(modelTable(block, resolver, doc, ratio, image, geometry));
1197
+ continue;
1198
+ }
1199
+ if (block.type !== "paragraph") {
1200
+ cell.append(opaqueBlock(block, 0, resolver, doc, ratio, image, geometry).element);
1201
+ continue;
1202
+ }
1203
+ const { paragraph, run } = resolver.paragraph(block.attrs ?? {}, format);
1204
+ const element = doc.createElement(tagOf(paragraph));
1205
+ // A cell's paragraph: where it is on pages is measured too (`cellParagraphs`).
1206
+ element.dataset.foliCell = "";
1207
+ styleParagraph(element, paragraph);
1208
+ styleRun(element, run, lineHeight(paragraph, run, ratio(fontStack(latin(run)))));
1209
+ renderInline(element, block.content ?? [], run, paragraph, context);
1210
+ if (!element.textContent) element.append(doc.createElement("br"));
1211
+ element.style.marginTop = `${paragraph.spacing.before * PX_PER_TWIP}px`;
1212
+ // 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`;
1214
+ cell.append(element);
1215
+ }
1216
+ });
1217
+ body.append(row);
1218
+ });
1219
+ table.append(body);
1220
+ return table;
1221
+ }
1222
+
774
1223
  function childValueOf(element: Element, attribute: string): string | undefined {
775
1224
  for (const a of element.attributes) if (a.localName === attribute) return a.value;
776
1225
  return undefined;