@folijs/view 0.4.0 → 0.6.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 (71) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/clipboard.d.ts +3 -1
  3. package/dist/clipboard.d.ts.map +1 -1
  4. package/dist/clipboard.js.map +1 -1
  5. package/dist/index.d.ts +2 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/layout/flow.d.ts +195 -20
  10. package/dist/layout/flow.d.ts.map +1 -1
  11. package/dist/layout/flow.js +790 -102
  12. package/dist/layout/flow.js.map +1 -1
  13. package/dist/print.d.ts +22 -0
  14. package/dist/print.d.ts.map +1 -0
  15. package/dist/print.js +31 -0
  16. package/dist/print.js.map +1 -0
  17. package/dist/view.d.ts +407 -8
  18. package/dist/view.d.ts.map +1 -1
  19. package/dist/view.js +2956 -263
  20. package/dist/view.js.map +1 -1
  21. package/dist/word/blocks.d.ts +99 -2
  22. package/dist/word/blocks.d.ts.map +1 -1
  23. package/dist/word/blocks.js +535 -31
  24. package/dist/word/blocks.js.map +1 -1
  25. package/dist/word/columns.d.ts +23 -0
  26. package/dist/word/columns.d.ts.map +1 -0
  27. package/dist/word/columns.js +51 -0
  28. package/dist/word/columns.js.map +1 -0
  29. package/dist/word/controls.d.ts +63 -0
  30. package/dist/word/controls.d.ts.map +1 -0
  31. package/dist/word/controls.js +411 -0
  32. package/dist/word/controls.js.map +1 -0
  33. package/dist/word/edit.d.ts +32 -11
  34. package/dist/word/edit.d.ts.map +1 -1
  35. package/dist/word/edit.js +215 -33
  36. package/dist/word/edit.js.map +1 -1
  37. package/dist/word/matches.d.ts +23 -0
  38. package/dist/word/matches.d.ts.map +1 -0
  39. package/dist/word/matches.js +97 -0
  40. package/dist/word/matches.js.map +1 -0
  41. package/dist/word/notes.d.ts +105 -0
  42. package/dist/word/notes.d.ts.map +1 -0
  43. package/dist/word/notes.js +392 -0
  44. package/dist/word/notes.js.map +1 -0
  45. package/dist/word/pages.d.ts +26 -13
  46. package/dist/word/pages.d.ts.map +1 -1
  47. package/dist/word/pages.js +439 -203
  48. package/dist/word/pages.js.map +1 -1
  49. package/dist/word/regions.d.ts +113 -0
  50. package/dist/word/regions.d.ts.map +1 -0
  51. package/dist/word/regions.js +374 -0
  52. package/dist/word/regions.js.map +1 -0
  53. package/dist/word/table.d.ts +79 -0
  54. package/dist/word/table.d.ts.map +1 -0
  55. package/dist/word/table.js +210 -0
  56. package/dist/word/table.js.map +1 -0
  57. package/package.json +2 -2
  58. package/src/clipboard.ts +3 -0
  59. package/src/index.ts +8 -1
  60. package/src/layout/flow.ts +948 -111
  61. package/src/print.ts +48 -0
  62. package/src/view.ts +3291 -273
  63. package/src/word/blocks.ts +611 -28
  64. package/src/word/columns.ts +66 -0
  65. package/src/word/controls.ts +447 -0
  66. package/src/word/edit.ts +253 -30
  67. package/src/word/matches.ts +99 -0
  68. package/src/word/notes.ts +451 -0
  69. package/src/word/pages.ts +524 -192
  70. package/src/word/regions.ts +469 -0
  71. package/src/word/table.ts +267 -0
