@folijs/view 0.1.0 → 0.3.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.
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Schema v3 blocks for the editable view (8.7a): the paragraphs of `blocks.ts`, rendered from
3
+ * model nodes with their leaves (the text nodes and elements positions map to), split into
4
+ * fragments at content offsets like the v2 blocks (`render.ts`), and what the page flow needs
5
+ * of each: Word's paragraph spacing and keep rules. Built with createElement/textContent only.
6
+ *
7
+ * Tracked changes are shown as markup (inserted and deleted text both shown). Content the model
8
+ * keeps opaque is shown from its XML and cannot be edited: an opaque block is a block leaf, an
9
+ * opaque inline node a leaf element.
10
+ */
11
+ import {
12
+ isSafeHref,
13
+ type ListMarker,
14
+ type Mark,
15
+ type MarkJSON,
16
+ type Node as ModelNode,
17
+ type RunFormat,
18
+ type WordContext,
19
+ } from "@folijs/core";
20
+ import type { BlockDesc, LeafDesc } from "../render.js";
21
+ import {
22
+ fontStack,
23
+ latin,
24
+ lineHeight,
25
+ markerElement,
26
+ opaqueBlock,
27
+ opaqueText,
28
+ PX_PER_TWIP,
29
+ parseOpaque,
30
+ styleParagraph,
31
+ styleRun,
32
+ tagOf,
33
+ WORD_PAGE_BREAK_ATTR,
34
+ } from "./blocks.js";
35
+
36
+ /** What the page flow needs to know about a v3 block. */
37
+ export interface WordInfo {
38
+ /** Space before and after in CSS px (Word adds them: the flow places them). */
39
+ before: number;
40
+ after: number;
41
+ keepNext: boolean;
42
+ keepLines: boolean;
43
+ pageBreakBefore: boolean;
44
+ /** The paragraph's style and whether it drops spacing next to the same style. */
45
+ style: string | null;
46
+ contextual: boolean;
47
+ }
48
+
49
+ /** A rendered v3 block: a view block plus its flow information and what it was rendered for. */
50
+ export interface WordBlockDesc extends BlockDesc {
51
+ readonly word: WordInfo;
52
+ /** What the rendering depends on besides the node (its marker, open comments). */
53
+ readonly key: string;
54
+ }
55
+
56
+ /**
57
+ * Renders the blocks of one v3 document for the editable view. `prepare` runs before each
58
+ * render: list numbers and comment ranges depend on the blocks before.
59
+ */
60
+ export class WordRenderer {
61
+ readonly #context: WordContext;
62
+ readonly #doc: Document;
63
+ readonly #ratio: (family: string) => number;
64
+ /** For the clipboard (`clipboardBlocks`): links as links, list numbers as Word's HTML has them. */
65
+ readonly #clipboard: boolean;
66
+ #markers: (ListMarker | null)[] = [];
67
+ /** Comment ranges open at the start of each block. */
68
+ #comments: number[][] = [];
69
+
70
+ constructor(
71
+ context: WordContext,
72
+ doc: Document,
73
+ ratio: (family: string) => number,
74
+ clipboard = false,
75
+ ) {
76
+ this.#context = context;
77
+ this.#doc = doc;
78
+ this.#ratio = ratio;
79
+ this.#clipboard = clipboard;
80
+ }
81
+
82
+ get context(): WordContext {
83
+ return this.#context;
84
+ }
85
+
86
+ /** Numbering and comment state per top-level node of `doc`. */
87
+ prepare(doc: ModelNode): void {
88
+ const attrs: Record<string, unknown>[] = [];
89
+ const comments: number[][] = [];
90
+ const open = new Set<number>();
91
+ doc.forEach((node) => {
92
+ attrs.push(node.type.name === "paragraph" ? node.attrs : { numbering: { id: 0 } });
93
+ comments.push([...open]);
94
+ node.forEach((child) => {
95
+ const id = child.attrs.id as number;
96
+ if (child.type.name === "commentStart") open.add(id);
97
+ else if (child.type.name === "commentEnd") open.delete(id);
98
+ });
99
+ });
100
+ this.#markers = this.#context.resolver.markers(attrs);
101
+ this.#comments = comments;
102
+ }
103
+
104
+ /** Whether the top-level block at `index` shows a list number. */
105
+ hasMarker(index: number): boolean {
106
+ return !!this.#markers[index];
107
+ }
108
+
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(" ")}`;
112
+ }
113
+
114
+ render(node: ModelNode, index: number, splits: readonly number[] = []): WordBlockDesc {
115
+ if (node.type.name !== "paragraph") return this.#opaque(node, index);
116
+ const { resolver } = this.#context;
117
+ const { paragraph, run } = resolver.paragraph(node.attrs);
118
+ const line = (r: RunFormat) => lineHeight(paragraph, r, this.#ratio(fontStack(latin(r))));
119
+ const doc = this.#doc;
120
+ const fragments = [0, ...splits].map((_, i, all) => {
121
+ const fragment = doc.createElement(tagOf(paragraph));
122
+ styleParagraph(fragment, paragraph);
123
+ styleRun(fragment, run, line(run));
124
+ if (all.length > 1) {
125
+ fragment.dataset.fragment = String(i);
126
+ // The first-line indent is the paragraph's first line only.
127
+ if (i > 0) fragment.style.textIndent = "0";
128
+ // Justified text stays justified up to the page end (a fragment's last line is not
129
+ // the paragraph's; see render.ts for the forced-break case).
130
+ if (i < all.length - 1 && fragment.style.textAlign === "justify")
131
+ fragment.style.textAlignLast = "justify";
132
+ }
133
+ return fragment;
134
+ });
135
+ const dom = fragments[0] as HTMLElement;
136
+ const marker = this.#markers[index];
137
+ if (marker) {
138
+ const element = markerElement(marker, paragraph, doc, this.#ratio);
139
+ // Shown, not document text: no caret inside, not read back. Other apps take it as Word's
140
+ // number for its list paragraph (set below).
141
+ if (this.#clipboard) element.setAttribute("style", `${styleOf(element)}mso-list:Ignore`);
142
+ else element.setAttribute("contenteditable", "false");
143
+ dom.append(element);
144
+ }
145
+ const fragmentAt = (at: number) => {
146
+ let i = 0;
147
+ while (i < splits.length && (splits[i] as number) <= at) i++;
148
+ return fragments[i] as HTMLElement;
149
+ };
150
+ const leaves: LeafDesc[] = [];
151
+ const comments = new Set(this.#comments[index] ?? []);
152
+ node.forEach((child, offset) => {
153
+ const name = child.type.name;
154
+ if (name === "commentStart") comments.add(child.attrs.id as number);
155
+ if (name === "commentEnd") comments.delete(child.attrs.id as number);
156
+ const leafElement = (element: HTMLElement) => {
157
+ leaves.push({ dom: element, offset, size: child.nodeSize });
158
+ fragmentAt(offset).append(this.#wrap(element, child.marks, comments.size > 0));
159
+ };
160
+ switch (name) {
161
+ case "text":
162
+ break;
163
+ case "hardBreak":
164
+ case "columnBreak":
165
+ case "pageBreak": {
166
+ // shortcut: a column break ends the line; Foli lays out one column.
167
+ const br = doc.createElement("br");
168
+ if (name === "pageBreak") br.setAttribute(WORD_PAGE_BREAK_ATTR, "");
169
+ leaves.push({ dom: br, offset, size: 1 });
170
+ fragmentAt(offset).append(br);
171
+ return;
172
+ }
173
+ case "tab": {
174
+ // A tab is text to the line layout (tab stops) and to the read-back.
175
+ const span = this.#run(run, child.marks, line);
176
+ const tab = doc.createTextNode("\t");
177
+ span.append(tab);
178
+ leaves.push({ dom: tab, offset, size: 1 });
179
+ fragmentAt(offset).append(this.#wrap(span, child.marks, comments.size > 0));
180
+ return;
181
+ }
182
+ case "opaqueInline": {
183
+ const span = this.#run(run, child.marks, line);
184
+ const xml = parseOpaque(String(child.attrs.xml ?? ""), doc);
185
+ span.textContent = xml ? opaqueText(xml) : "";
186
+ span.dataset.foliOpaque = String(child.attrs.label ?? "");
187
+ span.setAttribute("contenteditable", "false");
188
+ leafElement(span);
189
+ return;
190
+ }
191
+ default: {
192
+ // Bookmarks, comment anchors and reference marks: nothing to see, a place to map to.
193
+ const span = doc.createElement("span");
194
+ if (name === "commentReference")
195
+ span.dataset.foliCommentReference = String(child.attrs.id);
196
+ leaves.push({ dom: span, offset, size: child.nodeSize });
197
+ fragmentAt(offset).append(span);
198
+ return;
199
+ }
200
+ }
201
+ const text = child.text ?? "";
202
+ const cuts = splits.filter((split) => split > offset && split < offset + text.length);
203
+ let from = offset;
204
+ for (const to of [...cuts, offset + text.length]) {
205
+ const leaf = doc.createTextNode(text.slice(from - offset, to - offset));
206
+ leaves.push({ dom: leaf, offset: from, size: to - from });
207
+ const span = this.#run(run, child.marks, line);
208
+ span.append(leaf);
209
+ fragmentAt(from).append(this.#wrap(span, child.marks, comments.size > 0));
210
+ from = to;
211
+ }
212
+ });
213
+ // An empty paragraph, or one ending in a line break, shows its last line; after a page
214
+ // break the paragraph mark stays on the break's line, as in Word.
215
+ let last: ModelNode | null = null;
216
+ for (let i = node.childCount - 1; i >= 0 && !last; i--) {
217
+ const child = node.child(i);
218
+ if (!["bookmarkStart", "bookmarkEnd", "commentStart", "commentEnd"].includes(child.type.name))
219
+ last = child;
220
+ }
221
+ if (!last || last.type.name === "hardBreak" || last.type.name === "columnBreak")
222
+ (fragments[fragments.length - 1] as HTMLElement).append(doc.createElement("br"));
223
+ const { before, after } = paragraph.spacing;
224
+ // Word's automatic spacing (HTML): 14 pt.
225
+ const word: WordInfo = {
226
+ before: (paragraph.spacing.beforeAutospacing ? 280 : before) * PX_PER_TWIP,
227
+ after: (paragraph.spacing.afterAutospacing ? 280 : after) * PX_PER_TWIP,
228
+ keepNext: paragraph.keepNext,
229
+ keepLines: paragraph.keepLines,
230
+ pageBreakBefore: paragraph.pageBreakBefore,
231
+ style: paragraph.style,
232
+ contextual: paragraph.contextualSpacing,
233
+ };
234
+ if (this.#clipboard) {
235
+ // The flow places the spacing in the editor; elsewhere it is the paragraph's margins.
236
+ dom.style.marginTop = `${word.before}px`;
237
+ dom.style.marginBottom = `${word.after}px`;
238
+ // Written as text: the CSS object model drops properties it does not know.
239
+ const numbering = marker && paragraph.numbering;
240
+ if (numbering) {
241
+ const list = `l${numbering.id} level${numbering.level + 1} lfo${numbering.id}`;
242
+ dom.setAttribute("style", `${styleOf(dom)}mso-list:${list}`);
243
+ }
244
+ }
245
+ return { node, dom, fragments, splits, leaves, word, key: this.key(index) };
246
+ }
247
+
248
+ /** A span for text with `marks` over its paragraph's run formatting. */
249
+ #run(
250
+ paragraphRun: RunFormat,
251
+ marks: readonly Mark[],
252
+ line: (run: RunFormat) => string,
253
+ ): HTMLElement {
254
+ const json: MarkJSON[] = marks.map((m) => m.toJSON());
255
+ const run = this.#context.resolver.run(paragraphRun, json);
256
+ const span = this.#doc.createElement("span");
257
+ styleRun(span, run, line(run));
258
+ return span;
259
+ }
260
+
261
+ /** 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)";
265
+ let outer = element;
266
+ const change = marks.find((m) => m.type.name === "insertion" || m.type.name === "deletion");
267
+ if (change) {
268
+ 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";
273
+ outer.append(element);
274
+ }
275
+ // Schema v3 keeps any target (`file:`…): only a safe one is a link in the page or on the
276
+ // clipboard. It looks as its run says (Word shows a link without the Hyperlink style plain).
277
+ const href = marks.find((m) => m.type.name === "link")?.attrs.href;
278
+ if (typeof href !== "string" || !isSafeHref(href)) return outer;
279
+ const a = this.#doc.createElement("a");
280
+ a.setAttribute("href", href);
281
+ a.style.color = "inherit";
282
+ a.style.textDecoration = "none";
283
+ a.append(outer);
284
+ return a;
285
+ }
286
+
287
+ /** An opaque block, shown from its XML: a block leaf, not editable inside. */
288
+ #opaque(node: ModelNode, index: number): WordBlockDesc {
289
+ const shown = opaqueBlock(node.toJSON(), index, this.#context.resolver, this.#doc, this.#ratio);
290
+ const dom = shown.element;
291
+ dom.setAttribute("contenteditable", "false");
292
+ return {
293
+ node,
294
+ dom,
295
+ fragments: [dom],
296
+ splits: [],
297
+ leaves: [],
298
+ key: this.key(index),
299
+ word: {
300
+ before: shown.before,
301
+ after: shown.after,
302
+ keepNext: false,
303
+ keepLines: false,
304
+ pageBreakBefore: false,
305
+ style: null,
306
+ contextual: false,
307
+ },
308
+ };
309
+ }
310
+ }
311
+
312
+ /** An element's style attribute, ready for one more declaration. */
313
+ function styleOf(element: Element): string {
314
+ const style = element.getAttribute("style")?.trim() ?? "";
315
+ return style && !style.endsWith(";") ? `${style};` : style;
316
+ }
317
+
318
+ /**
319
+ * The HTML of copied v3 blocks `nodes`: drawn as the editor draws them, with their list numbers
320
+ * in `doc` (from top-level block `first`; -1 for text from inside one paragraph, which takes no
321
+ * number), without what only the editor needs (comment shading, `contenteditable`).
322
+ */
323
+ export function clipboardBlocks(
324
+ context: WordContext,
325
+ doc: ModelNode,
326
+ nodes: readonly ModelNode[],
327
+ first: number,
328
+ ownerDocument: Document,
329
+ ratio: (family: string) => number,
330
+ ): HTMLElement[] {
331
+ const renderer = new WordRenderer(context, ownerDocument, ratio, true);
332
+ renderer.prepare(doc);
333
+ return nodes.map((node, i) => {
334
+ const { dom } = renderer.render(node, first < 0 ? -1 : first + i);
335
+ for (const element of [dom, ...dom.querySelectorAll("*")])
336
+ for (const name of element.getAttributeNames())
337
+ if (
338
+ name === "contenteditable" ||
339
+ (name.startsWith("data-") && name !== WORD_PAGE_BREAK_ATTR)
340
+ )
341
+ element.removeAttribute(name);
342
+ return dom;
343
+ });
344
+ }
345
+
346
+ /**
347
+ * A block's space before and after next to its neighbours: Word ignores the space between
348
+ * paragraphs of the same style that ask for it (contextual spacing).
349
+ */
350
+ export function spacing(
351
+ above: WordInfo | undefined,
352
+ block: WordInfo,
353
+ below: WordInfo | undefined,
354
+ ): { before: number; after: number } {
355
+ const same = (other: WordInfo | undefined) => other !== undefined && other.style === block.style;
356
+ return {
357
+ before: same(above) && block.contextual ? 0 : block.before,
358
+ after: same(below) && block.contextual ? 0 : block.after,
359
+ };
360
+ }