@folijs/view 0.4.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,6 +21,256 @@ 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
276
  /** How tracked changes show (`@folijs/core`'s, for `renderDocument` too). */
@@ -83,6 +334,26 @@ export interface BlockOptions {
83
334
  * Measured by the page layout; 1.2 when nothing measures (no layout engine).
84
335
  */
85
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
+ };
86
357
  }
87
358
 
88
359
  /** A rendered block and what the page flow needs to know about it. */
@@ -336,6 +607,9 @@ export function renderBlocks(
336
607
  return value;
337
608
  };
338
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);
339
613
  const content = document.content.content ?? [];
340
614
  const attrsOf = (node: NodeJSON) => (node.attrs ?? {}) as Record<string, unknown>;
341
615
  // In the final and simple views a paragraph whose mark was deleted joins the next paragraph
@@ -363,7 +637,7 @@ export function renderBlocks(
363
637
 
364
638
  content.forEach((node, index) => {
365
639
  if (node.type !== "paragraph") {
366
- blocks.push(opaqueBlock(node, index, resolver, doc, ratio));
640
+ blocks.push(opaqueBlock(node, index, resolver, doc, ratio, image, geometry));
367
641
  return;
368
642
  }
369
643
  const attrs = attrsOf(node);
@@ -395,6 +669,8 @@ export function renderBlocks(
395
669
  review,
396
670
  comments,
397
671
  ratio,
672
+ image,
673
+ geometry,
398
674
  });
399
675
  // An empty paragraph, or one ending in a line break, shows its last (empty) line; after a
400
676
  // page break the paragraph mark stays on the break's line, as in Word.
@@ -502,6 +778,9 @@ interface InlineContext {
502
778
  review: ReviewView;
503
779
  comments: Set<number>;
504
780
  ratio: (family: string) => number;
781
+ image?: ImageSource | undefined;
782
+ /** The page floating pictures are positioned against. */
783
+ geometry: FloatGeometry;
505
784
  }
506
785
 
507
786
  /** A paragraph's inline content: runs as spans, breaks, comment anchors, opaque inline content. */
@@ -512,7 +791,8 @@ function renderInline(
512
791
  paragraph: ParagraphFormat,
513
792
  context: InlineContext,
514
793
  ): void {
515
- const { resolver, doc, review, comments, ratio } = context;
794
+ const { resolver, doc, review, comments, ratio, image } = context;
795
+ const floats: HTMLElement[] = [];
516
796
  for (const node of inline) {
517
797
  const marks = (node.marks ?? []) as MarkJSON[];
518
798
  const inserted = marks.some((m) => m.type === "insertion");
@@ -535,6 +815,10 @@ function renderInline(
535
815
  case "bookmarkStart":
536
816
  case "bookmarkEnd":
537
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;
538
822
  case "hardBreak":
539
823
  case "columnBreak":
540
824
  // shortcut: a column break ends the line; Foli lays out one column.
@@ -585,6 +869,8 @@ function renderInline(
585
869
  }
586
870
  parent.append(element);
587
871
  }
872
+ // Floating pictures first in the paragraph, in order: lines from its top go around them.
873
+ parent.prepend(...floats);
588
874
  }
589
875
 
590
876
  /**
@@ -598,15 +884,20 @@ export function opaqueBlock(
598
884
  resolver: Resolver,
599
885
  doc: Document,
600
886
  ratio: (family: string) => number,
887
+ image?: ImageSource,
888
+ /** The page floating pictures in its cells are placed against. */
889
+ geometry: FloatGeometry = floatGeometry(undefined),
601
890
  ): WordBlock {
602
891
  const attrs = (node.attrs ?? {}) as Record<string, unknown>;
603
892
  const element = doc.createElement("div");
604
893
  element.dataset.foliOpaque = String(attrs.label ?? "");
605
894
  element.style.margin = "0";
606
895
  element.style.display = "flow-root";
607
- const xml = parseOpaque(String(attrs.xml ?? ""), doc);
896
+ const xml = node.type === "table" ? null : parseOpaque(String(attrs.xml ?? ""), doc);
608
897
  let after = 0;
609
- 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));
610
901
  else if (xml) {
611
902
  const paragraphs = outermost(xml, PARAGRAPHS);
612
903
  paragraphs.forEach((p, i) => {
@@ -820,6 +1111,115 @@ function opaqueTable(
820
1111
  return table;
821
1112
  }
822
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
+
823
1223
  function childValueOf(element: Element, attribute: string): string | undefined {
824
1224
  for (const a of element.attributes) if (a.localName === attribute) return a.value;
825
1225
  return undefined;