@folijs/core 0.2.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.
Files changed (115) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +10 -16
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +22 -22
  6. package/dist/document.js.map +1 -1
  7. package/dist/index.d.ts +3 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/model/fragment.d.ts +5 -2
  12. package/dist/model/fragment.d.ts.map +1 -1
  13. package/dist/model/fragment.js +5 -2
  14. package/dist/model/fragment.js.map +1 -1
  15. package/dist/model/node.d.ts +1 -1
  16. package/dist/model/node.d.ts.map +1 -1
  17. package/dist/model/node.js.map +1 -1
  18. package/dist/schema.d.ts +10 -1
  19. package/dist/schema.d.ts.map +1 -1
  20. package/dist/schema.js +11 -1
  21. package/dist/schema.js.map +1 -1
  22. package/dist/state/commands.d.ts +7 -6
  23. package/dist/state/commands.d.ts.map +1 -1
  24. package/dist/state/commands.js +134 -97
  25. package/dist/state/commands.js.map +1 -1
  26. package/dist/state/editor.d.ts +25 -15
  27. package/dist/state/editor.d.ts.map +1 -1
  28. package/dist/state/editor.js +44 -16
  29. package/dist/state/editor.js.map +1 -1
  30. package/dist/state/format.d.ts +8 -22
  31. package/dist/state/format.d.ts.map +1 -1
  32. package/dist/state/format.js +16 -140
  33. package/dist/state/format.js.map +1 -1
  34. package/dist/state/index.d.ts +8 -4
  35. package/dist/state/index.d.ts.map +1 -1
  36. package/dist/state/index.js +8 -4
  37. package/dist/state/index.js.map +1 -1
  38. package/dist/state/links.d.ts.map +1 -1
  39. package/dist/state/links.js +10 -2
  40. package/dist/state/links.js.map +1 -1
  41. package/dist/state/lists.d.ts +19 -32
  42. package/dist/state/lists.d.ts.map +1 -1
  43. package/dist/state/lists.js +23 -372
  44. package/dist/state/lists.js.map +1 -1
  45. package/dist/state/mark.d.ts +25 -0
  46. package/dist/state/mark.d.ts.map +1 -0
  47. package/dist/state/mark.js +40 -0
  48. package/dist/state/mark.js.map +1 -0
  49. package/dist/state/state.d.ts.map +1 -1
  50. package/dist/state/state.js +11 -0
  51. package/dist/state/state.js.map +1 -1
  52. package/dist/state/word.d.ts +72 -0
  53. package/dist/state/word.d.ts.map +1 -0
  54. package/dist/state/word.js +173 -0
  55. package/dist/state/word.js.map +1 -0
  56. package/dist/state/wordclip.d.ts +43 -0
  57. package/dist/state/wordclip.d.ts.map +1 -0
  58. package/dist/state/wordclip.js +412 -0
  59. package/dist/state/wordclip.js.map +1 -0
  60. package/dist/state/wordformat.d.ts +136 -0
  61. package/dist/state/wordformat.d.ts.map +1 -0
  62. package/dist/state/wordformat.js +846 -0
  63. package/dist/state/wordformat.js.map +1 -0
  64. package/dist/v3/check.d.ts +33 -0
  65. package/dist/v3/check.d.ts.map +1 -0
  66. package/dist/v3/check.js +90 -0
  67. package/dist/v3/check.js.map +1 -0
  68. package/dist/v3/document.d.ts +217 -0
  69. package/dist/v3/document.d.ts.map +1 -0
  70. package/dist/v3/document.js +225 -0
  71. package/dist/v3/document.js.map +1 -0
  72. package/dist/v3/index.d.ts +6 -0
  73. package/dist/v3/index.d.ts.map +1 -0
  74. package/dist/v3/index.js +6 -0
  75. package/dist/v3/index.js.map +1 -0
  76. package/dist/v3/migrate.d.ts +19 -0
  77. package/dist/v3/migrate.d.ts.map +1 -0
  78. package/dist/v3/migrate.js +227 -0
  79. package/dist/v3/migrate.js.map +1 -0
  80. package/dist/v3/resolve.d.ts +129 -0
  81. package/dist/v3/resolve.d.ts.map +1 -0
  82. package/dist/v3/resolve.js +534 -0
  83. package/dist/v3/resolve.js.map +1 -0
  84. package/dist/v3/schema.d.ts +27 -0
  85. package/dist/v3/schema.d.ts.map +1 -0
  86. package/dist/v3/schema.js +429 -0
  87. package/dist/v3/schema.js.map +1 -0
  88. package/dist/v3/units.d.ts +16 -0
  89. package/dist/v3/units.d.ts.map +1 -0
  90. package/dist/v3/units.js +28 -0
  91. package/dist/v3/units.js.map +1 -0
  92. package/package.json +1 -1
  93. package/src/document.ts +26 -26
  94. package/src/index.ts +3 -6
  95. package/src/model/fragment.ts +11 -3
  96. package/src/model/node.ts +6 -1
  97. package/src/schema.ts +13 -1
  98. package/src/state/commands.ts +147 -91
  99. package/src/state/editor.ts +81 -35
  100. package/src/state/format.ts +24 -122
  101. package/src/state/index.ts +34 -3
  102. package/src/state/links.ts +10 -2
  103. package/src/state/lists.ts +31 -408
  104. package/src/state/mark.ts +47 -0
  105. package/src/state/state.ts +11 -0
  106. package/src/state/word.ts +245 -0
  107. package/src/state/wordclip.ts +445 -0
  108. package/src/state/wordformat.ts +982 -0
  109. package/src/v3/check.ts +119 -0
  110. package/src/v3/document.ts +456 -0
  111. package/src/v3/index.ts +33 -0
  112. package/src/v3/migrate.ts +267 -0
  113. package/src/v3/resolve.ts +646 -0
  114. package/src/v3/schema.ts +479 -0
  115. package/src/v3/units.ts +34 -0