@@ -0,0 +1,451 @@
1
+ /**
2
+ * Footnotes and endnotes on pages (11.10, ADR-0007), for both renderers: a note measured as lines
3
+ * for the flow, and its pieces drawn at the column's foot or, for endnotes, after the text. A note
4
+ * is drawn from the model by the read-only blocks renderer, its number filled in.
5
+ */
6
+ import {
7
+ type FoliDocument,
8
+ type NoteNumber,
9
+ noteKindOf,
10
+ noteProperties,
11
+ type Resolver,
12
+ type SectionJSON,
13
+ type StoryJSON,
14
+ } from "@folijs/core";
15
+ import { arrangeNotes, type FlowNote, type FlowRules, type NotePiece } from "../layout/flow.js";
16
+ import { type BlockOptions, renderBlocks } from "./blocks.js";
17
+ import { columnsPx } from "./columns.js";
18
+ import { REGION_CLASS, REGION_CONTENT_CLASS, type RegionOptions, stack } from "./regions.js";
19
+
20
+ /** On a piece of a note drawn on a page: the story. */
21
+ export const NOTE_ATTR = "data-foli-note";
22
+ /** The class of what holds a column's notes. */
23
+ export const NOTES_CLASS = "foli-notes";
24
+
25
+ /**
26
+ * The bottom of each line of a rendered block, from its top. Lines are the vertical clusters of
27
+ * its contents' client rects; a boundary is halfway between one line's content and the next's,
28
+ * the last line ends at the block's bottom.
29
+ *
30
+ * shortcut: line boxes are inferred from content rects (exact for even line heights); a
31
+ * superscript or a much larger run on a line moves that line's boundaries slightly.
32
+ */
33
+ export function lineBottoms(element: HTMLElement): number[] {
34
+ const box = element.getBoundingClientRect();
35
+ const doc = element.ownerDocument;
36
+ const range = doc.createRange();
37
+ const rects: { rect: DOMRect; text: boolean }[] = [];
38
+ // Text and line breaks only: a range over the whole block also has the boxes of the
39
+ // elements inside it (a table's), which span many lines.
40
+ const walker = doc.createTreeWalker(element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
41
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
42
+ if (node.nodeType === Node.TEXT_NODE) {
43
+ // A raised number says nothing about where its line is.
44
+ if ((node.parentElement as HTMLElement | null)?.style.verticalAlign === "super") continue;
45
+ range.selectNodeContents(node);
46
+ for (const rect of range.getClientRects()) rects.push({ rect, text: true });
47
+ } else if (node.nodeName === "BR")
48
+ rects.push({ rect: (node as Element).getBoundingClientRect(), text: false });
49
+ }
50
+ rects.sort((a, b) => a.rect.top - b.rect.top);
51
+ type Line = { top: number; bottom: number; text: boolean };
52
+ const lines: Line[] = [];
53
+ for (const { rect, text } of rects) {
54
+ if (rect.height <= 0) continue;
55
+ const last = lines[lines.length - 1];
56
+ // Same line: it starts above the middle of the line so far.
57
+ if (last && rect.top < (last.top + last.bottom) / 2) {
58
+ // A line's text says where it is; a <br> only for a line without text (engines size
59
+ // its box differently).
60
+ if (text && !last.text) Object.assign(last, { top: rect.top, bottom: rect.bottom, text });
61
+ else if (text === last.text) {
62
+ last.top = Math.min(last.top, rect.top);
63
+ last.bottom = Math.max(last.bottom, rect.bottom);
64
+ }
65
+ } else lines.push({ top: rect.top, bottom: rect.bottom, text });
66
+ }
67
+ const bottoms = lines.slice(1).map((line, i) => {
68
+ const above = lines[i] as { bottom: number };
69
+ return (above.bottom + line.top) / 2 - box.top;
70
+ });
71
+ bottoms.push(box.height);
72
+ return bottoms;
73
+ }
74
+
75
+ /** Word's separators when a document has none of its own. */
76
+ const defaultSeparator = (type: "separator" | "continuationSeparator"): StoryJSON => ({
77
+ kind: "footnote",
78
+ noteType: type,
79
+ content: {
80
+ type: "doc",
81
+ content: [
82
+ {
83
+ type: "paragraph",
84
+ attrs: { spacing: { after: 0, line: 240, lineRule: "auto" } },
85
+ content: [{ type: "opaqueInline", attrs: { xml: `<w:r><w:${type}/></w:r>`, label: type } }],
86
+ },
87
+ ],
88
+ },
89
+ });
90
+ const DEFAULT_SEPARATOR = defaultSeparator("separator");
91
+
92
+ /**
93
+ * What a story shows: a separator single spaced with nothing before or after it, whatever its
94
+ * paragraph says (Word's PDFs: a bare separator and one with that spacing sit alike).
95
+ */
96
+ function asWordSets(story: StoryJSON): StoryJSON["content"] {
97
+ if ((story.noteType ?? "normal") === "normal") return story.content;
98
+ const spacing = { before: 0, after: 0, line: 240, lineRule: "auto" };
99
+ return {
100
+ ...story.content,
101
+ content: (story.content.content ?? []).map((block) =>
102
+ block.type === "paragraph"
103
+ ? { ...block, attrs: { ...block.attrs, spacing: { ...spacing } } }
104
+ : block,
105
+ ),
106
+ };
107
+ }
108
+ const DEFAULT_CONTINUATION = defaultSeparator("continuationSeparator");
109
+
110
+ /** A note at a width, with its number, as drawn and measured. */
111
+ interface Drawn {
112
+ serial: number;
113
+ template: HTMLElement;
114
+ /** The bottom of each line, from its top. */
115
+ lines: number[];
116
+ }
117
+
118
+ export type NoteCache = WeakMap<StoryJSON, Map<string, Drawn>>;
119
+
120
+ let serial = 0;
121
+
122
+ /** The notes at a band's foot, or after the text of one of its columns. */
123
+ export interface NoteGroup {
124
+ page: number;
125
+ band: number;
126
+ /** In the flow, its column. */
127
+ column: number;
128
+ /** In the text's flow: endnotes, and footnotes set beneath the text. */
129
+ inFlow: boolean;
130
+ pieces: NotePiece[];
131
+ /** The section whose columns they are in. */
132
+ section: number;
133
+ }
134
+
135
+ /** What a document's pages need to know of its notes. */
136
+ export class PageNotes {
137
+ private document: Omit<FoliDocument, "content"> | null = null;
138
+ private sections: readonly SectionJSON[] = [];
139
+ private resolver: Resolver | null = null;
140
+ private references: readonly NoteNumber[] = [];
141
+ private numbers = new Map<string, string>();
142
+ /** The note being edited: whole, one line to the flow. */
143
+ open: string | null = null;
144
+
145
+ constructor(
146
+ private readonly doc: Document,
147
+ private readonly options: RegionOptions,
148
+ public cache: NoteCache,
149
+ ) {}
150
+
151
+ /** What is laid out now: the references shown, in order, with their numbers. */
152
+ setDocument(
153
+ document: Omit<FoliDocument, "content">,
154
+ sections: readonly SectionJSON[],
155
+ resolver: Resolver,
156
+ references: readonly NoteNumber[],
157
+ ): void {
158
+ this.document = document;
159
+ this.sections = sections;
160
+ this.resolver = resolver;
161
+ this.references = references;
162
+ this.numbers = new Map(references.map((n) => [n.story, n.text]));
163
+ }
164
+
165
+ private story(id: string): StoryJSON | undefined {
166
+ const stories = this.document?.stories;
167
+ return stories && Object.hasOwn(stories, id) ? stories[id] : undefined;
168
+ }
169
+
170
+ /** The separator of `kind`, the document's own or Word's. */
171
+ private separator(kind: "footnote" | "endnote", type: "separator" | "continuationSeparator") {
172
+ const found = Object.entries(this.document?.stories ?? {}).find(
173
+ ([, story]) => story.kind === kind && story.noteType === type,
174
+ );
175
+ return found
176
+ ? { id: found[0], story: found[1] }
177
+ : {
178
+ id: `${kind}:${type}`,
179
+ story: type === "separator" ? DEFAULT_SEPARATOR : DEFAULT_CONTINUATION,
180
+ };
181
+ }
182
+
183
+ private storyFor(id: string): StoryJSON | undefined {
184
+ if (id === "footnote:separator" || id === "endnote:separator") return DEFAULT_SEPARATOR;
185
+ if (id.endsWith(":continuationSeparator")) return DEFAULT_CONTINUATION;
186
+ return this.story(id);
187
+ }
188
+
189
+ private drawn(id: string, width: number): Drawn {
190
+ const story = this.storyFor(id) as StoryJSON;
191
+ const mark = this.numbers.get(id) ?? "";
192
+ let byKey = this.cache.get(story);
193
+ if (!byKey) {
194
+ byKey = new Map();
195
+ this.cache.set(story, byKey);
196
+ }
197
+ const key = `${mark}|${width}`;
198
+ let found = byKey.get(key);
199
+ if (!found) {
200
+ const template = this.doc.createElement("div");
201
+ template.className = REGION_CONTENT_CLASS;
202
+ template.style.paddingTop = "0.01px";
203
+ const options: BlockOptions = {
204
+ ...this.options,
205
+ notes: { mark },
206
+ ...(this.resolver ? { resolver: this.resolver } : {}),
207
+ };
208
+ const blocks = renderBlocks(
209
+ { ...this.document, content: asWordSets(story) } as FoliDocument,
210
+ this.doc,
211
+ options,
212
+ );
213
+ const after = stack(blocks, template, !!this.resolver?.addsParagraphSpacing);
214
+ const { style } = template;
215
+ style.position = "absolute";
216
+ style.visibility = "hidden";
217
+ style.width = `${width}px`;
218
+ this.options.measureIn().append(template);
219
+ const scale = this.options.scale?.() ?? 1;
220
+ const top = template.getBoundingClientRect().top;
221
+ const lines = blocks.flatMap(({ element }) => {
222
+ const offset = (element.getBoundingClientRect().top - top) / scale;
223
+ return lineBottoms(element).map((bottom) => offset + bottom / scale);
224
+ });
225
+ template.remove();
226
+ style.position = "";
227
+ style.visibility = "";
228
+ style.width = "";
229
+ // The last space after is the note's: the next one starts below it.
230
+ if (lines.length) lines[lines.length - 1] = (lines.at(-1) as number) + after;
231
+ found = { serial: ++serial, template, lines: lines.length ? lines : [0] };
232
+ byKey.set(key, found);
233
+ }
234
+ return found;
235
+ }
236
+
237
+ /** The lines of story `id` in `width`; the note being edited is one, whole. */
238
+ private linesOf(id: string, width: number): number[] {
239
+ const { lines } = this.drawn(id, width);
240
+ return id === this.open ? [lines.at(-1) as number] : lines;
241
+ }
242
+
243
+ private flowNote(id: string, widths: readonly number[]): FlowNote {
244
+ return { id, lines: (column) => this.linesOf(id, widths[column] ?? (widths[0] as number)) };
245
+ }
246
+
247
+ private widths(section: number): number[] {
248
+ return columnsPx(this.sections[section] ?? {}).widths;
249
+ }
250
+
251
+ /** The footnote `story` as the flow takes it, when its reference is shown. */
252
+ footnote(story: string, section: number): FlowNote | null {
253
+ return noteKindOf(story) === "footnote" && this.numbers.has(story) && this.story(story)
254
+ ? this.flowNote(story, this.widths(section))
255
+ : null;
256
+ }
257
+
258
+ /** What goes above footnotes, when the document has any on its pages. */
259
+ flowRules(): FlowRules["notes"] {
260
+ if (!this.references.some((n) => n.kind === "footnote" && this.story(n.story)))
261
+ return undefined;
262
+ const widths = this.widths(0);
263
+ return {
264
+ separator: this.flowNote(this.separator("footnote", "separator").id, widths),
265
+ continuation: this.flowNote(this.separator("footnote", "continuationSeparator").id, widths),
266
+ };
267
+ }
268
+
269
+ /** The endnotes that follow the last block of each section, with their separator. */
270
+ endnotes(): Map<number, FlowNote[]> {
271
+ const out = new Map<number, FlowNote[]>();
272
+ const lastSection = Math.max(this.sections.length - 1, 0);
273
+ const document = this.document;
274
+ if (!document) return out;
275
+ const atSectionEnd = noteProperties(document, "endnote").position === "sectEnd";
276
+ for (const { story, kind, section } of this.references) {
277
+ if (kind !== "endnote" || !this.story(story)) continue;
278
+ const at = atSectionEnd ? section : lastSection;
279
+ const list = out.get(at) ?? [
280
+ this.flowNote(this.separator("endnote", "separator").id, this.widths(at)),
281
+ ];
282
+ list.push(this.flowNote(story, this.widths(at)));
283
+ out.set(at, list);
284
+ }
285
+ return out;
286
+ }
287
+
288
+ /** A change in what any of these measures means a new flow. */
289
+ key(): string {
290
+ if (!this.references.length) return "";
291
+ const heights = this.references
292
+ .filter((n) => this.story(n.story))
293
+ .map(({ story, section }) => {
294
+ const lines = this.linesOf(story, this.widths(section)[0] as number);
295
+ return `${lines.length}:${lines.at(-1)}`;
296
+ });
297
+ return `${this.open ?? ""}|${heights.join(" ")}`;
298
+ }
299
+
300
+ /** The notes of each column of each page, foot and flow apart. */
301
+ groups(pieces: readonly NotePiece[], sectionOf: (page: number, band: number) => number) {
302
+ const groups = new Map<string, NoteGroup>();
303
+ for (const piece of pieces) {
304
+ const band = piece.band ?? 0;
305
+ const column = piece.column ?? 0;
306
+ const section = sectionOf(piece.page, band);
307
+ const setup = this.sections[section];
308
+ // Beneath the text: with one column, whose text they then follow.
309
+ const beneath =
310
+ !!this.document &&
311
+ this.widths(section).length === 1 &&
312
+ noteProperties(this.document, "footnote", setup).position === "beneathText";
313
+ const inFlow = !!piece.end || (beneath && noteKindOf(piece.id) === "footnote");
314
+ const key = `${piece.page}|${band}|${inFlow ? column : 0}|${inFlow}`;
315
+ let group = groups.get(key);
316
+ if (!group) {
317
+ group = { page: piece.page, band, column, inFlow, pieces: [], section };
318
+ groups.set(key, group);
319
+ }
320
+ group.pieces.push(piece);
321
+ }
322
+ return [...groups.values()];
323
+ }
324
+
325
+ private widthOf(group: NoteGroup): number {
326
+ const widths = this.widths(group.section);
327
+ return widths[group.column] ?? (widths[0] as number);
328
+ }
329
+
330
+ private pieceHeight(piece: NotePiece, width: number): number {
331
+ const lines = this.linesOf(piece.id, width);
332
+ const to = Math.min(piece.toLine, lines.length);
333
+ return (
334
+ (piece.lead ?? 0) +
335
+ (lines[to - 1] ?? 0) -
336
+ (piece.fromLine ? (lines[piece.fromLine - 1] ?? 0) : 0)
337
+ );
338
+ }
339
+
340
+ /** A group as it is set: its separators, then each piece in its column. */
341
+ private arranged(group: NoteGroup) {
342
+ const width = this.widthOf(group);
343
+ const isSeparator = (piece: NotePiece) =>
344
+ (this.storyFor(piece.id)?.noteType ?? "normal") !== "normal";
345
+ const separators = group.pieces.filter(isSeparator);
346
+ const notes = group.pieces.filter((piece) => !isSeparator(piece));
347
+ const columns = group.inFlow ? 1 : this.widths(group.section).length;
348
+ const heights = notes.map((piece) => this.pieceHeight(piece, width));
349
+ const { height, columnOf } = arrangeNotes(heights, columns);
350
+ const above = separators.reduce((sum, piece) => sum + this.pieceHeight(piece, width), 0);
351
+ return { separators, notes, columnOf, columns, above, height };
352
+ }
353
+
354
+ /** How tall a group is. */
355
+ heightOf(group: NoteGroup): number {
356
+ const { above, height } = this.arranged(group);
357
+ return above + height;
358
+ }
359
+
360
+ /** What identifies how a group looks: the same key, the same drawing. */
361
+ keyOf(group: NoteGroup): string {
362
+ const width = this.widthOf(group);
363
+ return group.pieces
364
+ .map((p) => {
365
+ const { serial: drawing } = this.drawn(p.id, width);
366
+ return `${p.id}|${drawing}|${p.fromLine}|${p.toLine}|${p.lead ?? 0}|${p.id === this.open}`;
367
+ })
368
+ .join(";");
369
+ }
370
+
371
+ /** A piece of a note: the note's lines shown, clipped to them unless it is whole. */
372
+ pieceElement(piece: NotePiece, group: NoteGroup): HTMLElement {
373
+ const width = this.widthOf(group);
374
+ const { lines, template } = this.drawn(piece.id, width);
375
+ const outer = this.doc.createElement("div");
376
+ outer.setAttribute(NOTE_ATTR, piece.id);
377
+ if (piece.lead) outer.style.marginTop = `${piece.lead}px`;
378
+ const copy = template.cloneNode(true) as HTMLElement;
379
+ const whole = piece.fromLine === 0 && piece.toLine >= lines.length;
380
+ if (whole || piece.id === this.open) {
381
+ outer.append(copy);
382
+ return outer;
383
+ }
384
+ const top = piece.fromLine ? (lines[piece.fromLine - 1] as number) : 0;
385
+ const bottom = lines[Math.min(piece.toLine, lines.length) - 1] as number;
386
+ outer.style.overflow = "hidden";
387
+ outer.style.height = `${bottom - top}px`;
388
+ copy.style.marginTop = `${-top}px`;
389
+ if (piece.fromLine) copy.setAttribute("aria-hidden", "true");
390
+ outer.append(copy);
391
+ return outer;
392
+ }
393
+
394
+ /** The element of a group, its pieces given by `pieceOf` (one kept while it is being edited). */
395
+ groupElement(
396
+ group: NoteGroup,
397
+ place: { left: number; bottom: number } | null,
398
+ pieceOf: (piece: NotePiece) => HTMLElement = (piece) => this.pieceElement(piece, group),
399
+ /** Above a group in the flow: the space after the text it follows. */
400
+ lead = 0,
401
+ ): HTMLElement {
402
+ const element = this.doc.createElement("div");
403
+ element.className = `${REGION_CLASS} ${NOTES_CLASS}`;
404
+ element.setAttribute("contenteditable", "false");
405
+ const { style } = element;
406
+ style.userSelect = "none";
407
+ style.setProperty("-webkit-user-select", "none");
408
+ style.width = `${this.widthOf(group)}px`;
409
+ if (lead) style.marginTop = `${lead}px`;
410
+ if (place) {
411
+ style.position = "absolute";
412
+ style.left = `${place.left}px`;
413
+ style.bottom = `${place.bottom}px`;
414
+ }
415
+ const { separators, notes, columnOf, columns, above } = this.arranged(group);
416
+ if (columns === 1) {
417
+ element.append(...group.pieces.map(pieceOf));
418
+ return element;
419
+ }
420
+ // In the section's columns: the separator over the first, the others level with its notes.
421
+ const { widths, gaps } = columnsPx(this.sections[group.section] ?? {});
422
+ style.width = "auto";
423
+ style.display = "flex";
424
+ style.alignItems = "flex-start";
425
+ for (let c = 0; c < columns; c++) {
426
+ const column = this.doc.createElement("div");
427
+ column.style.flex = "none";
428
+ column.style.width = `${widths[c]}px`;
429
+ column.style.marginRight = `${gaps[c] ?? 0}px`;
430
+ if (c) column.style.paddingTop = `${above}px`;
431
+ else column.append(...separators.map(pieceOf));
432
+ column.append(...notes.filter((_, n) => columnOf[n] === c).map(pieceOf));
433
+ element.append(column);
434
+ }
435
+ return element;
436
+ }
437
+
438
+ /** Where the foot of a band is: from the page's left edge and bottom edge. */
439
+ footPlace(margins: { left: number; bottom: number }, stacked: number) {
440
+ return { left: margins.left, bottom: margins.bottom + stacked };
441
+ }
442
+
443
+ /** How much of the foot the bands below a group's take, on its page. */
444
+ stacked(group: NoteGroup, groups: readonly NoteGroup[]): number {
445
+ const below = new Map<number, number>();
446
+ for (const other of groups)
447
+ if (other.page === group.page && !other.inFlow && other.band > group.band)
448
+ below.set(other.band, Math.max(below.get(other.band) ?? 0, this.heightOf(other)));
449
+ return [...below.values()].reduce((sum, height) => sum + height, 0);
450
+ }
451
+ }