@folijs/core 0.5.0 → 1.0.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 (202) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +0 -7
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +5 -1
  6. package/dist/document.js.map +1 -1
  7. package/dist/index.d.ts +4 -4
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +8 -4
  10. package/dist/index.js.map +1 -1
  11. package/dist/internal.d.ts +5 -0
  12. package/dist/internal.d.ts.map +1 -0
  13. package/dist/internal.js +7 -0
  14. package/dist/internal.js.map +1 -0
  15. package/dist/model/attrs.d.ts +0 -10
  16. package/dist/model/attrs.d.ts.map +1 -1
  17. package/dist/model/attrs.js +10 -2
  18. package/dist/model/attrs.js.map +1 -1
  19. package/dist/model/content.d.ts +1 -1
  20. package/dist/model/content.d.ts.map +1 -1
  21. package/dist/model/content.js +1 -1
  22. package/dist/model/content.js.map +1 -1
  23. package/dist/model/errors.d.ts +0 -2
  24. package/dist/model/errors.d.ts.map +1 -1
  25. package/dist/model/errors.js +4 -1
  26. package/dist/model/errors.js.map +1 -1
  27. package/dist/model/fragment.d.ts +1 -1
  28. package/dist/model/fragment.d.ts.map +1 -1
  29. package/dist/model/fragment.js +3 -1
  30. package/dist/model/fragment.js.map +1 -1
  31. package/dist/model/mark.d.ts +1 -1
  32. package/dist/model/mark.d.ts.map +1 -1
  33. package/dist/model/mark.js +1 -1
  34. package/dist/model/mark.js.map +1 -1
  35. package/dist/model/node.d.ts +4 -4
  36. package/dist/model/node.d.ts.map +1 -1
  37. package/dist/model/node.js +8 -4
  38. package/dist/model/node.js.map +1 -1
  39. package/dist/model/schema.d.ts +8 -8
  40. package/dist/model/schema.d.ts.map +1 -1
  41. package/dist/model/schema.js +4 -3
  42. package/dist/model/schema.js.map +1 -1
  43. package/dist/schema.d.ts +0 -11
  44. package/dist/schema.d.ts.map +1 -1
  45. package/dist/schema.js +2 -0
  46. package/dist/schema.js.map +1 -1
  47. package/dist/state/attempt.d.ts +1 -3
  48. package/dist/state/attempt.d.ts.map +1 -1
  49. package/dist/state/commands.d.ts +2 -0
  50. package/dist/state/commands.d.ts.map +1 -1
  51. package/dist/state/commands.js +38 -6
  52. package/dist/state/commands.js.map +1 -1
  53. package/dist/state/comments.d.ts +1 -7
  54. package/dist/state/comments.d.ts.map +1 -1
  55. package/dist/state/comments.js +13 -3
  56. package/dist/state/comments.js.map +1 -1
  57. package/dist/state/controls.d.ts +110 -0
  58. package/dist/state/controls.d.ts.map +1 -0
  59. package/dist/state/controls.js +1473 -0
  60. package/dist/state/controls.js.map +1 -0
  61. package/dist/state/editor.d.ts +188 -68
  62. package/dist/state/editor.d.ts.map +1 -1
  63. package/dist/state/editor.js +265 -79
  64. package/dist/state/editor.js.map +1 -1
  65. package/dist/state/fields.d.ts +68 -0
  66. package/dist/state/fields.d.ts.map +1 -0
  67. package/dist/state/fields.js +410 -0
  68. package/dist/state/fields.js.map +1 -0
  69. package/dist/state/fieldupdate.d.ts +132 -0
  70. package/dist/state/fieldupdate.d.ts.map +1 -0
  71. package/dist/state/fieldupdate.js +1575 -0
  72. package/dist/state/fieldupdate.js.map +1 -0
  73. package/dist/state/find.d.ts +66 -0
  74. package/dist/state/find.d.ts.map +1 -0
  75. package/dist/state/find.js +405 -0
  76. package/dist/state/find.js.map +1 -0
  77. package/dist/state/history.d.ts +2 -0
  78. package/dist/state/history.d.ts.map +1 -1
  79. package/dist/state/history.js +44 -7
  80. package/dist/state/history.js.map +1 -1
  81. package/dist/state/index.d.ts +13 -6
  82. package/dist/state/index.d.ts.map +1 -1
  83. package/dist/state/index.js +12 -5
  84. package/dist/state/index.js.map +1 -1
  85. package/dist/state/lists.d.ts +3 -3
  86. package/dist/state/lists.d.ts.map +1 -1
  87. package/dist/state/lists.js.map +1 -1
  88. package/dist/state/mark.d.ts +1 -17
  89. package/dist/state/mark.d.ts.map +1 -1
  90. package/dist/state/mark.js +10 -1
  91. package/dist/state/mark.js.map +1 -1
  92. package/dist/state/navigation.d.ts +70 -0
  93. package/dist/state/navigation.d.ts.map +1 -0
  94. package/dist/state/navigation.js +226 -0
  95. package/dist/state/navigation.js.map +1 -0
  96. package/dist/state/notes.d.ts +84 -0
  97. package/dist/state/notes.d.ts.map +1 -0
  98. package/dist/state/notes.js +451 -0
  99. package/dist/state/notes.js.map +1 -0
  100. package/dist/state/review.d.ts +8 -4
  101. package/dist/state/review.d.ts.map +1 -1
  102. package/dist/state/review.js +134 -18
  103. package/dist/state/review.js.map +1 -1
  104. package/dist/state/sections.d.ts +91 -0
  105. package/dist/state/sections.d.ts.map +1 -0
  106. package/dist/state/sections.js +479 -0
  107. package/dist/state/sections.js.map +1 -0
  108. package/dist/state/state.d.ts +13 -7
  109. package/dist/state/state.d.ts.map +1 -1
  110. package/dist/state/state.js +9 -2
  111. package/dist/state/state.js.map +1 -1
  112. package/dist/state/stories.d.ts +2 -0
  113. package/dist/state/stories.d.ts.map +1 -0
  114. package/dist/state/stories.js +259 -0
  115. package/dist/state/stories.js.map +1 -0
  116. package/dist/state/tables.d.ts +1 -36
  117. package/dist/state/tables.d.ts.map +1 -1
  118. package/dist/state/tables.js +25 -6
  119. package/dist/state/tables.js.map +1 -1
  120. package/dist/state/track.d.ts +1 -6
  121. package/dist/state/track.d.ts.map +1 -1
  122. package/dist/state/track.js +65 -9
  123. package/dist/state/track.js.map +1 -1
  124. package/dist/state/word.d.ts +47 -55
  125. package/dist/state/word.d.ts.map +1 -1
  126. package/dist/state/word.js +306 -19
  127. package/dist/state/word.js.map +1 -1
  128. package/dist/state/wordclip.d.ts +17 -6
  129. package/dist/state/wordclip.d.ts.map +1 -1
  130. package/dist/state/wordclip.js +254 -17
  131. package/dist/state/wordclip.js.map +1 -1
  132. package/dist/state/wordformat.d.ts +1 -86
  133. package/dist/state/wordformat.d.ts.map +1 -1
  134. package/dist/state/wordformat.js +114 -12
  135. package/dist/state/wordformat.js.map +1 -1
  136. package/dist/transform/stepmap.d.ts +0 -2
  137. package/dist/transform/stepmap.d.ts.map +1 -1
  138. package/dist/v3/check.d.ts +0 -25
  139. package/dist/v3/check.d.ts.map +1 -1
  140. package/dist/v3/check.js +35 -7
  141. package/dist/v3/check.js.map +1 -1
  142. package/dist/v3/document.d.ts +135 -10
  143. package/dist/v3/document.d.ts.map +1 -1
  144. package/dist/v3/document.js +192 -38
  145. package/dist/v3/document.js.map +1 -1
  146. package/dist/v3/extensions.d.ts +43 -0
  147. package/dist/v3/extensions.d.ts.map +1 -0
  148. package/dist/v3/extensions.js +154 -0
  149. package/dist/v3/extensions.js.map +1 -0
  150. package/dist/v3/index.d.ts +3 -2
  151. package/dist/v3/index.d.ts.map +1 -1
  152. package/dist/v3/index.js +3 -2
  153. package/dist/v3/index.js.map +1 -1
  154. package/dist/v3/resolve.d.ts +9 -3
  155. package/dist/v3/resolve.d.ts.map +1 -1
  156. package/dist/v3/resolve.js +28 -4
  157. package/dist/v3/resolve.js.map +1 -1
  158. package/dist/v3/schema.d.ts +5 -16
  159. package/dist/v3/schema.d.ts.map +1 -1
  160. package/dist/v3/schema.js +167 -7
  161. package/dist/v3/schema.js.map +1 -1
  162. package/package.json +5 -1
  163. package/src/document.ts +5 -1
  164. package/src/index.ts +330 -4
  165. package/src/internal.ts +50 -0
  166. package/src/model/attrs.ts +10 -2
  167. package/src/model/content.ts +1 -1
  168. package/src/model/errors.ts +4 -1
  169. package/src/model/fragment.ts +2 -1
  170. package/src/model/mark.ts +1 -1
  171. package/src/model/node.ts +6 -4
  172. package/src/model/schema.ts +9 -3
  173. package/src/schema.ts +2 -0
  174. package/src/state/commands.ts +41 -4
  175. package/src/state/comments.ts +12 -3
  176. package/src/state/controls.ts +1612 -0
  177. package/src/state/editor.ts +508 -143
  178. package/src/state/fields.ts +444 -0
  179. package/src/state/fieldupdate.ts +1771 -0
  180. package/src/state/find.ts +518 -0
  181. package/src/state/history.ts +53 -7
  182. package/src/state/index.ts +125 -1
  183. package/src/state/lists.ts +2 -2
  184. package/src/state/mark.ts +10 -1
  185. package/src/state/navigation.ts +305 -0
  186. package/src/state/notes.ts +529 -0
  187. package/src/state/numeric-pictures.word.json +172 -0
  188. package/src/state/review.ts +172 -19
  189. package/src/state/sections.ts +578 -0
  190. package/src/state/state.ts +21 -3
  191. package/src/state/stories.ts +312 -0
  192. package/src/state/tables.ts +29 -7
  193. package/src/state/track.ts +72 -10
  194. package/src/state/word.ts +360 -24
  195. package/src/state/wordclip.ts +282 -32
  196. package/src/state/wordformat.ts +116 -12
  197. package/src/v3/check.ts +35 -7
  198. package/src/v3/document.ts +358 -50
  199. package/src/v3/extensions.ts +201 -0
  200. package/src/v3/index.ts +16 -0
  201. package/src/v3/resolve.ts +38 -9
  202. package/src/v3/schema.ts +174 -7
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Custom nodes and marks (ADR-0008): extensions add namespaced inline or block leaves and marks
3
+ * to the Word schema. A namespaced type the schema does not have is never dropped: it is read as
4
+ * a foreign node or mark holding its type and attributes, and written back as it was.
5
+ */
6
+ import type { Attrs, MarkJSON, MarkSpec, NodeJSON, NodeSpec } from "../model/index.js";
7
+ import { Schema } from "../model/index.js";
8
+ import type { Plugin } from "../state/state.js";
9
+ import { isRecord } from "./check.js";
10
+ import { CUSTOM_TYPE, schema as wordSchema } from "./schema.js";
11
+
12
+ /** A custom node type: an inline leaf (`inline: true`) or a block leaf. */
13
+ export interface ExtensionNodeSpec extends Omit<NodeSpec, "content" | "text"> {
14
+ /** The text it stands for in plain text, find, the clipboard and `.docx`. */
15
+ text: (attrs: Attrs) => string;
16
+ }
17
+
18
+ /**
19
+ * What an app adds to the editor: custom node and mark types, named `<namespace>:<name>`
20
+ * (lowercase letters, digits and `-`), and plugins. Given to `createEditor` and `parseDocument`.
21
+ */
22
+ export interface Extension {
23
+ name: string;
24
+ nodes?: Readonly<Record<string, ExtensionNodeSpec>>;
25
+ marks?: Readonly<Record<string, MarkSpec>>;
26
+ plugins?: readonly Plugin[];
27
+ }
28
+
29
+ /** Options of `parseDocument`. */
30
+ export interface ParseOptions {
31
+ /** The custom types the document may hold as themselves; others are kept as foreign. */
32
+ extensions?: readonly Extension[];
33
+ }
34
+
35
+ /** Options of `parseContent`. */
36
+ export interface ContentOptions extends ParseOptions {
37
+ /** Where the content is, for error messages (default `content`). */
38
+ path?: string;
39
+ /** Content to paste, which a table may end. */
40
+ fragment?: boolean;
41
+ /**
42
+ * The schema to parse with (an editor's `state.schema`), in place of `extensions`.
43
+ * @internal
44
+ */
45
+ schema?: Schema;
46
+ }
47
+
48
+ /** Schemas by extension list: an array given again gets the same schema (do not mutate it). */
49
+ const schemas = new WeakMap<readonly Extension[], Schema>();
50
+
51
+ /**
52
+ * The Word schema with `extensions`' types (the Word schema itself when there are none). Throws
53
+ * a `RangeError` on a name that is not namespaced or is taken twice, or a node that is not a leaf.
54
+ * @internal
55
+ */
56
+ export function schemaWith(extensions: readonly Extension[] | undefined): Schema {
57
+ if (!extensions?.length) return wordSchema;
58
+ const known = schemas.get(extensions);
59
+ if (known) return known;
60
+ const nodes: Record<string, NodeSpec> = { ...wordSchema.spec.nodes };
61
+ const marks: Record<string, MarkSpec> = { ...wordSchema.spec.marks };
62
+ const add = (into: Record<string, unknown>, name: string, from: string) => {
63
+ if (!CUSTOM_TYPE.test(name))
64
+ throw new RangeError(`${from}: ${name} is not a namespaced type (<namespace>:<name>)`);
65
+ if (Object.hasOwn(nodes, name) || Object.hasOwn(marks, name))
66
+ throw new RangeError(`${from}: ${name} is declared twice`);
67
+ return into;
68
+ };
69
+ for (const extension of extensions) {
70
+ for (const [name, spec] of Object.entries(extension.nodes ?? {})) {
71
+ const group = spec.inline ? "inline" : "block";
72
+ if ((spec as NodeSpec).content || (spec.group !== undefined && spec.group !== group))
73
+ throw new RangeError(`${extension.name}: ${name} must be a leaf in the ${group} group`);
74
+ if (typeof spec.text !== "function")
75
+ throw new RangeError(`${extension.name}: ${name} needs text(attrs)`);
76
+ add(nodes, name, extension.name)[name] = { ...spec, group };
77
+ }
78
+ for (const [name, spec] of Object.entries(extension.marks ?? {}))
79
+ add(marks, name, extension.name)[name] = spec;
80
+ }
81
+ const schema = new Schema({ nodes, marks });
82
+ schemas.set(extensions, schema);
83
+ return schema;
84
+ }
85
+
86
+ /** What a foreign node's JSON carries in memory: the text its `.docx` control showed. */
87
+ const FOREIGN_TEXT = Symbol.for("foli.foreignText");
88
+
89
+ /**
90
+ * The text a custom node's JSON carries in memory (read from a `.docx` control), if any.
91
+ */
92
+ export const foreignTextOf = (json: NodeJSON): string | undefined =>
93
+ (json as { [FOREIGN_TEXT]?: string })[FOREIGN_TEXT];
94
+
95
+ /**
96
+ * `json` carrying `text` in memory: never saved (`JSON.stringify` and copies leave it out).
97
+ */
98
+ export function withForeignText<T extends NodeJSON>(json: T, text: string): T {
99
+ Object.defineProperty(json, FOREIGN_TEXT, { value: text, configurable: true });
100
+ return json;
101
+ }
102
+
103
+ const FOREIGN = new Set(["foreignInline", "foreignBlock"]);
104
+ /** The deepest JSON walked; deeper input is left to the schema, which refuses it. */
105
+ const MAX_DEPTH = 302;
106
+
107
+ function resolveMarks(marks: unknown, schema: Schema): unknown {
108
+ if (!Array.isArray(marks)) return marks;
109
+ let out: unknown[] | undefined;
110
+ marks.forEach((mark, i) => {
111
+ let next = mark;
112
+ if (isRecord(mark) && typeof mark.type === "string") {
113
+ const attrs = isRecord(mark.attrs) ? mark.attrs : undefined;
114
+ if (CUSTOM_TYPE.test(mark.type) && !schema.marks[mark.type])
115
+ next = { type: "foreign", attrs: { type: mark.type, attrs: mark.attrs ?? null } };
116
+ else if (
117
+ mark.type === "foreign" &&
118
+ typeof attrs?.type === "string" &&
119
+ CUSTOM_TYPE.test(attrs.type) &&
120
+ schema.marks[attrs.type]
121
+ )
122
+ next = { type: attrs.type, ...(isRecord(attrs.attrs) ? { attrs: attrs.attrs } : {}) };
123
+ }
124
+ if (next === mark) return;
125
+ out ??= marks.slice();
126
+ out[i] = next;
127
+ });
128
+ return out ?? marks;
129
+ }
130
+
131
+ /**
132
+ * Untrusted content JSON with custom types `schema` lacks as foreign nodes and marks, and foreign
133
+ * ones whose type it has as themselves. Returns `value` itself when nothing changes; never
134
+ * changes it.
135
+ * @internal
136
+ */
137
+ export function resolveCustom(value: unknown, schema: Schema, inline = false, depth = 0): unknown {
138
+ if (!isRecord(value) || depth > MAX_DEPTH) return value;
139
+ const type = value.type;
140
+ const marks = resolveMarks(value.marks, schema);
141
+ if (typeof type === "string" && CUSTOM_TYPE.test(type) && !schema.nodes[type]) {
142
+ const text = foreignTextOf(value as unknown as NodeJSON);
143
+ return {
144
+ type: inline ? "foreignInline" : "foreignBlock",
145
+ attrs: { type, attrs: value.attrs ?? null, ...(text === undefined ? {} : { text }) },
146
+ ...(marks === undefined ? {} : { marks }),
147
+ };
148
+ }
149
+ if (typeof type === "string" && FOREIGN.has(type) && isRecord(value.attrs)) {
150
+ const custom = value.attrs.type;
151
+ if (typeof custom === "string" && CUSTOM_TYPE.test(custom) && schema.nodes[custom]) {
152
+ const attrs = value.attrs.attrs;
153
+ return {
154
+ type: custom,
155
+ ...(isRecord(attrs) ? { attrs } : {}),
156
+ ...(marks === undefined ? {} : { marks }),
157
+ };
158
+ }
159
+ }
160
+ let content = value.content;
161
+ if (Array.isArray(content)) {
162
+ const items: unknown[] = content;
163
+ const parent = typeof type === "string" ? schema.nodes[type] : undefined;
164
+ const inner = parent ? parent.inlineContent : false;
165
+ let out: unknown[] | undefined;
166
+ items.forEach((child, i) => {
167
+ const next = resolveCustom(child, schema, inner, depth + 1);
168
+ if (next === child) return;
169
+ out ??= items.slice();
170
+ out[i] = next;
171
+ });
172
+ content = out ?? items;
173
+ }
174
+ return content === value.content && marks === value.marks ? value : { ...value, content, marks };
175
+ }
176
+
177
+ /** A foreign mark's JSON as the custom mark it stands for. */
178
+ const markOut = (mark: MarkJSON): MarkJSON =>
179
+ mark.type === "foreign" && mark.attrs
180
+ ? {
181
+ type: String(mark.attrs.type),
182
+ ...(isRecord(mark.attrs.attrs) ? { attrs: mark.attrs.attrs } : {}),
183
+ }
184
+ : mark;
185
+
186
+ /**
187
+ * Content JSON with foreign nodes and marks written back as the custom types they stand for (a
188
+ * foreign node's text carried in memory: `foreignTextOf`). Changes `json` in place.
189
+ * @internal
190
+ */
191
+ export function writeCustom(json: NodeJSON): NodeJSON {
192
+ if (json.marks?.some((m) => m.type === "foreign")) json.marks = json.marks.map(markOut);
193
+ if (FOREIGN.has(json.type) && json.attrs) {
194
+ const { type, attrs, text } = json.attrs as { type: string; attrs?: unknown; text?: unknown };
195
+ const out: NodeJSON = { type, ...(isRecord(attrs) ? { attrs } : {}) };
196
+ if (json.marks) out.marks = json.marks;
197
+ return typeof text === "string" ? withForeignText(out, text) : out;
198
+ }
199
+ if (json.content) json.content = json.content.map(writeCustom);
200
+ return json;
201
+ }
package/src/v3/index.ts CHANGED
@@ -3,11 +3,16 @@ export {
3
3
  type BorderJSON,
4
4
  type CellPropertiesJSON,
5
5
  type CommentJSON,
6
+ type ControlJSON,
7
+ checkControl,
6
8
  createDocument,
7
9
  type FoliDocument,
8
10
  type FoliDocumentV3,
11
+ type FoliDocumentV4,
9
12
  type MeasureJSON,
10
13
  migrateToV4,
14
+ migrateToV5,
15
+ type NotePropertiesJSON,
11
16
  type NumberingInstanceJSON,
12
17
  type NumberingLevelJSON,
13
18
  type ParagraphPropertiesJSON,
@@ -17,13 +22,23 @@ export {
17
22
  type RowPropertiesJSON,
18
23
  SCHEMA_VERSION,
19
24
  type SectionJSON,
25
+ type StoryJSON,
20
26
  type StyleJSON,
21
27
  TABLE_CONDITIONS,
22
28
  type TableCondition,
23
29
  type TableConditionJSON,
24
30
  type TablePropertiesJSON,
25
31
  type ThemeJSON,
32
+ type WordSettingsJSON,
26
33
  } from "./document.js";
34
+ export {
35
+ type ContentOptions,
36
+ type Extension,
37
+ type ExtensionNodeSpec,
38
+ foreignTextOf,
39
+ type ParseOptions,
40
+ withForeignText,
41
+ } from "./extensions.js";
27
42
  export { migrateToV3 } from "./migrate.js";
28
43
  export {
29
44
  type CellFormat,
@@ -37,6 +52,7 @@ export {
37
52
  tableConditions,
38
53
  } from "./resolve.js";
39
54
  export {
55
+ CUSTOM_TYPE,
40
56
  checkSection,
41
57
  HIGHLIGHT_COLORS,
42
58
  JUSTIFICATIONS,
package/src/v3/resolve.ts CHANGED
@@ -84,12 +84,16 @@ export interface ParagraphFormat {
84
84
  export interface ListMarker {
85
85
  /** As Word shows it ("1.", "1.1", "(a)", or a bullet's character as the file has it). */
86
86
  text: string;
87
+ /** The same without the words of its format: "Section 1." is "1." (`REF \\t`). */
88
+ plain: string;
87
89
  /** What follows the marker. */
88
90
  suffix: "tab" | "space" | "nothing";
89
91
  justification: string;
90
92
  /** The marker's formatting: the paragraph's, its mark's, then the level's run properties. */
91
93
  run: RunFormat;
92
94
  instance: number;
95
+ /** The definition counted: instances sharing one go on from each other. */
96
+ abstract: number;
93
97
  level: number;
94
98
  }
95
99
 
@@ -371,11 +375,22 @@ export function formatNumber(n: number, format: string | undefined): string {
371
375
  return letters(n).toLowerCase();
372
376
  case "ordinal":
373
377
  return ordinal(n);
378
+ case "chicago":
379
+ return chicago(n);
380
+ case "numberInDash":
381
+ return `- ${n} -`;
374
382
  default:
375
383
  return String(n);
376
384
  }
377
385
  }
378
386
 
387
+ /** Word's `chicago` marks: `*`, `†`, `‡`, `§`, then the same doubled, tripled... */
388
+ function chicago(n: number): string {
389
+ const marks = ["*", "†", "‡", "§"];
390
+ if (n < 1) return String(n);
391
+ return (marks[(n - 1) % 4] as string).repeat(Math.ceil(n / 4));
392
+ }
393
+
379
394
  const ROMAN: [number, string][] = [
380
395
  [1000, "M"],
381
396
  [900, "CM"],
@@ -499,8 +514,8 @@ function last<T, V>(layers: readonly T[], pick: (layer: T) => V | undefined | nu
499
514
  * columns, banded rows, first and last column, first and last row, then the corners. The first
500
515
  * and last row and column (when `look` turns them on) are left out of banding.
501
516
  *
502
- * shortcut: banding counts cells (not grid columns) and leaves out only the first and last
503
- * row; check against Word on the corpus's banded table (06) when tables reach the pages (10.5).
517
+ * shortcut: banding and the first and last column count cells, not grid columns; not checked
518
+ * against Word's drawing of a table with merged cells or rows starting late (`gridBefore`).
504
519
  */
505
520
  export function tableConditions(
506
521
  look: NonNullable<TablePropertiesJSON["look"]>,
@@ -532,7 +547,7 @@ export function tableConditions(
532
547
  return out;
533
548
  }
534
549
 
535
- type Envelope = Pick<FoliDocument, "defaults" | "styles" | "numbering" | "theme">;
550
+ type Envelope = Pick<FoliDocument, "defaults" | "styles" | "numbering" | "theme" | "settings">;
536
551
 
537
552
  interface Level {
538
553
  instance: NumberingInstanceJSON;
@@ -559,6 +574,11 @@ export class Resolver {
559
574
  #defaultTableStyle: string | undefined;
560
575
  readonly #layers = new Map<string, TableLayer>();
561
576
 
577
+ /** Whether a paragraph's space after and the next one's space before add up (else: the larger). */
578
+ get addsParagraphSpacing(): boolean {
579
+ return this.#envelope.settings?.doNotUseHTMLParagraphAutoSpacing === true;
580
+ }
581
+
562
582
  constructor(envelope: Envelope) {
563
583
  this.#envelope = envelope;
564
584
  // With duplicate ids, the first wins, as in Word.
@@ -693,7 +713,7 @@ export class Resolver {
693
713
  * for the cell, which come between them as ECMA-376 17.7.2 orders them), memoized.
694
714
  *
695
715
  * shortcut: Word lets a table style's properties win over the default paragraph style's
696
- * (Normal) in some cases; not modeled until the corpus's tables are measured on pages (10.5).
716
+ * (Normal) in some cases; not modeled (docs/limitations.md).
697
717
  */
698
718
  #paragraphStyle(id: string | undefined, layer?: TableLayer) {
699
719
  const key = JSON.stringify([layer?.key ?? null, id ?? null]);
@@ -846,6 +866,11 @@ export class Resolver {
846
866
  const counters = new Map<number, (number | undefined)[]>();
847
867
  const overridden = new Set<string>();
848
868
  return paragraphs.map((attrs) => {
869
+ // Not numbered (most paragraphs): no number without resolving the whole paragraph, which
870
+ // the view does for every block on every change (12.11). As `#resolve` merges numbering.
871
+ const numbering = (attrs as ParagraphPropertiesJSON).numbering;
872
+ const style = (attrs as ParagraphPropertiesJSON).style ?? undefined;
873
+ if (!(numbering?.id ?? this.#paragraphStyle(style).paragraph.numbering?.id)) return null;
849
874
  const { run, level: found } = this.#resolve(attrs);
850
875
  if (!found) return null;
851
876
  const { instance, abstract, index, level } = found;
@@ -869,20 +894,24 @@ export class Resolver {
869
894
  const restart = this.#definition(instance, abstract, deeper)?.restart;
870
895
  if (restart === undefined || (restart !== 0 && index < restart)) levels[deeper] = undefined;
871
896
  }
872
- const text = (level.text ?? "").replace(/%([1-9])/g, (_, d: string) => {
873
- const i = Number(d) - 1;
874
- const format = level.legal ? "decimal" : this.#definition(instance, abstract, i)?.format;
875
- return formatNumber(levels[i] ?? startOf(i), format);
876
- });
897
+ const written = (template: string) =>
898
+ template.replace(/%([1-9])/g, (_, d: string) => {
899
+ const i = Number(d) - 1;
900
+ const format = level.legal ? "decimal" : this.#definition(instance, abstract, i)?.format;
901
+ return formatNumber(levels[i] ?? startOf(i), format);
902
+ });
903
+ const text = written(level.text ?? "");
877
904
  const marker = cloneRun(run);
878
905
  applyDirect(marker, attrs.markFormat as MarkJSON[] | undefined, this.#envelope.theme);
879
906
  applyDirect(marker, level.run, this.#envelope.theme);
880
907
  return {
881
908
  text,
909
+ plain: written((level.text ?? "").replace(/\p{L}+/gu, "")).trim(),
882
910
  suffix: level.suffix ?? "tab",
883
911
  justification: level.justification ?? "left",
884
912
  run: marker,
885
913
  instance: instance.id,
914
+ abstract: abstract.id,
886
915
  level: index,
887
916
  };
888
917
  });
package/src/v3/schema.ts CHANGED
@@ -61,7 +61,9 @@ export const JUSTIFICATIONS = [
61
61
  ] as const;
62
62
  export type Justification = (typeof JUSTIFICATIONS)[number];
63
63
 
64
+ /** @internal */
64
65
  export const LINE_RULES = ["auto", "exact", "atLeast"] as const;
66
+ /** @internal */
65
67
  export const TAB_KINDS = [
66
68
  "left",
67
69
  "center",
@@ -73,7 +75,9 @@ export const TAB_KINDS = [
73
75
  "start",
74
76
  "end",
75
77
  ] as const;
78
+ /** @internal */
76
79
  export const TAB_LEADERS = ["none", "dot", "hyphen", "underscore", "heavy", "middleDot"] as const;
80
+ /** @internal */
77
81
  export const SECTION_TYPES = [
78
82
  "nextPage",
79
83
  "continuous",
@@ -81,6 +85,7 @@ export const SECTION_TYPES = [
81
85
  "oddPage",
82
86
  "nextColumn",
83
87
  ] as const;
88
+ /** @internal */
84
89
  export const VERTICAL_ALIGNS = ["baseline", "superscript", "subscript"] as const;
85
90
  /** Word's highlight colors (ST_HighlightColor); any other color is shading. */
86
91
  export const HIGHLIGHT_COLORS = [
@@ -102,6 +107,7 @@ export const HIGHLIGHT_COLORS = [
102
107
  "lightGray",
103
108
  "none",
104
109
  ] as const;
110
+ /** @internal */
105
111
  export const THEME_FONTS = [
106
112
  "majorAscii",
107
113
  "majorHAnsi",
@@ -136,12 +142,27 @@ const ID = int(0, 2_147_483_647);
136
142
  const revisionFields = { id: ID, author: str(), date: nullable(date) };
137
143
  const revision = shape(revisionFields, ["id", "author"]);
138
144
 
145
+ /**
146
+ * How notes are placed and numbered (`w:footnotePr`, `w:endnotePr`), for a document or section.
147
+ * @internal
148
+ */
149
+ export const checkNoteProperties: Check = shape({
150
+ position: oneOf(["pageBottom", "beneathText", "sectEnd", "docEnd"]),
151
+ format: token,
152
+ start: ID,
153
+ restart: oneOf(["continuous", "eachSect", "eachPage"]),
154
+ });
155
+
156
+ /** Word's limit on a section's columns. */
157
+ const MAX_SECTION_COLUMNS = 45;
158
+
139
159
  /**
140
160
  * A section's page setup (`w:sectPr`): on the last paragraph of each section, and the
141
161
  * envelope's for the last. Every part is optional (Word's defaults apply); `{}` is a section
142
162
  * break with Word's defaults.
143
163
  */
144
- export const checkSection: Check = shape(
164
+ export const checkSection: Check = (value) => sectionShape(value);
165
+ const sectionShape: Check = shape(
145
166
  {
146
167
  pageSize: shape({
147
168
  width: int(1, MAX_TWIPS),
@@ -161,6 +182,23 @@ export const checkSection: Check = shape(
161
182
  titlePage: bool,
162
183
  headers: shape({ default: text(), first: text(), even: text() }),
163
184
  footers: shape({ default: text(), first: text(), even: text() }),
185
+ /** `w:cols` (schema v5): `widths` when the columns are not equal. */
186
+ columns: shape({
187
+ count: int(1, MAX_SECTION_COLUMNS),
188
+ space: positiveTwips,
189
+ equalWidth: bool,
190
+ separator: bool,
191
+ widths: listOf(
192
+ shape({ width: positiveTwips, space: positiveTwips }, ["width"]),
193
+ MAX_SECTION_COLUMNS,
194
+ ),
195
+ }),
196
+ /** `w:pgNumType` (schema v5). */
197
+ pageNumbers: shape({ start: ID, format: token }),
198
+ footnotes: checkNoteProperties,
199
+ endnotes: checkNoteProperties,
200
+ /** `w:sectPrChange`: a tracked change of the page setup, and the setup before it. */
201
+ change: shape({ ...revisionFields, previous: checkSection }, ["id", "author", "previous"]),
164
202
  ext: xml,
165
203
  },
166
204
  [],
@@ -265,9 +303,14 @@ const propertiesCheck =
265
303
  return undefined;
266
304
  };
267
305
 
268
- /** Table, row and cell properties as a table style or a row's exceptions give them. */
306
+ /**
307
+ * Table, row and cell properties as a table style or a row's exceptions give them.
308
+ * @internal
309
+ */
269
310
  export const checkTableProperties: Check = propertiesCheck(tableProperties);
311
+ /** @internal */
270
312
  export const checkRowProperties: Check = propertiesCheck(rowProperties);
313
+ /** @internal */
271
314
  export const checkCellProperties: Check = propertiesCheck(cellProperties);
272
315
 
273
316
  /** EMU (English Metric Units: 914 400 per inch), as DrawingML measures pictures. */
@@ -312,7 +355,10 @@ export const RUN_PROPERTY_MARKS = [
312
355
  "characterSpacing",
313
356
  ];
314
357
 
315
- /** Run properties given as marks JSON (a style's, a paragraph mark's, a recorded change's previous). */
358
+ /**
359
+ * Run properties given as marks JSON (a style's, a paragraph mark's, a recorded change's previous).
360
+ * @internal
361
+ */
316
362
  export const checkRunProperties: Check = (v) => {
317
363
  if (!Array.isArray(v)) return "must be an array of marks";
318
364
  for (const mark of v) {
@@ -387,10 +433,16 @@ const paragraphProperties: Record<string, AttributeSpec> = {
387
433
  ext: nullableAttr(xml),
388
434
  };
389
435
 
390
- /** The names of the paragraph properties (`w:pPr`) among a paragraph's attributes. */
436
+ /**
437
+ * The names of the paragraph properties (`w:pPr`) among a paragraph's attributes.
438
+ * @internal
439
+ */
391
440
  export const PARAGRAPH_PROPERTY_KEYS: readonly string[] = Object.keys(paragraphProperties);
392
441
 
393
- /** Paragraph properties as a style, a numbering level, the defaults or a recorded change give them. */
442
+ /**
443
+ * Paragraph properties as a style, a numbering level, the defaults or a recorded change give them.
444
+ * @internal
445
+ */
394
446
  export const checkParagraphProperties: Check = (v) => {
395
447
  if (!isRecord(v)) return "must be an object";
396
448
  for (const [key, value] of Object.entries(v)) {
@@ -433,11 +485,70 @@ const reviewMark: MarkSpec = {
433
485
  };
434
486
  /** A marker's own unknown attributes (`w:displacedByCustomXml`…). */
435
487
  const markerAttributes = { attributes: nullableAttr(attributes) };
488
+ /** Ids of content controls, outermost first: at least one, none twice. */
489
+ const controlIds: Check = (v) => {
490
+ const error = listOf(text(), 64)(v);
491
+ if (error) return error;
492
+ const ids = v as string[];
493
+ if (!ids.length) return "must not be empty (use null)";
494
+ return new Set(ids).size === ids.length ? undefined : "must not repeat an id";
495
+ };
496
+ /** The content controls around a block, row or cell (schema v5, ADR-0007). */
497
+ const controlsAttr = { controls: nullableAttr(controlIds) };
498
+ /** Part of a field (schema v5): stands in a run, verbatim XML of what the model does not hold. */
499
+ const fieldPart = { group: "inline", inline: true, selectable: false } as const;
436
500
  const fontName = markAttr(nullable(text()), null);
437
501
  const themeFont = markAttr(nullable(oneOf(THEME_FONTS)), null);
438
502
  const hexByte = (v: unknown) =>
439
503
  typeof v === "string" && /^[0-9A-Fa-f]{2}$/.test(v) ? undefined : "must be a hex byte";
440
504
 
505
+ /**
506
+ * The name of a custom node or mark type (ADR-0008): `<namespace>:<name>`, lowercase letters,
507
+ * digits and `-`. Word's types never have a colon.
508
+ */
509
+ export const CUSTOM_TYPE = /^[a-z0-9-]+:[a-z0-9-]+$/;
510
+
511
+ /** The largest custom attributes a foreign node or mark holds, as JSON text. */
512
+ const MAX_FOREIGN_ATTRS = 65_536;
513
+
514
+ /** Plain JSON (no `undefined`, functions, non-finite numbers or cycles), nested at most 32 deep. */
515
+ function plainJSON(value: unknown, depth = 0): boolean {
516
+ if (depth > 32) return false;
517
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
518
+ if (typeof value === "number") return Number.isFinite(value);
519
+ if (Array.isArray(value)) return value.every((v) => plainJSON(v, depth + 1));
520
+ return (
521
+ isRecord(value) &&
522
+ Object.getPrototypeOf(value) === Object.prototype &&
523
+ Object.values(value).every((v) => plainJSON(v, depth + 1))
524
+ );
525
+ }
526
+
527
+ /** A foreign type's attributes: a plain JSON object, size-limited. */
528
+ const foreignAttrs: Check = (v) => {
529
+ if (!isRecord(v) || !plainJSON(v)) return "must be a plain JSON object";
530
+ return JSON.stringify(v).length <= MAX_FOREIGN_ATTRS
531
+ ? undefined
532
+ : `must be at most ${MAX_FOREIGN_ATTRS} characters as JSON`;
533
+ };
534
+
535
+ /**
536
+ * What a foreign node or mark holds: the custom type and attributes it was read as. `text` is
537
+ * a foreign node's text as a `.docx` control showed it: in memory only, never saved.
538
+ */
539
+ const foreign = {
540
+ type: {
541
+ validate: (v: unknown) =>
542
+ typeof v === "string" && CUSTOM_TYPE.test(v) ? undefined : "must be a namespaced type",
543
+ },
544
+ attrs: nullableAttr(foreignAttrs),
545
+ };
546
+ const foreignNode = {
547
+ attrs: { ...foreign, text: nullableAttr(str(65_535)) },
548
+ text: (attrs: Record<string, unknown>) =>
549
+ typeof attrs.text === "string" ? attrs.text : `[${String(attrs.type)}]`,
550
+ };
551
+
441
552
  export const schema = new Schema({
442
553
  nodes: {
443
554
  doc: { content: "block+" },
@@ -446,6 +557,7 @@ export const schema = new Schema({
446
557
  content: "inline*",
447
558
  attrs: {
448
559
  ...paragraphProperties,
560
+ ...controlsAttr,
449
561
  /** Ends a section: its page setup. The last section's is the envelope's `section`. */
450
562
  section: nullableAttr(checkSection),
451
563
  /** The paragraph mark inserted and/or deleted as tracked changes. */
@@ -472,6 +584,7 @@ export const schema = new Schema({
472
584
  content: "tableRow+",
473
585
  attrs: {
474
586
  ...tableProperties,
587
+ ...controlsAttr,
475
588
  /** The grid's column widths in twips (`w:tblGrid`). */
476
589
  grid: { default: [], validate: listOf(positiveTwips, MAX_COLUMNS) },
477
590
  /** The `w:tblGrid` the grid was read from, verbatim. */
@@ -482,6 +595,7 @@ export const schema = new Schema({
482
595
  content: "tableCell+",
483
596
  attrs: {
484
597
  ...rowProperties,
598
+ ...controlsAttr,
485
599
  /** The row inserted or deleted as a tracked change (`w:trPr/w:ins`, `w:del`). */
486
600
  revision: nullableAttr(shape({ insertion: revision, deletion: revision })),
487
601
  /** The row's table property exceptions (`w:tblPrEx`). */
@@ -493,12 +607,12 @@ export const schema = new Schema({
493
607
  tableCell: {
494
608
  // As Word requires, a cell ends with a paragraph.
495
609
  content: "block* paragraph",
496
- attrs: cellProperties,
610
+ attrs: { ...cellProperties, ...controlsAttr },
497
611
  },
498
612
  /** Block content Foli does not model yet (a table inside a content control…), kept verbatim. */
499
613
  opaqueBlock: {
500
614
  group: "block",
501
- attrs: { xml: { validate: xml }, label: nullableAttr(text()) },
615
+ attrs: { xml: { validate: xml }, label: nullableAttr(text()), ...controlsAttr },
502
616
  },
503
617
  text: { group: "inline" },
504
618
  tab: { group: "inline", inline: true },
@@ -541,6 +655,51 @@ export const schema = new Schema({
541
655
  inline: true,
542
656
  attrs: { id: { validate: ID }, ...markerAttributes },
543
657
  },
658
+ /**
659
+ * A field, as Word has it (schema v5, ADR-0007): start, code, optional separator, result,
660
+ * end. The code range runs from the start to the separator (or the end) and may hold other
661
+ * fields; the result is ordinary content.
662
+ */
663
+ fieldStart: {
664
+ ...fieldPart,
665
+ attrs: {
666
+ dirty: nullableAttr(bool),
667
+ locked: nullableAttr(bool),
668
+ /** Read from `w:fldSimple`, and written back as one. */
669
+ simple: nullableAttr(bool),
670
+ ext: nullableAttr(xml),
671
+ },
672
+ },
673
+ /** One `w:instrText`: part of a field's code. */
674
+ fieldCode: { ...fieldPart, attrs: { text: { validate: str(65_535) }, ...markerAttributes } },
675
+ fieldSeparator: { ...fieldPart, attrs: { ext: nullableAttr(xml) } },
676
+ fieldEnd: { ...fieldPart, attrs: { ext: nullableAttr(xml) } },
677
+ /** An inline content control's ends; its properties are the envelope's `controls[id]`. */
678
+ controlStart: {
679
+ group: "inline",
680
+ inline: true,
681
+ selectable: false,
682
+ attrs: { id: { validate: text() } },
683
+ },
684
+ controlEnd: {
685
+ group: "inline",
686
+ inline: true,
687
+ selectable: false,
688
+ attrs: { id: { validate: text() } },
689
+ },
690
+ /** A footnote's or endnote's reference: its text is the envelope's `stories[story]`. */
691
+ noteReference: {
692
+ group: "inline",
693
+ inline: true,
694
+ attrs: {
695
+ story: { validate: text() },
696
+ /** `w:customMarkFollows`: the mark is the text after it, not a number. */
697
+ customMark: nullableAttr(bool),
698
+ ...markerAttributes,
699
+ },
700
+ },
701
+ /** Where a note shows its own number (`w:footnoteRef`, `w:endnoteRef`). */
702
+ noteMark: { group: "inline", inline: true, selectable: false },
544
703
  /**
545
704
  * A picture (`w:drawing` holding `pic:pic`, schema v4), inline or floating. Its bytes are
546
705
  * the envelope's `resources[resource]`.
@@ -577,6 +736,12 @@ export const schema = new Schema({
577
736
  run: { default: false, validate: bool },
578
737
  },
579
738
  },
739
+ /**
740
+ * A custom node whose extension is not loaded (ADR-0008): kept whole, written back as the
741
+ * type and attributes it was read as. Only in memory: never saved under this name.
742
+ */
743
+ foreignInline: { group: "inline", inline: true, ...foreignNode },
744
+ foreignBlock: { group: "block", ...foreignNode },
580
745
  },
581
746
  marks: {
582
747
  // Order: the canonical order of mark sets, and of nesting when rendered (outermost first).
@@ -658,5 +823,7 @@ export const schema = new Schema({
658
823
  },
659
824
  /** The `w:rPr` these marks were read from, verbatim (see the module comment). */
660
825
  runExt: { attrs: { xml: markAttr(xml) } },
826
+ /** A custom mark whose extension is not loaded, as `foreignInline` is a node. Several combine. */
827
+ foreign: { attrs: foreign, excludes: "", inclusive: false },
661
828
  },
662
829
  });