@@ -0,0 +1,646 @@
1
+ /**
2
+ * How a schema v3 document looks: the effective paragraph and run formatting Word computes from
3
+ * the document defaults, the styles and direct formatting (ECMA-376 Part 1, 17.7.2), and the
4
+ * list markers numbering gives paragraphs (17.9). No DOM: the view turns these into CSS.
5
+ */
6
+
7
+ import type { MarkJSON } from "../model/index.js";
8
+ import type {
9
+ AbstractNumberingJSON,
10
+ FoliDocument,
11
+ NumberingInstanceJSON,
12
+ NumberingLevelJSON,
13
+ ParagraphPropertiesJSON,
14
+ StyleJSON,
15
+ ThemeJSON,
16
+ } from "./document.js";
17
+
18
+ type Json = Record<string, unknown>;
19
+
20
+ /** Effective run formatting: what a run looks like after defaults, styles and direct marks. */
21
+ export interface RunFormat {
22
+ bold: boolean;
23
+ /** Bold for complex scripts (`w:bCs`). */
24
+ boldCs: boolean;
25
+ italic: boolean;
26
+ italicCs: boolean;
27
+ caps: boolean;
28
+ smallCaps: boolean;
29
+ strike: boolean;
30
+ doubleStrike: boolean;
31
+ hidden: boolean;
32
+ /** Underline style (`single`, `double`…); null for none. */
33
+ underline: string | null;
34
+ underlineColor: string | null;
35
+ /** Font names per script, theme fonts resolved; null where nothing names one. */
36
+ font: { ascii: string | null; hAnsi: string | null; eastAsia: string | null; cs: string | null };
37
+ /** Half-points (Word's default without any: 20, 10 pt). */
38
+ size: number;
39
+ sizeCs: number;
40
+ /** `RRGGBB` (theme colors resolved); null for automatic. */
41
+ color: string | null;
42
+ highlight: string | null;
43
+ /** Shading fill `RRGGBB`; null for none. */
44
+ shading: string | null;
45
+ verticalAlign: "baseline" | "superscript" | "subscript";
46
+ /** Twips. */
47
+ characterSpacing: number;
48
+ }
49
+
50
+ /** Effective paragraph properties: a paragraph's attributes after defaults, styles and numbering. */
51
+ export interface ParagraphFormat {
52
+ /** The paragraph style that applies (the default paragraph style when none is named). */
53
+ style: string | null;
54
+ justification: string | null;
55
+ /** Twips. Only one of `firstLine` and `hanging` is non-zero. */
56
+ indent: { left: number; right: number; firstLine: number; hanging: number };
57
+ spacing: {
58
+ before: number;
59
+ after: number;
60
+ line: number | null;
61
+ lineRule: "auto" | "exact" | "atLeast";
62
+ beforeAutospacing: boolean;
63
+ afterAutospacing: boolean;
64
+ };
65
+ keepNext: boolean;
66
+ keepLines: boolean;
67
+ widowControl: boolean;
68
+ pageBreakBefore: boolean;
69
+ contextualSpacing: boolean;
70
+ outlineLevel: number | null;
71
+ tabs: { position: number; kind: string; leader: string | null }[];
72
+ borders: NonNullable<ParagraphPropertiesJSON["borders"]> | null;
73
+ shading: ParagraphPropertiesJSON["shading"] | null;
74
+ /** The numbering that applies (direct, or from the style): instance id and level. */
75
+ numbering: { id: number; level: number } | null;
76
+ }
77
+
78
+ /** A paragraph's list marker. */
79
+ export interface ListMarker {
80
+ /** As Word shows it ("1.", "1.1", "(a)", or a bullet's character as the file has it). */
81
+ text: string;
82
+ /** What follows the marker. */
83
+ suffix: "tab" | "space" | "nothing";
84
+ justification: string;
85
+ /** The marker's formatting: the paragraph's, its mark's, then the level's run properties. */
86
+ run: RunFormat;
87
+ instance: number;
88
+ level: number;
89
+ }
90
+
91
+ const TOGGLES = [
92
+ "bold",
93
+ "boldCs",
94
+ "italic",
95
+ "italicCs",
96
+ "caps",
97
+ "smallCaps",
98
+ "strike",
99
+ "doubleStrike",
100
+ "hidden",
101
+ ] as const;
102
+ type Toggle = (typeof TOGGLES)[number];
103
+
104
+ const DEFAULT_RUN: RunFormat = {
105
+ bold: false,
106
+ boldCs: false,
107
+ italic: false,
108
+ italicCs: false,
109
+ caps: false,
110
+ smallCaps: false,
111
+ strike: false,
112
+ doubleStrike: false,
113
+ hidden: false,
114
+ underline: null,
115
+ underlineColor: null,
116
+ font: { ascii: null, hAnsi: null, eastAsia: null, cs: null },
117
+ size: 20,
118
+ sizeCs: 20,
119
+ color: null,
120
+ highlight: null,
121
+ shading: null,
122
+ verticalAlign: "baseline",
123
+ characterSpacing: 0,
124
+ };
125
+
126
+ /** While merging, the numbering level may be unknown (a style naming only the instance). */
127
+ type Merging = Omit<ParagraphFormat, "numbering"> & {
128
+ numbering: { id: number; level: number | undefined } | null;
129
+ };
130
+
131
+ const DEFAULT_PARAGRAPH: Merging = {
132
+ style: null,
133
+ justification: null,
134
+ indent: { left: 0, right: 0, firstLine: 0, hanging: 0 },
135
+ spacing: {
136
+ before: 0,
137
+ after: 0,
138
+ line: null,
139
+ lineRule: "auto",
140
+ beforeAutospacing: false,
141
+ afterAutospacing: false,
142
+ },
143
+ keepNext: false,
144
+ keepLines: false,
145
+ widowControl: false,
146
+ pageBreakBefore: false,
147
+ contextualSpacing: false,
148
+ outlineLevel: null,
149
+ tabs: [],
150
+ borders: null,
151
+ shading: null,
152
+ numbering: null,
153
+ };
154
+
155
+ const PLAIN_KEYS = new Set([
156
+ "justification",
157
+ "keepNext",
158
+ "keepLines",
159
+ "widowControl",
160
+ "pageBreakBefore",
161
+ "contextualSpacing",
162
+ "outlineLevel",
163
+ "shading",
164
+ ]);
165
+
166
+ /** Paragraph properties merged in order, later winning, attribute by attribute as Word inherits them. */
167
+ function mergeParagraph(target: Merging, props: ParagraphPropertiesJSON | undefined): void {
168
+ if (!props) return;
169
+ const { indent, spacing, numbering, borders, tabs } = props;
170
+ if (indent) {
171
+ // A first-line indent and a hanging one are one value: setting one replaces the other.
172
+ if (indent.firstLine !== undefined) target.indent.hanging = 0;
173
+ Object.assign(target.indent, indent);
174
+ // With both, Word applies the hanging indent.
175
+ if (target.indent.hanging) target.indent.firstLine = 0;
176
+ }
177
+ if (spacing) Object.assign(target.spacing, spacing);
178
+ if (numbering) {
179
+ target.numbering = {
180
+ id: numbering.id ?? target.numbering?.id ?? 0,
181
+ level: numbering.level ?? target.numbering?.level,
182
+ };
183
+ }
184
+ if (borders) target.borders = { ...target.borders, ...borders };
185
+ if (tabs) {
186
+ // Tab stops accumulate down the styles; a `clear` stop removes an inherited one.
187
+ const stops = new Map(target.tabs.map((t) => [t.position, t]));
188
+ for (const t of tabs) {
189
+ if (t.kind === "clear") stops.delete(t.position);
190
+ else stops.set(t.position, { position: t.position, kind: t.kind, leader: t.leader ?? null });
191
+ }
192
+ target.tabs = [...stops.values()].sort((a, b) => a.position - b.position);
193
+ }
194
+ for (const [key, value] of Object.entries(props)) {
195
+ // A live node's attributes carry null for what is not set: it inherits.
196
+ if (PLAIN_KEYS.has(key) && value != null) (target as unknown as Json)[key] = value;
197
+ }
198
+ }
199
+
200
+ function cloneParagraph(p: Merging): Merging {
201
+ return {
202
+ ...p,
203
+ indent: { ...p.indent },
204
+ spacing: { ...p.spacing },
205
+ tabs: p.tabs.map((t) => ({ ...t })),
206
+ borders: p.borders
207
+ ? Object.fromEntries(Object.entries(p.borders).map(([side, b]) => [side, { ...b }]))
208
+ : null,
209
+ shading: p.shading ? { ...p.shading } : null,
210
+ numbering: p.numbering ? { ...p.numbering } : null,
211
+ };
212
+ }
213
+
214
+ function cloneRun(r: RunFormat): RunFormat {
215
+ return { ...r, font: { ...r.font } };
216
+ }
217
+
218
+ /** The toggle properties marks turn on or off (only those they name). */
219
+ function togglesOf(marks: readonly MarkJSON[] | undefined): Partial<Record<Toggle, boolean>> {
220
+ const out: Partial<Record<Toggle, boolean>> = {};
221
+ for (const m of marks ?? []) {
222
+ const a = (m.attrs ?? {}) as Json;
223
+ const value = a.value === undefined ? true : (a.value as boolean | null);
224
+ switch (m.type) {
225
+ case "bold":
226
+ case "italic": {
227
+ if (value !== null) out[m.type] = value;
228
+ const cs = a.complexScript as boolean | null | undefined;
229
+ if (cs !== null && cs !== undefined) out[m.type === "bold" ? "boldCs" : "italicCs"] = cs;
230
+ break;
231
+ }
232
+ case "caps":
233
+ case "smallCaps":
234
+ case "strike":
235
+ case "doubleStrike":
236
+ case "hidden":
237
+ if (value !== null) out[m.type] = value;
238
+ break;
239
+ default:
240
+ }
241
+ }
242
+ return out;
243
+ }
244
+
245
+ /** Theme color names (`w:themeColor`) and the theme's color scheme entries they use. */
246
+ const THEME_COLORS: Record<string, string> = {
247
+ text1: "dk1",
248
+ background1: "lt1",
249
+ text2: "dk2",
250
+ background2: "lt2",
251
+ dark1: "dk1",
252
+ light1: "lt1",
253
+ dark2: "dk2",
254
+ light2: "lt2",
255
+ hyperlink: "hlink",
256
+ followedHyperlink: "folHlink",
257
+ };
258
+
259
+ /** Run properties other than toggles, applied in order (later wins). */
260
+ function mergeRun(
261
+ target: RunFormat,
262
+ marks: readonly MarkJSON[] | undefined,
263
+ theme: ThemeJSON | undefined,
264
+ ): void {
265
+ for (const m of marks ?? []) {
266
+ const a = (m.attrs ?? {}) as Json;
267
+ switch (m.type) {
268
+ case "underline": {
269
+ const style = (a.style as string | undefined) ?? "single";
270
+ target.underline = style === "none" ? null : style;
271
+ target.underlineColor = (a.color as string | null | undefined) ?? null;
272
+ break;
273
+ }
274
+ case "font":
275
+ for (const script of ["ascii", "hAnsi", "eastAsia", "cs"] as const) {
276
+ const themed = a[`${script}Theme`] as string | null | undefined;
277
+ // A theme font the document has no theme for falls back to the name the file gives.
278
+ const name =
279
+ (themed && themeFont(theme, themed)) || (a[script] as string | null | undefined);
280
+ if (name) target.font[script] = name;
281
+ }
282
+ break;
283
+ case "fontSize":
284
+ if (typeof a.value === "number") target.size = a.value;
285
+ if (typeof a.complexScript === "number") target.sizeCs = a.complexScript;
286
+ break;
287
+ case "color": {
288
+ // With a tint or shade, `value` is the computed color: Word writes it there.
289
+ const themed =
290
+ a.themeColor && !a.themeTint && !a.themeShade
291
+ ? theme?.colors[THEME_COLORS[a.themeColor as string] ?? (a.themeColor as string)]
292
+ : undefined;
293
+ const value = (themed ?? a.value) as string | undefined;
294
+ target.color = value === undefined || value === "auto" ? null : value.toUpperCase();
295
+ break;
296
+ }
297
+ case "highlight":
298
+ target.highlight = a.value === "none" ? null : (a.value as string);
299
+ break;
300
+ case "shading":
301
+ target.shading =
302
+ a.fill === "auto" || a.fill === undefined ? null : String(a.fill).toUpperCase();
303
+ break;
304
+ case "verticalAlign":
305
+ target.verticalAlign = a.value as RunFormat["verticalAlign"];
306
+ break;
307
+ case "characterSpacing":
308
+ target.characterSpacing = a.value as number;
309
+ break;
310
+ default:
311
+ }
312
+ }
313
+ }
314
+
315
+ /** Direct formatting: toggles set, everything else applied. */
316
+ function applyDirect(
317
+ target: RunFormat,
318
+ marks: readonly MarkJSON[] | undefined,
319
+ theme: ThemeJSON | undefined,
320
+ ): void {
321
+ Object.assign(target, togglesOf(marks));
322
+ mergeRun(target, marks, theme);
323
+ }
324
+
325
+ /**
326
+ * A style chain's run formatting (root first). Within the chain a style overrides what it is
327
+ * based on; the chain's toggles then flip the run's (ECMA-376 17.7.3), which is why a bold
328
+ * character style on a bold heading shows plain text.
329
+ */
330
+ function applyStyles(
331
+ target: RunFormat,
332
+ chain: readonly (readonly MarkJSON[])[],
333
+ theme: ThemeJSON | undefined,
334
+ ): void {
335
+ const toggles: Partial<Record<Toggle, boolean>> = {};
336
+ for (const marks of chain) {
337
+ Object.assign(toggles, togglesOf(marks));
338
+ mergeRun(target, marks, theme);
339
+ }
340
+ for (const key of TOGGLES) if (toggles[key]) target[key] = !target[key];
341
+ }
342
+
343
+ /** A theme font reference (`minorHAnsi`) as a font name. */
344
+ function themeFont(theme: ThemeJSON | undefined, ref: string): string | null {
345
+ if (!theme) return null;
346
+ const set = ref.startsWith("major") ? theme.fonts.major : theme.fonts.minor;
347
+ const script = ref.slice(5);
348
+ const name = script === "EastAsia" ? set.eastAsia : script === "Bidi" ? set.cs : set.latin;
349
+ return name || null;
350
+ }
351
+
352
+ /** A counter in a number format (ST_NumberFormat); formats Foli does not know show as decimal. */
353
+ export function formatNumber(n: number, format: string | undefined): string {
354
+ switch (format ?? "decimal") {
355
+ case "none":
356
+ return "";
357
+ case "decimalZero":
358
+ return n >= 0 && n < 10 ? `0${n}` : String(n);
359
+ case "upperRoman":
360
+ return roman(n);
361
+ case "lowerRoman":
362
+ return roman(n).toLowerCase();
363
+ case "upperLetter":
364
+ return letters(n);
365
+ case "lowerLetter":
366
+ return letters(n).toLowerCase();
367
+ case "ordinal":
368
+ return ordinal(n);
369
+ default:
370
+ return String(n);
371
+ }
372
+ }
373
+
374
+ const ROMAN: [number, string][] = [
375
+ [1000, "M"],
376
+ [900, "CM"],
377
+ [500, "D"],
378
+ [400, "CD"],
379
+ [100, "C"],
380
+ [90, "XC"],
381
+ [50, "L"],
382
+ [40, "XL"],
383
+ [10, "X"],
384
+ [9, "IX"],
385
+ [5, "V"],
386
+ [4, "IV"],
387
+ [1, "I"],
388
+ ];
389
+
390
+ function roman(n: number): string {
391
+ if (n <= 0 || n >= 4000) return String(n);
392
+ let out = "";
393
+ let rest = n;
394
+ for (const [value, symbol] of ROMAN) {
395
+ for (; rest >= value; rest -= value) out += symbol;
396
+ }
397
+ return out;
398
+ }
399
+
400
+ /** Word's letters: A…Z, then AA…ZZ, AAA… (the letter repeated). */
401
+ function letters(n: number): string {
402
+ // shortcut: past 780 (30 letters) the number is written in digits, which bounds the string
403
+ // a hostile counter can build; check what Word shows there if a real document gets that far.
404
+ if (n <= 0 || n > 780) return String(n);
405
+ return String.fromCharCode(65 + ((n - 1) % 26)).repeat(Math.floor((n - 1) / 26) + 1);
406
+ }
407
+
408
+ function ordinal(n: number): string {
409
+ const tens = n % 100;
410
+ const suffix = tens >= 11 && tens <= 13 ? "th" : (["th", "st", "nd", "rd"][n % 10] ?? "th");
411
+ return `${n}${suffix}`;
412
+ }
413
+
414
+ type Envelope = Pick<FoliDocument, "defaults" | "styles" | "numbering" | "theme">;
415
+
416
+ interface Level {
417
+ instance: NumberingInstanceJSON;
418
+ abstract: AbstractNumberingJSON;
419
+ index: number;
420
+ level: NumberingLevelJSON;
421
+ }
422
+
423
+ /**
424
+ * Resolves a document's formatting from its envelope (defaults, styles, numbering, theme).
425
+ * Style resolutions are memoized: build one per envelope and reuse it.
426
+ */
427
+ export class Resolver {
428
+ readonly #styles = new Map<string, StyleJSON>();
429
+ #defaultParagraphStyle: string | undefined;
430
+ readonly #envelope: Envelope;
431
+ readonly #paragraphStyles = new Map<
432
+ string,
433
+ { paragraph: Merging; run: RunFormat; chain: StyleJSON[] }
434
+ >();
435
+ readonly #characterStyles = new Map<string, MarkJSON[][]>();
436
+ readonly #instances = new Map<number, NumberingInstanceJSON>();
437
+ readonly #abstracts = new Map<number, AbstractNumberingJSON>();
438
+
439
+ constructor(envelope: Envelope) {
440
+ this.#envelope = envelope;
441
+ // With duplicate ids, the first wins, as in Word.
442
+ for (const s of envelope.styles) if (!this.#styles.has(s.id)) this.#styles.set(s.id, s);
443
+ // With several default paragraph styles, the last one applies (ECMA-376 17.7.4.17).
444
+ for (const s of envelope.styles)
445
+ if (s.type === "paragraph" && s.isDefault) this.#defaultParagraphStyle = s.id;
446
+ for (const n of envelope.numbering.instances)
447
+ if (!this.#instances.has(n.id)) this.#instances.set(n.id, n);
448
+ for (const a of envelope.numbering.abstracts)
449
+ if (!this.#abstracts.has(a.id)) this.#abstracts.set(a.id, a);
450
+ }
451
+
452
+ /** A style and those it is based on, the root first (a cycle or a missing style ends it). */
453
+ #chain(id: string | undefined, type: StyleJSON["type"]): StyleJSON[] {
454
+ const out: StyleJSON[] = [];
455
+ const seen = new Set<string>();
456
+ for (let at = id; at !== undefined && !seen.has(at); ) {
457
+ seen.add(at);
458
+ const style = this.#styles.get(at);
459
+ if (style?.type !== type) break;
460
+ out.unshift(style);
461
+ at = style.basedOn;
462
+ }
463
+ return out;
464
+ }
465
+
466
+ /** A paragraph style's formatting over the defaults, memoized. */
467
+ #paragraphStyle(id: string | undefined) {
468
+ const key = id ?? "";
469
+ const known = this.#paragraphStyles.get(key);
470
+ if (known) return known;
471
+ const { defaults } = this.#envelope;
472
+ const paragraph = cloneParagraph(DEFAULT_PARAGRAPH);
473
+ const run = cloneRun(DEFAULT_RUN);
474
+ mergeParagraph(paragraph, defaults.paragraph);
475
+ applyDirect(run, defaults.run, this.#envelope.theme);
476
+ // A style that does not exist (or is not a paragraph style) is the default paragraph style.
477
+ let chain = id === undefined ? [] : this.#chain(id, "paragraph");
478
+ if (!chain.length) chain = this.#chain(this.#defaultParagraphStyle, "paragraph");
479
+ for (const style of chain) mergeParagraph(paragraph, style.paragraph);
480
+ applyStyles(
481
+ run,
482
+ chain.map((s) => s.run ?? []),
483
+ this.#envelope.theme,
484
+ );
485
+ paragraph.style = chain.at(-1)?.id ?? null;
486
+ const result = { paragraph, run, chain };
487
+ this.#paragraphStyles.set(key, result);
488
+ return result;
489
+ }
490
+
491
+ /**
492
+ * A paragraph's effective properties, and the formatting of its text before a run's own marks
493
+ * (`attrs`: the paragraph node's attributes, as JSON or a live node has them). The results are
494
+ * the caller's: changing them changes nothing else.
495
+ */
496
+ paragraph(attrs: Json): { paragraph: ParagraphFormat; run: RunFormat } {
497
+ const { paragraph, run } = this.#resolve(attrs);
498
+ return { paragraph, run };
499
+ }
500
+
501
+ #resolve(attrs: Json): { paragraph: ParagraphFormat; run: RunFormat; level: Level | undefined } {
502
+ const props = attrs as ParagraphPropertiesJSON;
503
+ const base = this.#paragraphStyle(props.style ?? undefined);
504
+ let paragraph = cloneParagraph(base.paragraph);
505
+ const directNumbering = props.numbering?.id != null;
506
+ if (props.numbering) mergeParagraph(paragraph, { numbering: props.numbering });
507
+ const level = this.#levelOf(paragraph);
508
+ if (level?.level.paragraph) {
509
+ if (directNumbering) {
510
+ // Numbering's indents come over the style's, under direct formatting.
511
+ mergeParagraph(paragraph, level.level.paragraph);
512
+ } else {
513
+ // Numbering given by the style: the style's own indents win over the level's.
514
+ const stacked = cloneParagraph(DEFAULT_PARAGRAPH);
515
+ mergeParagraph(stacked, this.#envelope.defaults.paragraph);
516
+ mergeParagraph(stacked, level.level.paragraph);
517
+ for (const style of base.chain) mergeParagraph(stacked, style.paragraph);
518
+ stacked.style = paragraph.style;
519
+ stacked.numbering = paragraph.numbering;
520
+ paragraph = stacked;
521
+ }
522
+ }
523
+ const { style: _style, numbering: _numbering, ...direct } = props;
524
+ mergeParagraph(paragraph, direct);
525
+ const numbering = level ? { id: level.instance.id, level: level.index } : null;
526
+ // Cloned: the merged values may be the styles' own objects.
527
+ return {
528
+ paragraph: { ...cloneParagraph(paragraph), numbering },
529
+ run: cloneRun(base.run),
530
+ level,
531
+ };
532
+ }
533
+
534
+ /**
535
+ * The number format (`decimal`, `bullet`…) of the numbering level a paragraph is in (`attrs`:
536
+ * its attributes), or null when it is not numbered.
537
+ */
538
+ numberFormat(attrs: Json): string | null {
539
+ const level = this.#resolve(attrs).level;
540
+ return level ? (level.level.format ?? "decimal") : null;
541
+ }
542
+
543
+ /** A run's formatting: its paragraph's (`paragraphRun`), its character style, then its own marks. */
544
+ run(paragraphRun: RunFormat, marks: readonly MarkJSON[]): RunFormat {
545
+ const run = cloneRun(paragraphRun);
546
+ const styleId = marks.find((m) => m.type === "characterStyle")?.attrs?.id as string | undefined;
547
+ if (styleId) {
548
+ let chain = this.#characterStyles.get(styleId);
549
+ if (!chain) {
550
+ chain = this.#chain(styleId, "character").map((s) => s.run ?? []);
551
+ this.#characterStyles.set(styleId, chain);
552
+ }
553
+ applyStyles(run, chain, this.#envelope.theme);
554
+ }
555
+ applyDirect(run, marks, this.#envelope.theme);
556
+ return run;
557
+ }
558
+
559
+ /**
560
+ * The numbering level a paragraph is in. A style that names only the instance (numbered
561
+ * headings) is in the level whose `style` is that style.
562
+ */
563
+ #levelOf(paragraph: Merging): Level | undefined {
564
+ const id = paragraph.numbering?.id;
565
+ const instance = id ? this.#instances.get(id) : undefined;
566
+ const abstract = instance && this.#abstractOf(instance.abstract);
567
+ if (!instance || !abstract) return undefined;
568
+ const index =
569
+ paragraph.numbering?.level ??
570
+ abstract.levels.find((l) => l.style !== undefined && l.style === paragraph.style)?.level ??
571
+ 0;
572
+ const level = this.#definition(instance, abstract, index);
573
+ return level ? { instance, abstract, index, level } : undefined;
574
+ }
575
+
576
+ #definition(instance: NumberingInstanceJSON, abstract: AbstractNumberingJSON, index: number) {
577
+ const override = instance.overrides?.find((o) => o.level === index)?.definition;
578
+ return override ?? abstract.levels.find((l) => l.level === index);
579
+ }
580
+
581
+ /** An abstract definition, following a numbering style's link to the definition it uses. */
582
+ #abstractOf(id: number): AbstractNumberingJSON | undefined {
583
+ let abstract = this.#abstracts.get(id);
584
+ for (let hops = 0; abstract?.numStyleLink && hops < 8; hops++) {
585
+ const style = this.#styles.get(abstract.numStyleLink);
586
+ const numId = style?.paragraph?.numbering?.id;
587
+ const instance = numId ? this.#instances.get(numId) : undefined;
588
+ const next = instance ? this.#abstracts.get(instance.abstract) : undefined;
589
+ if (!next || next === abstract) break;
590
+ abstract = next;
591
+ }
592
+ return abstract;
593
+ }
594
+
595
+ /**
596
+ * The list markers of a document's paragraphs in order (`paragraphs`: each paragraph's
597
+ * attributes). Counters are kept per abstract definition, so instances that share one continue
598
+ * a list; an instance's start override restarts it where the instance is first used; a level
599
+ * restarts after a paragraph of a level above it, or as its `restart` says.
600
+ */
601
+ markers(paragraphs: readonly Json[]): (ListMarker | null)[] {
602
+ const counters = new Map<number, (number | undefined)[]>();
603
+ const overridden = new Set<string>();
604
+ return paragraphs.map((attrs) => {
605
+ const { run, level: found } = this.#resolve(attrs);
606
+ if (!found) return null;
607
+ const { instance, abstract, index, level } = found;
608
+ let levels = counters.get(abstract.id);
609
+ if (!levels) {
610
+ levels = [];
611
+ counters.set(abstract.id, levels);
612
+ }
613
+ const startOf = (i: number) => {
614
+ const override = instance.overrides?.find((o) => o.level === i)?.start;
615
+ return override ?? this.#definition(instance, abstract, i)?.start ?? 0;
616
+ };
617
+ const key = `${instance.id}:${index}`;
618
+ const override = instance.overrides?.find((o) => o.level === index)?.start;
619
+ const current = levels[index];
620
+ if (override !== undefined && !overridden.has(key)) {
621
+ overridden.add(key);
622
+ levels[index] = override;
623
+ } else levels[index] = current === undefined ? startOf(index) : current + 1;
624
+ for (let deeper = index + 1; deeper < 9; deeper++) {
625
+ const restart = this.#definition(instance, abstract, deeper)?.restart;
626
+ if (restart === undefined || (restart !== 0 && index < restart)) levels[deeper] = undefined;
627
+ }
628
+ const text = (level.text ?? "").replace(/%([1-9])/g, (_, d: string) => {
629
+ const i = Number(d) - 1;
630
+ const format = level.legal ? "decimal" : this.#definition(instance, abstract, i)?.format;
631
+ return formatNumber(levels[i] ?? startOf(i), format);
632
+ });
633
+ const marker = cloneRun(run);
634
+ applyDirect(marker, attrs.markFormat as MarkJSON[] | undefined, this.#envelope.theme);
635
+ applyDirect(marker, level.run, this.#envelope.theme);
636
+ return {
637
+ text,
638
+ suffix: level.suffix ?? "tab",
639
+ justification: level.justification ?? "left",
640
+ run: marker,
641
+ instance: instance.id,
642
+ level: index,
643
+ };
644
+ });
645
+ }
646
+ }