@folijs/core 0.2.0 → 0.4.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 (136) hide show
  1. package/CHANGELOG.md +45 -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 +162 -97
  25. package/dist/state/commands.js.map +1 -1
  26. package/dist/state/comments.d.ts +47 -0
  27. package/dist/state/comments.d.ts.map +1 -0
  28. package/dist/state/comments.js +304 -0
  29. package/dist/state/comments.js.map +1 -0
  30. package/dist/state/editor.d.ts +67 -16
  31. package/dist/state/editor.d.ts.map +1 -1
  32. package/dist/state/editor.js +74 -18
  33. package/dist/state/editor.js.map +1 -1
  34. package/dist/state/format.d.ts +8 -22
  35. package/dist/state/format.d.ts.map +1 -1
  36. package/dist/state/format.js +16 -140
  37. package/dist/state/format.js.map +1 -1
  38. package/dist/state/history.d.ts +1 -1
  39. package/dist/state/history.d.ts.map +1 -1
  40. package/dist/state/history.js +3 -2
  41. package/dist/state/history.js.map +1 -1
  42. package/dist/state/index.d.ts +11 -4
  43. package/dist/state/index.d.ts.map +1 -1
  44. package/dist/state/index.js +11 -4
  45. package/dist/state/index.js.map +1 -1
  46. package/dist/state/links.d.ts.map +1 -1
  47. package/dist/state/links.js +10 -2
  48. package/dist/state/links.js.map +1 -1
  49. package/dist/state/lists.d.ts +19 -32
  50. package/dist/state/lists.d.ts.map +1 -1
  51. package/dist/state/lists.js +23 -372
  52. package/dist/state/lists.js.map +1 -1
  53. package/dist/state/mark.d.ts +28 -0
  54. package/dist/state/mark.d.ts.map +1 -0
  55. package/dist/state/mark.js +57 -0
  56. package/dist/state/mark.js.map +1 -0
  57. package/dist/state/review.d.ts +43 -0
  58. package/dist/state/review.d.ts.map +1 -0
  59. package/dist/state/review.js +282 -0
  60. package/dist/state/review.js.map +1 -0
  61. package/dist/state/state.d.ts +2 -0
  62. package/dist/state/state.d.ts.map +1 -1
  63. package/dist/state/state.js +18 -0
  64. package/dist/state/state.js.map +1 -1
  65. package/dist/state/track.d.ts +47 -0
  66. package/dist/state/track.d.ts.map +1 -0
  67. package/dist/state/track.js +534 -0
  68. package/dist/state/track.js.map +1 -0
  69. package/dist/state/word.d.ts +100 -0
  70. package/dist/state/word.d.ts.map +1 -0
  71. package/dist/state/word.js +253 -0
  72. package/dist/state/word.js.map +1 -0
  73. package/dist/state/wordclip.d.ts +43 -0
  74. package/dist/state/wordclip.d.ts.map +1 -0
  75. package/dist/state/wordclip.js +412 -0
  76. package/dist/state/wordclip.js.map +1 -0
  77. package/dist/state/wordformat.d.ts +136 -0
  78. package/dist/state/wordformat.d.ts.map +1 -0
  79. package/dist/state/wordformat.js +846 -0
  80. package/dist/state/wordformat.js.map +1 -0
  81. package/dist/v3/check.d.ts +33 -0
  82. package/dist/v3/check.d.ts.map +1 -0
  83. package/dist/v3/check.js +90 -0
  84. package/dist/v3/check.js.map +1 -0
  85. package/dist/v3/document.d.ts +217 -0
  86. package/dist/v3/document.d.ts.map +1 -0
  87. package/dist/v3/document.js +225 -0
  88. package/dist/v3/document.js.map +1 -0
  89. package/dist/v3/index.d.ts +6 -0
  90. package/dist/v3/index.d.ts.map +1 -0
  91. package/dist/v3/index.js +6 -0
  92. package/dist/v3/index.js.map +1 -0
  93. package/dist/v3/migrate.d.ts +19 -0
  94. package/dist/v3/migrate.d.ts.map +1 -0
  95. package/dist/v3/migrate.js +227 -0
  96. package/dist/v3/migrate.js.map +1 -0
  97. package/dist/v3/resolve.d.ts +129 -0
  98. package/dist/v3/resolve.d.ts.map +1 -0
  99. package/dist/v3/resolve.js +534 -0
  100. package/dist/v3/resolve.js.map +1 -0
  101. package/dist/v3/schema.d.ts +29 -0
  102. package/dist/v3/schema.d.ts.map +1 -0
  103. package/dist/v3/schema.js +431 -0
  104. package/dist/v3/schema.js.map +1 -0
  105. package/dist/v3/units.d.ts +16 -0
  106. package/dist/v3/units.d.ts.map +1 -0
  107. package/dist/v3/units.js +28 -0
  108. package/dist/v3/units.js.map +1 -0
  109. package/package.json +1 -1
  110. package/src/document.ts +26 -26
  111. package/src/index.ts +3 -6
  112. package/src/model/fragment.ts +11 -3
  113. package/src/model/node.ts +6 -1
  114. package/src/schema.ts +13 -1
  115. package/src/state/commands.ts +173 -91
  116. package/src/state/comments.ts +342 -0
  117. package/src/state/editor.ts +176 -36
  118. package/src/state/format.ts +24 -122
  119. package/src/state/history.ts +3 -2
  120. package/src/state/index.ts +73 -3
  121. package/src/state/links.ts +10 -2
  122. package/src/state/lists.ts +31 -408
  123. package/src/state/mark.ts +64 -0
  124. package/src/state/review.ts +330 -0
  125. package/src/state/state.ts +18 -0
  126. package/src/state/track.ts +602 -0
  127. package/src/state/word.ts +330 -0
  128. package/src/state/wordclip.ts +445 -0
  129. package/src/state/wordformat.ts +982 -0
  130. package/src/v3/check.ts +119 -0
  131. package/src/v3/document.ts +456 -0
  132. package/src/v3/index.ts +33 -0
  133. package/src/v3/migrate.ts +267 -0
  134. package/src/v3/resolve.ts +646 -0
  135. package/src/v3/schema.ts +482 -0
  136. package/src/v3/units.ts +34 -0
@@ -0,0 +1,982 @@
1
+ /**
2
+ * Word formatting on a schema v3 document (8.7b): paragraph styles, font family and size, text
3
+ * color and highlight, alignment, line spacing, indentation, and lists as Word's numbering. The
4
+ * generic commands (`setAlign`, `setTextColor`, `toggleList`…) call these on a v3 document;
5
+ * the others are v3 only (they do not apply to schema v2).
6
+ *
7
+ * Run properties, alignment and line spacing are written as direct formatting only where the
8
+ * paragraph's or run's styles do not already give the value (picking a heading's own size
9
+ * leaves no direct size), as Word does; space before and after and indents are always written.
10
+ * Built-in styles a document has not used yet (headings, List Paragraph, Hyperlink) are added
11
+ * with Word's definitions when first applied.
12
+ */
13
+ import type { Attrs, Mark, MarkType, Node } from "../model/index.js";
14
+ import type { Alignment } from "../schema.js";
15
+ import { NodeMarkupBatchStep, NodeMarkupStep } from "../transform/index.js";
16
+ import type {
17
+ AbstractNumberingJSON,
18
+ NumberingInstanceJSON,
19
+ NumberingLevelJSON,
20
+ StyleJSON,
21
+ } from "../v3/document.js";
22
+ import type { RunFormat } from "../v3/resolve.js";
23
+ import { attempt } from "./attempt.js";
24
+ import { marksAt, TextSelection } from "./selection.js";
25
+ import type { Command, EditorState, Transaction } from "./state.js";
26
+ import {
27
+ isMarker,
28
+ type WordContext,
29
+ type WordEnvelope,
30
+ withEnvelope,
31
+ wordContext,
32
+ } from "./word.js";
33
+
34
+ const json = (value: unknown) => JSON.stringify(value ?? null);
35
+
36
+ /** The paragraphs the selection touches, with their positions. */
37
+ function paragraphsIn(state: EditorState): { node: Node; pos: number }[] {
38
+ const found: { node: Node; pos: number }[] = [];
39
+ const { from, to } = state.selection;
40
+ state.doc.nodesBetween(from, to, (node, pos) => {
41
+ if (node.type.name !== "paragraph") return true;
42
+ found.push({ node, pos });
43
+ return false;
44
+ });
45
+ return found;
46
+ }
47
+
48
+ /**
49
+ * Changes the attributes of every selected paragraph (`change` gives the new ones, or null to
50
+ * leave it) in one step. Does not apply when nothing changes.
51
+ */
52
+ function updateParagraphs(
53
+ state: EditorState,
54
+ dispatch: ((tr: Transaction) => void) | undefined,
55
+ change: (node: Node) => Attrs | null,
56
+ envelope?: WordEnvelope,
57
+ ): boolean {
58
+ const steps = paragraphsIn(state).flatMap(({ node, pos }) => {
59
+ const next = change(node);
60
+ return next && json(next) !== json(node.attrs)
61
+ ? [new NodeMarkupStep(pos, node.type, next)]
62
+ : [];
63
+ });
64
+ if (!steps.length) return false;
65
+ return attempt(state, dispatch, (tr) => {
66
+ tr.step(new NodeMarkupBatchStep(steps));
67
+ if (envelope) withEnvelope(tr, envelope);
68
+ });
69
+ }
70
+
71
+ /** The value all `values` share, or null (none, or mixed). */
72
+ function common<T>(values: readonly T[]): T | null {
73
+ const [first] = values;
74
+ return first !== undefined && values.every((v) => json(v) === json(first)) ? first : null;
75
+ }
76
+
77
+ // ---------- paragraph styles ----------
78
+
79
+ export type HasEnvelope = Pick<WordContext, "envelope">;
80
+
81
+ /** The id of the document's style of `type` named `name` (Word's names: "heading 1"), if any. */
82
+ export function styleNamed(
83
+ context: HasEnvelope,
84
+ name: string,
85
+ type: StyleJSON["type"] = "paragraph",
86
+ ): string | null {
87
+ const lower = name.toLowerCase();
88
+ return (
89
+ context.envelope.styles.find((s) => s.type === type && s.name?.toLowerCase() === lower)?.id ??
90
+ null
91
+ );
92
+ }
93
+
94
+ /** The id of the default style of `type` (Normal, Default Paragraph Font), if the document has one. */
95
+ export function defaultParagraphStyleOf(
96
+ context: HasEnvelope,
97
+ type: StyleJSON["type"] = "paragraph",
98
+ ): string | null {
99
+ let id: string | null = null;
100
+ for (const s of context.envelope.styles) if (s.type === type && s.isDefault) id = s.id;
101
+ return id;
102
+ }
103
+
104
+ /** The built-in style a style id names (`Heading2`: "heading 2"), for a document without it. */
105
+ const builtinName = (id: string) =>
106
+ /^Heading[1-9]$/.test(id)
107
+ ? `heading ${id.slice(7)}`
108
+ : id === "ListParagraph"
109
+ ? "List Paragraph"
110
+ : null;
111
+
112
+ /**
113
+ * Word's definition of built-in style `name` ("heading 1"–"heading 9", "List Paragraph",
114
+ * "Hyperlink"), as Word adds it to a document the first time it is used (the Word 2013–2019
115
+ * template's values; not checked against newer Word).
116
+ */
117
+ export function builtinStyle(context: HasEnvelope, name: string): StyleJSON | null {
118
+ const normal = defaultParagraphStyleOf(context);
119
+ const based = normal ? { basedOn: normal } : {};
120
+ const heading = /^heading ([1-9])$/.exec(name)?.[1];
121
+ if (heading) {
122
+ const n = Number(heading);
123
+ const color =
124
+ n >= 8
125
+ ? { value: "272727", themeColor: "text1", themeTint: "D8" }
126
+ : {
127
+ ...([3, 6, 7].includes(n)
128
+ ? { value: "1F3763", themeShade: "7F" }
129
+ : { value: "2F5496", themeShade: "BF" }),
130
+ themeColor: "accent1",
131
+ };
132
+ const size = [32, 26, 24, 0, 0, 0, 0, 21, 21][n - 1];
133
+ return {
134
+ id: `Heading${n}`,
135
+ type: "paragraph",
136
+ name,
137
+ ...based,
138
+ ...(normal ? { next: normal } : {}),
139
+ paragraph: {
140
+ keepNext: true,
141
+ keepLines: true,
142
+ spacing: { before: n === 1 ? 240 : 40, after: 0 },
143
+ outlineLevel: n - 1,
144
+ },
145
+ run: [
146
+ {
147
+ type: "font",
148
+ attrs: {
149
+ asciiTheme: "majorHAnsi",
150
+ eastAsiaTheme: "majorEastAsia",
151
+ hAnsiTheme: "majorHAnsi",
152
+ csTheme: "majorBidi",
153
+ },
154
+ },
155
+ ...([4, 7, 9].includes(n) ? [{ type: "italic", attrs: { complexScript: true } }] : []),
156
+ { type: "color", attrs: color },
157
+ ...(size ? [{ type: "fontSize", attrs: { value: size, complexScript: size } }] : []),
158
+ ],
159
+ };
160
+ }
161
+ if (name === "List Paragraph")
162
+ return {
163
+ id: "ListParagraph",
164
+ type: "paragraph",
165
+ name,
166
+ ...based,
167
+ paragraph: { indent: { left: 720 }, contextualSpacing: true },
168
+ };
169
+ if (name === "Hyperlink") {
170
+ const font = defaultParagraphStyleOf(context, "character");
171
+ return {
172
+ id: "Hyperlink",
173
+ type: "character",
174
+ name,
175
+ ...(font ? { basedOn: font } : {}),
176
+ run: [
177
+ { type: "color", attrs: { value: "0563C1", themeColor: "hyperlink" } },
178
+ { type: "underline", attrs: { style: "single" } },
179
+ ],
180
+ };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ /**
186
+ * The id of the document's style named `name`, adding Word's built-in definition when the
187
+ * document does not have it yet (with the envelope that has it; unchanged if it was there).
188
+ */
189
+ function ensureStyle(
190
+ context: HasEnvelope,
191
+ name: string,
192
+ type: StyleJSON["type"] = "paragraph",
193
+ ): { id: string; envelope: WordEnvelope } | null {
194
+ const { envelope } = context;
195
+ const found = styleNamed(context, name, type);
196
+ if (found) return { id: found, envelope };
197
+ const style = builtinStyle(context, name);
198
+ if (!style) return null;
199
+ const ids = new Set(envelope.styles.map((s) => s.id));
200
+ let id = style.id;
201
+ for (let i = 1; ids.has(id); i++) id = `${style.id}${i}`;
202
+ return { id, envelope: { ...envelope, styles: [...envelope.styles, { ...style, id }] } };
203
+ }
204
+
205
+ /**
206
+ * The paragraph styles a style picker offers: the document's, its default first, then Word's
207
+ * Heading 1 to 3 where the document does not have them yet (added when picked).
208
+ */
209
+ export function paragraphStyles(state: EditorState): { id: string; name: string }[] {
210
+ const context = wordContext(state);
211
+ if (!context) return [];
212
+ const seen = new Set<string>();
213
+ const styles = context.envelope.styles.filter(
214
+ (s) => s.type === "paragraph" && !seen.has(s.id) && seen.add(s.id),
215
+ );
216
+ const first = defaultParagraphStyleOf(context);
217
+ const builtins = ["Heading1", "Heading2", "Heading3"].filter(
218
+ (id) => !seen.has(id) && !styleNamed(context, builtinName(id) as string),
219
+ );
220
+ return [
221
+ ...styles
222
+ .map((s) => ({ id: s.id, name: s.name ?? s.id }))
223
+ .sort((a, b) => Number(b.id === first) - Number(a.id === first)),
224
+ ...builtins.map((id) => ({ id, name: builtinName(id) as string })),
225
+ ];
226
+ }
227
+
228
+ /** The style all selected paragraphs are in (the default one when they name none), or null. */
229
+ export function paragraphStyleAt(state: EditorState): string | null {
230
+ const context = wordContext(state);
231
+ if (!context) return null;
232
+ return common(
233
+ paragraphsIn(state).map(
234
+ ({ node }) => context.resolver.paragraph(node.attrs).paragraph.style ?? null,
235
+ ),
236
+ );
237
+ }
238
+
239
+ /**
240
+ * Puts the selected paragraphs in paragraph style `id` (the default style: no style named).
241
+ * Their direct formatting stays. A built-in style the document does not have yet (`Heading1`–
242
+ * `Heading9`, `ListParagraph`) is added with Word's definition; any other must exist.
243
+ */
244
+ export function setParagraphStyle(id: string): Command {
245
+ return (state, dispatch) => {
246
+ const context = wordContext(state);
247
+ if (!context) return false;
248
+ if (context.envelope.styles.some((s) => s.id === id && s.type === "paragraph"))
249
+ return applyStyle(state, dispatch, context, { id, envelope: context.envelope });
250
+ const name = builtinName(id);
251
+ return !!name && setStyleNamed(name)(state, dispatch);
252
+ };
253
+ }
254
+
255
+ /**
256
+ * Puts the selected paragraphs in the paragraph style named `name` ("heading 2"), adding Word's
257
+ * definition of a built-in one the document does not have yet.
258
+ */
259
+ export function setStyleNamed(name: string): Command {
260
+ return (state, dispatch) => {
261
+ const context = wordContext(state);
262
+ const target = context && ensureStyle(context, name);
263
+ return !!target && applyStyle(state, dispatch, context, target);
264
+ };
265
+ }
266
+
267
+ function applyStyle(
268
+ state: EditorState,
269
+ dispatch: ((tr: Transaction) => void) | undefined,
270
+ context: WordContext,
271
+ target: { id: string; envelope: WordEnvelope },
272
+ ): boolean {
273
+ const style = target.id === defaultParagraphStyleOf(context) ? null : target.id;
274
+ return updateParagraphs(
275
+ state,
276
+ dispatch,
277
+ (node) => ({ ...node.attrs, style }),
278
+ target.envelope === context.envelope ? undefined : target.envelope,
279
+ );
280
+ }
281
+
282
+ // ---------- run properties ----------
283
+
284
+ /** The inline nodes of the selection a run property applies to (markers have no text to format). */
285
+ function runsIn(state: EditorState, type: MarkType) {
286
+ const context = wordContext(state);
287
+ const found: { node: Node; pos: number; parent: Node }[] = [];
288
+ const { from, to } = state.selection;
289
+ state.doc.nodesBetween(from, to, (node, pos, parent) => {
290
+ if (!node.isInline || !parent?.type.allowsMarkType(type)) return undefined;
291
+ if (!isMarker(context, node)) found.push({ node, pos, parent });
292
+ return false;
293
+ });
294
+ return found;
295
+ }
296
+
297
+ /** What text with `marks` in `paragraph` shows, without its own mark of `type` (`own`: with). */
298
+ function runFormat(
299
+ context: WordContext,
300
+ paragraph: Node,
301
+ marks: readonly Mark[],
302
+ type?: MarkType,
303
+ ): RunFormat {
304
+ const { run } = context.resolver.paragraph(paragraph.attrs);
305
+ return context.resolver.run(
306
+ run,
307
+ marks.filter((m) => m.type !== type).map((m) => m.toJSON()),
308
+ );
309
+ }
310
+
311
+ /**
312
+ * Sets a run property on the selected text (at a caret, for the text typed next): `build` gives
313
+ * the mark of `name` for text that has `existing` and shows `inherited` without it, or null
314
+ * for none.
315
+ */
316
+ function setRunMark(
317
+ name: string,
318
+ build: (existing: Mark | undefined, inherited: RunFormat, type: MarkType) => Mark | null,
319
+ ): Command {
320
+ return (state, dispatch) => {
321
+ const context = wordContext(state);
322
+ const type = state.schema.marks[name];
323
+ if (!context || !type) return false;
324
+ const { selection } = state;
325
+ if (selection.empty && selection instanceof TextSelection) {
326
+ const { $from } = selection;
327
+ if (!$from.parent.type.allowsMarkType(type)) return false;
328
+ const marks = state.storedMarks ?? marksAt($from);
329
+ const existing = type.isInSet(marks);
330
+ const mark = build(existing, runFormat(context, $from.parent, marks, type), type);
331
+ const rest = type.removeFromSet(marks);
332
+ dispatch?.(state.tr.setStoredMarks(mark ? mark.addToSet(rest) : rest));
333
+ return true;
334
+ }
335
+ const runs = runsIn(state, type);
336
+ if (!runs.length) return false;
337
+ return attempt(state, dispatch, (tr) => {
338
+ for (const { node, pos, parent } of runs) {
339
+ const from = Math.max(selection.from, pos);
340
+ const to = Math.min(selection.to, pos + node.nodeSize);
341
+ const existing = type.isInSet(node.marks);
342
+ const mark = build(existing, runFormat(context, parent, node.marks, type), type);
343
+ if (mark ? existing?.eq(mark) : !existing) continue;
344
+ tr.removeMark(from, to, type);
345
+ if (mark) tr.addMark(from, to, mark);
346
+ }
347
+ });
348
+ };
349
+ }
350
+
351
+ /** What the selected text (or the text typed at a caret) shows of `read`, if all the same. */
352
+ function runValueAt<T>(state: EditorState, read: (run: RunFormat) => T): T | null {
353
+ const context = wordContext(state);
354
+ if (!context) return null;
355
+ const { selection } = state;
356
+ if (selection.empty) {
357
+ const marks = state.storedMarks ?? marksAt(selection.$from);
358
+ return read(runFormat(context, selection.$from.parent, marks));
359
+ }
360
+ return common(
361
+ runsIn(state, state.schema.marks.font as MarkType)
362
+ .filter((r) => r.node.isText)
363
+ .map((r) => read(runFormat(context, r.parent, r.node.marks))),
364
+ );
365
+ }
366
+
367
+ /** The font name Latin text shows. */
368
+ const latinFont = (run: RunFormat) => run.font.ascii ?? run.font.hAnsi;
369
+
370
+ /**
371
+ * The font family of the selected text (or of the text typed next); null puts back the styles'
372
+ * font. Sets the font Latin text uses (`w:ascii`, `w:hAnsi`), as Word's font box does; East
373
+ * Asian and complex-script fonts stay.
374
+ */
375
+ export function setFontFamily(name: string | null): Command {
376
+ const font = name?.trim() || null;
377
+ return setRunMark("font", (existing, inherited, type) => {
378
+ const attrs: Record<string, unknown> = {
379
+ ...(existing?.attrs ?? {}),
380
+ asciiTheme: null,
381
+ hAnsiTheme: null,
382
+ };
383
+ const same = font !== null && latinFont(inherited) === font;
384
+ attrs.ascii = attrs.hAnsi = font === null || same ? null : font;
385
+ return Object.values(attrs).some((v) => v !== null) ? type.create(attrs) : null;
386
+ });
387
+ }
388
+
389
+ /** The font family the selected text shows, if all the same. */
390
+ export function fontFamilyAt(state: EditorState): string | null {
391
+ return runValueAt(state, latinFont);
392
+ }
393
+
394
+ /**
395
+ * The font size in points (half points stored, `w:sz` and `w:szCs`) of the selected text, or of
396
+ * the text typed next; null puts back the styles' size. Sizes from 1 to 1638 pt, in half points.
397
+ */
398
+ export function setFontSize(points: number | null): Command {
399
+ const half = points === null ? null : Math.round(points * 2);
400
+ return (state, dispatch) => {
401
+ if (half !== null && !(half >= 2 && half <= 3276)) return false;
402
+ return setRunMark("fontSize", (_existing, inherited, type) =>
403
+ half === null || (inherited.size === half && inherited.sizeCs === half)
404
+ ? null
405
+ : type.create({
406
+ value: inherited.size === half ? null : half,
407
+ complexScript: inherited.sizeCs === half ? null : half,
408
+ }),
409
+ )(state, dispatch);
410
+ };
411
+ }
412
+
413
+ /** The font size in points the selected text shows, if all the same. */
414
+ export function fontSizeAt(state: EditorState): number | null {
415
+ return runValueAt(state, (run) => run.size / 2);
416
+ }
417
+
418
+ /** `#rrggbb` as Word's `RRGGBB`. */
419
+ const word = (hex: string) => hex.slice(1).toUpperCase();
420
+
421
+ /** Word's highlight colors (`w:highlight`) as `#rrggbb`. */
422
+ export const HIGHLIGHT_HEX: Readonly<Record<string, string>> = {
423
+ black: "#000000",
424
+ blue: "#0000ff",
425
+ cyan: "#00ffff",
426
+ green: "#00ff00",
427
+ magenta: "#ff00ff",
428
+ red: "#ff0000",
429
+ yellow: "#ffff00",
430
+ white: "#ffffff",
431
+ darkBlue: "#000080",
432
+ darkCyan: "#008080",
433
+ darkGreen: "#008000",
434
+ darkMagenta: "#800080",
435
+ darkRed: "#800000",
436
+ darkYellow: "#808000",
437
+ darkGray: "#808080",
438
+ lightGray: "#c0c0c0",
439
+ };
440
+
441
+ /**
442
+ * Text color on a v3 document (`#rrggbb`); null is Word's "Automatic": no direct color, or an
443
+ * explicit `auto` where a style colors the text.
444
+ */
445
+ export function setWordTextColor(color: string | null): Command {
446
+ return setRunMark("color", (_existing, inherited, type) => {
447
+ if (color === null) return inherited.color === null ? null : type.create({ value: "auto" });
448
+ return inherited.color === word(color) ? null : type.create({ value: word(color) });
449
+ });
450
+ }
451
+
452
+ /**
453
+ * Highlight on a v3 document (`#rrggbb`): one of Word's highlight colors as a highlight, any
454
+ * other as shading; null removes the highlight (an explicit `none` where a style highlights)
455
+ * and a plain shading fill, the kind a color outside Word's highlights gives. Patterned shading
456
+ * stays, and picking a highlight keeps any shading (Word's highlight and shading are apart).
457
+ */
458
+ export function setWordHighlight(color: string | null): Command {
459
+ return (state, dispatch) => {
460
+ const named = color
461
+ ? Object.keys(HIGHLIGHT_HEX).find((k) => HIGHLIGHT_HEX[k] === color.toLowerCase())
462
+ : undefined;
463
+ if (color === null || named) {
464
+ const highlight = setRunMark("highlight", (_existing, inherited, type) => {
465
+ if (named) return inherited.highlight === named ? null : type.create({ value: named });
466
+ return inherited.highlight === null ? null : type.create({ value: "none" });
467
+ });
468
+ if (named) return highlight(state, dispatch);
469
+ const fill = setRunMark("shading", (existing) =>
470
+ existing?.attrs.pattern === "clear" && existing.attrs.color === "auto"
471
+ ? null
472
+ : (existing ?? null),
473
+ );
474
+ return chain(state, dispatch, [highlight, fill]);
475
+ }
476
+ return chain(state, dispatch, [
477
+ removeMark("highlight"),
478
+ setRunMark("shading", (_existing, _inherited, type) =>
479
+ type.create({ pattern: "clear", color: "auto", fill: word(color) }),
480
+ ),
481
+ ]);
482
+ };
483
+ }
484
+
485
+ /** Removes the direct marks of `name` from the selection (at a caret, from the stored marks). */
486
+ function removeMark(name: string): Command {
487
+ return setRunMark(name, () => null);
488
+ }
489
+
490
+ /** Runs `commands` one after another as one transaction; applies when any of them does. */
491
+ function chain(
492
+ state: EditorState,
493
+ dispatch: ((tr: Transaction) => void) | undefined,
494
+ commands: readonly Command[],
495
+ ): boolean {
496
+ let current = state;
497
+ let tr: Transaction | null = null;
498
+ for (const command of commands) {
499
+ command(current, (next) => {
500
+ // Each command's steps go on the first transaction; stored marks and selection too.
501
+ if (!tr) tr = next;
502
+ else {
503
+ for (const step of next.steps) tr.step(step);
504
+ if (next.storedMarks !== current.storedMarks) tr.setStoredMarks(next.storedMarks);
505
+ }
506
+ current = current.apply(next);
507
+ });
508
+ }
509
+ if (!tr) return false;
510
+ dispatch?.(tr);
511
+ return true;
512
+ }
513
+
514
+ /** The text color the selection shows (`#rrggbb`; null: automatic, or mixed). */
515
+ export function wordTextColorAt(state: EditorState): string | null {
516
+ return runValueAt(state, (run) => (run.color ? `#${run.color.toLowerCase()}` : null));
517
+ }
518
+
519
+ /** The highlight (or shading) the selection shows (`#rrggbb`), or null. */
520
+ export function wordHighlightAt(state: EditorState): string | null {
521
+ return runValueAt(state, (run) =>
522
+ run.highlight
523
+ ? (HIGHLIGHT_HEX[run.highlight] ?? null)
524
+ : run.shading
525
+ ? `#${run.shading.toLowerCase()}`
526
+ : null,
527
+ );
528
+ }
529
+
530
+ // ---------- paragraph properties ----------
531
+
532
+ const TO_WORD: Record<Alignment, string> = {
533
+ start: "left",
534
+ center: "center",
535
+ end: "right",
536
+ justify: "both",
537
+ };
538
+
539
+ /** A Word justification as the editor's alignment (null for one it has no button for). */
540
+ function alignmentOf(justification: string | null): Alignment | null {
541
+ if (justification === null || justification === "left" || justification === "start")
542
+ return "start";
543
+ if (justification === "center") return "center";
544
+ if (justification === "right" || justification === "end") return "end";
545
+ if (justification === "both" || justification === "distribute") return "justify";
546
+ return null;
547
+ }
548
+
549
+ /**
550
+ * The paragraph's attributes with property `key` set to `value` directly, or left to the style
551
+ * when the style already gives it (`same` compares what the paragraph would show).
552
+ */
553
+ function direct(
554
+ context: WordContext,
555
+ node: Node,
556
+ key: string,
557
+ value: unknown,
558
+ shows: (paragraph: ReturnType<WordContext["resolver"]["paragraph"]>["paragraph"]) => boolean,
559
+ ): Attrs {
560
+ const without = { ...node.attrs, [key]: null };
561
+ const inherited = context.resolver.paragraph(without).paragraph;
562
+ return shows(inherited) ? without : { ...node.attrs, [key]: value };
563
+ }
564
+
565
+ /** Aligns the selected paragraphs (`setAlign` on a v3 document). */
566
+ export function setWordAlign(align: Alignment): Command {
567
+ return (state, dispatch) => {
568
+ const context = wordContext(state);
569
+ if (!context) return false;
570
+ return updateParagraphs(state, dispatch, (node) =>
571
+ direct(
572
+ context,
573
+ node,
574
+ "justification",
575
+ TO_WORD[align],
576
+ (p) => alignmentOf(p.justification) === align,
577
+ ),
578
+ );
579
+ };
580
+ }
581
+
582
+ /** The alignment all selected paragraphs show (`alignAt` on a v3 document). */
583
+ export function wordAlignAt(state: EditorState): Alignment | null {
584
+ const context = wordContext(state);
585
+ if (!context) return null;
586
+ return common(
587
+ paragraphsIn(state).map(({ node }) =>
588
+ alignmentOf(context.resolver.paragraph(node.attrs).paragraph.justification),
589
+ ),
590
+ );
591
+ }
592
+
593
+ /**
594
+ * Line spacing of the selected paragraphs as a multiple of single spacing (1, 1.15, 1.5, 2…);
595
+ * null puts back the styles' spacing. Space before and after stays.
596
+ */
597
+ export function setLineSpacing(multiple: number | null): Command {
598
+ return (state, dispatch) => {
599
+ const context = wordContext(state);
600
+ if (!context || (multiple !== null && !(multiple > 0 && multiple <= 132))) return false;
601
+ const line = multiple === null ? null : Math.round(multiple * 240);
602
+ return updateParagraphs(state, dispatch, (node) => {
603
+ const own = { ...((node.attrs.spacing as Record<string, unknown> | null) ?? {}) };
604
+ delete own.line;
605
+ delete own.lineRule;
606
+ const base = { ...node.attrs, spacing: Object.keys(own).length ? own : null };
607
+ const inherited = context.resolver.paragraph(base).paragraph.spacing;
608
+ if (line === null || (inherited.line === line && inherited.lineRule === "auto")) return base;
609
+ return { ...node.attrs, spacing: { ...own, line, lineRule: "auto" } };
610
+ });
611
+ };
612
+ }
613
+
614
+ /** The line spacing all selected paragraphs show, as a multiple (null: exact or mixed). */
615
+ export function lineSpacingAt(state: EditorState): number | null {
616
+ const context = wordContext(state);
617
+ if (!context) return null;
618
+ return common(
619
+ paragraphsIn(state).map(({ node }) => {
620
+ const { line, lineRule } = context.resolver.paragraph(node.attrs).paragraph.spacing;
621
+ if (line === null) return 1;
622
+ return lineRule === "auto" || lineRule === null ? Math.round((line / 240) * 100) / 100 : null;
623
+ }),
624
+ );
625
+ }
626
+
627
+ /**
628
+ * Space before and after the selected paragraphs, in points (only the parts given; null puts
629
+ * back the style's). Always written directly; a side given turns its auto spacing off (Word
630
+ * ignores the value with it on).
631
+ */
632
+ export function setParagraphSpacing(space: {
633
+ before?: number | null;
634
+ after?: number | null;
635
+ }): Command {
636
+ return (state, dispatch) => {
637
+ const context = wordContext(state);
638
+ if (!context) return false;
639
+ const values = Object.values(space);
640
+ if (values.some((v) => v !== null && !(v >= 0 && v <= 1584))) return false;
641
+ return updateParagraphs(state, dispatch, (node) => {
642
+ const own: Record<string, unknown> = {
643
+ ...((node.attrs.spacing as Record<string, unknown> | null) ?? {}),
644
+ };
645
+ const set: string[] = [];
646
+ for (const key of ["before", "after"] as const) {
647
+ const value = space[key];
648
+ if (value === undefined) continue;
649
+ if (value === null) delete own[key];
650
+ else {
651
+ own[key] = Math.round(value * 20);
652
+ delete own[`${key}Autospacing`];
653
+ set.push(key);
654
+ }
655
+ }
656
+ const shown = context.resolver.paragraph({ ...node.attrs, spacing: own }).paragraph.spacing;
657
+ for (const key of set)
658
+ if (shown[`${key}Autospacing` as "beforeAutospacing"]) own[`${key}Autospacing`] = false;
659
+ return { ...node.attrs, spacing: Object.keys(own).length ? own : null };
660
+ });
661
+ };
662
+ }
663
+
664
+ /** Word's indent step (half an inch), in twips. */
665
+ const STEP = 720;
666
+
667
+ /**
668
+ * Increase or decrease indent (`dir` 1 or -1) of the selected paragraphs: a numbered paragraph
669
+ * moves a list level; any other moves its left indent to the next half-inch stop (not below 0).
670
+ */
671
+ export function changeIndent(dir: 1 | -1): Command {
672
+ return (state, dispatch) => {
673
+ const context = wordContext(state);
674
+ if (!context) return false;
675
+ return updateParagraphs(state, dispatch, (node) => {
676
+ const { paragraph } = context.resolver.paragraph(node.attrs);
677
+ if (paragraph.numbering) {
678
+ const { id } = paragraph.numbering;
679
+ const level = paragraph.numbering.level + dir;
680
+ if (level < 0) return withoutNumbering(context, node);
681
+ const definition = levelOf(context, id, level);
682
+ // A level its list does not define would lose the number.
683
+ if (!definition) return null;
684
+ // Numbered headings: the level's own style (Heading 2), which numbers it there.
685
+ const style = definition.style;
686
+ if (style && context.envelope.styles.some((s) => s.id === style))
687
+ return { ...node.attrs, style, numbering: node.attrs.numbering ? { id, level } : null };
688
+ return { ...node.attrs, numbering: { id, level } };
689
+ }
690
+ const left = paragraph.indent.left;
691
+ const next =
692
+ dir > 0 ? (Math.floor(left / STEP) + 1) * STEP : (Math.ceil(left / STEP) - 1) * STEP;
693
+ if (next < 0 || next > 31_680) return null;
694
+ const own = (node.attrs.indent as Record<string, unknown> | null) ?? {};
695
+ return { ...node.attrs, indent: { ...own, left: next } };
696
+ });
697
+ };
698
+ }
699
+
700
+ /** Whether the selection has a paragraph whose indent can decrease (numbered, or indented). */
701
+ export function canOutdent(state: EditorState): boolean {
702
+ const context = wordContext(state);
703
+ if (!context) return false;
704
+ return paragraphsIn(state).some(({ node }) => {
705
+ const { paragraph } = context.resolver.paragraph(node.attrs);
706
+ return paragraph.numbering !== null || paragraph.indent.left > 0;
707
+ });
708
+ }
709
+
710
+ // ---------- lists ----------
711
+
712
+ export type ListKind = "bulletList" | "orderedList";
713
+
714
+ /** The kind of list a paragraph is in (from its numbering level's format), or null. */
715
+ function kindOf(context: WordContext, attrs: Attrs): ListKind | null {
716
+ const format = context.resolver.numberFormat(attrs);
717
+ if (format === null || format === "none") return null;
718
+ return format === "bullet" ? "bulletList" : "orderedList";
719
+ }
720
+
721
+ /** The kind of list all selected paragraphs are in, or null (none, or mixed). */
722
+ export function wordListKindAt(state: EditorState): ListKind | null {
723
+ const context = wordContext(state);
724
+ if (!context) return null;
725
+ const kinds = paragraphsIn(state).map(({ node }) => kindOf(context, node.attrs));
726
+ return kinds.length ? common(kinds) : null;
727
+ }
728
+
729
+ /** The paragraph's attributes without numbering (an explicit "none" where its style numbers it). */
730
+ function withoutNumbering(context: WordContext, node: Node): Attrs {
731
+ const base = { ...node.attrs, numbering: null };
732
+ const styled = context.resolver.paragraph(base).paragraph.numbering !== null;
733
+ const listStyle = styleNamed(context, "List Paragraph");
734
+ const style = listStyle !== null && node.attrs.style === listStyle ? null : node.attrs.style;
735
+ return { ...base, style, numbering: styled ? { id: 0 } : null };
736
+ }
737
+
738
+ /** Word's levels for a new list: bullets (Symbol, Courier New, Wingdings) or numbers. */
739
+ export function levels(kind: ListKind): NumberingLevelJSON[] {
740
+ const bullets = [
741
+ ["", "Symbol"],
742
+ ["o", "Courier New"],
743
+ ["", "Wingdings"],
744
+ ] as const;
745
+ const numbers = ["decimal", "lowerLetter", "lowerRoman"] as const;
746
+ return Array.from({ length: 9 }, (_, level) => {
747
+ const paragraph = { indent: { left: STEP * (level + 1), hanging: 360 } };
748
+ if (kind === "bulletList") {
749
+ const [text, font] = bullets[level % 3] as readonly [string, string];
750
+ return {
751
+ level,
752
+ start: 1,
753
+ format: "bullet",
754
+ text,
755
+ justification: "left" as const,
756
+ paragraph,
757
+ run: [{ type: "font", attrs: { ascii: font, hAnsi: font, hint: "default" } }],
758
+ };
759
+ }
760
+ return {
761
+ level,
762
+ start: 1,
763
+ format: numbers[level % 3] as string,
764
+ text: `%${level + 1}.`,
765
+ justification: level % 3 === 2 ? ("right" as const) : ("left" as const),
766
+ paragraph:
767
+ level % 3 === 2 ? { indent: { left: STEP * (level + 1), hanging: 180 } } : paragraph,
768
+ };
769
+ });
770
+ }
771
+
772
+ /** Not a numbering style's definition, nor one that numbers headings (levels linked to styles). */
773
+ const plain = (a: AbstractNumberingJSON) =>
774
+ !a.styleLink && !a.numStyleLink && !a.levels.some((l) => l.style);
775
+
776
+ /** The definition numbering instance `id` uses. */
777
+ function abstractOf(context: WordContext, id: number): AbstractNumberingJSON | undefined {
778
+ const { abstracts, instances } = context.envelope.numbering;
779
+ return abstracts.find((a) => a.id === instances.find((n) => n.id === id)?.abstract);
780
+ }
781
+
782
+ /** Level `level` of numbering instance `id`'s definition, if it defines one. */
783
+ function levelOf(context: WordContext, id: number, level: number): NumberingLevelJSON | undefined {
784
+ return abstractOf(context, id)?.levels.find((l) => l.level === level);
785
+ }
786
+
787
+ /** Whether numbering instance `id` is a plain list's (not numbered headings'). */
788
+ function plainList(context: WordContext, id: number): boolean {
789
+ const abstract = abstractOf(context, id);
790
+ return !!abstract && plain(abstract);
791
+ }
792
+
793
+ /**
794
+ * The numbering instance a new list of `kind` uses: bullets share one (the document's own, or a
795
+ * new definition); a numbered list starts at 1 in a new instance (of a definition of Foli's,
796
+ * made once). Returns the instance id and the envelope with what it added (unchanged if none).
797
+ */
798
+ function newList(envelope: WordEnvelope, kind: ListKind): { id: number; envelope: WordEnvelope } {
799
+ const { abstracts, instances } = envelope.numbering;
800
+ const format = (a: AbstractNumberingJSON) => a.levels.find((l) => l.level === 0)?.format;
801
+ const found =
802
+ kind === "bulletList"
803
+ ? instances.find((n) => {
804
+ const a = abstracts.find((x) => x.id === n.abstract);
805
+ return a && plain(a) && format(a) === "bullet" && !n.overrides?.length;
806
+ })
807
+ : undefined;
808
+ if (found) return { id: found.id, envelope };
809
+ const nextId = (ids: number[]) => Math.max(0, ...ids) + 1;
810
+ let abstract = abstracts.find(
811
+ (a) => plain(a) && format(a) === (kind === "bulletList" ? "bullet" : "decimal"),
812
+ );
813
+ const added: AbstractNumberingJSON[] = [];
814
+ if (!abstract) {
815
+ abstract = {
816
+ id: Math.max(-1, ...abstracts.map((a) => a.id)) + 1,
817
+ multiLevelType: "hybridMultilevel",
818
+ levels: levels(kind),
819
+ };
820
+ added.push(abstract);
821
+ }
822
+ const instance: NumberingInstanceJSON = {
823
+ id: nextId(instances.map((n) => n.id)),
824
+ abstract: abstract.id,
825
+ // A numbered list starts again at 1 (instances of one definition otherwise go on counting).
826
+ ...(kind === "orderedList" ? { overrides: [{ level: 0, start: 1 }] } : {}),
827
+ };
828
+ return {
829
+ id: instance.id,
830
+ envelope: {
831
+ ...envelope,
832
+ numbering: { abstracts: [...abstracts, ...added], instances: [...instances, instance] },
833
+ },
834
+ };
835
+ }
836
+
837
+ /**
838
+ * The list buttons on a v3 document: when every selected paragraph is in a list of `kind`, takes
839
+ * them out; otherwise numbers them as `kind` (a numbered paragraph keeps its level). A list of
840
+ * that kind right before the selection goes on; otherwise a new one starts. Paragraphs in the
841
+ * default style go to "List Paragraph" where the document has it, as in Word.
842
+ */
843
+ export function toggleWordList(kind: ListKind): Command {
844
+ return (state, dispatch) => {
845
+ const context = wordContext(state);
846
+ if (!context || !paragraphsIn(state).length) return false;
847
+ if (wordListKindAt(state) === kind)
848
+ return updateParagraphs(state, dispatch, (node) => withoutNumbering(context, node));
849
+ return wrapInWordList(kind)(state, dispatch);
850
+ };
851
+ }
852
+
853
+ /** Numbers the selected paragraphs as a list of `kind` (`wrapInList` on a v3 document). */
854
+ export function wrapInWordList(kind: ListKind): Command {
855
+ return (state, dispatch) => {
856
+ const context = wordContext(state);
857
+ if (!context) return false;
858
+ const paragraphs = paragraphsIn(state);
859
+ const first = paragraphs[0];
860
+ if (!first) return false;
861
+ // A list the paragraph before is in (its own numbering, not a numbered heading's) goes on.
862
+ const before = first.pos > 0 ? state.doc.resolve(first.pos).nodeBefore : null;
863
+ const previous = (before?.attrs.numbering as { id?: number } | null | undefined)?.id;
864
+ // Paragraphs in the default style go to "List Paragraph" (added if the document lacks it).
865
+ const plain = defaultParagraphStyleOf(context);
866
+ const inPlain = (node: Node) => {
867
+ const style = context.resolver.paragraph(node.attrs).paragraph.style;
868
+ return style === plain || style === null;
869
+ };
870
+ const list = paragraphs.some(({ node }) => inPlain(node))
871
+ ? ensureStyle(context, "List Paragraph")
872
+ : null;
873
+ const listStyle = list?.id ?? null;
874
+ let envelope = list?.envelope ?? context.envelope;
875
+ let id: number;
876
+ if (
877
+ previous &&
878
+ before &&
879
+ kindOf(context, before.attrs) === kind &&
880
+ plainList(context, previous)
881
+ )
882
+ id = previous;
883
+ else ({ id, envelope } = newList(envelope, kind));
884
+ return updateParagraphs(
885
+ state,
886
+ dispatch,
887
+ (node) => {
888
+ const current = context.resolver.paragraph(node.attrs).paragraph;
889
+ const level = current.numbering?.level ?? 0;
890
+ const style = listStyle && inPlain(node) ? listStyle : node.attrs.style;
891
+ return { ...node.attrs, style, numbering: { id, level } };
892
+ },
893
+ envelope === context.envelope ? undefined : envelope,
894
+ );
895
+ };
896
+ }
897
+
898
+ /** Whether the caret's paragraph is numbered, and the caret is at its start (or `anywhere`). */
899
+ function caretInList(state: EditorState, context: WordContext, atStart: boolean): Node | null {
900
+ const { selection } = state;
901
+ if (!selection.empty) return null;
902
+ const { $from } = selection;
903
+ if ($from.parent.type.name !== "paragraph" || (atStart && $from.parentOffset > 0)) return null;
904
+ return context.resolver.paragraph($from.parent.attrs).paragraph.numbering ? $from.parent : null;
905
+ }
906
+
907
+ /**
908
+ * Tab on a v3 document: at the start of a numbered paragraph, one level deeper; over several
909
+ * paragraphs, indents them (list levels, half-inch stops), as Word does. Elsewhere it does not
910
+ * apply (Tab types a tab).
911
+ */
912
+ export const sinkWordList: Command = (state, dispatch) => {
913
+ const context = wordContext(state);
914
+ if (!context) return false;
915
+ if (paragraphsIn(state).length < 2 && !caretInList(state, context, true)) return false;
916
+ return changeIndent(1)(state, dispatch);
917
+ };
918
+
919
+ /** Shift+Tab in a list on a v3 document: one level up (out of the list at the top). */
920
+ export const liftWordList: Command = (state, dispatch) => {
921
+ const context = wordContext(state);
922
+ if (!context) return false;
923
+ const numbered = paragraphsIn(state).some(
924
+ ({ node }) => context.resolver.paragraph(node.attrs).paragraph.numbering,
925
+ );
926
+ return numbered && changeIndent(-1)(state, dispatch);
927
+ };
928
+
929
+ /**
930
+ * Enter in an empty numbered paragraph on a v3 document: one level up, or at the top level ends
931
+ * the list there, as in Word.
932
+ */
933
+ export const endWordList: Command = (state, dispatch) => {
934
+ const context = wordContext(state);
935
+ const paragraph = context && caretInList(state, context, true);
936
+ if (!context || !paragraph || paragraph.content.size) return false;
937
+ return changeIndent(-1)(state, dispatch);
938
+ };
939
+
940
+ /**
941
+ * Backspace at the start of a numbered paragraph on a v3 document: removes its number, keeping
942
+ * the text where it was (the level's indent as the paragraph's own); the next Backspace joins.
943
+ */
944
+ export const removeWordListNumber: Command = (state, dispatch) => {
945
+ const context = wordContext(state);
946
+ const paragraph = context && caretInList(state, context, true);
947
+ if (!context || !paragraph) return false;
948
+ return updateParagraphs(state, dispatch, (node) => {
949
+ const { indent } = context.resolver.paragraph(node.attrs).paragraph;
950
+ return {
951
+ ...withoutNumbering(context, node),
952
+ indent: { left: indent.left, right: indent.right, firstLine: 0 },
953
+ };
954
+ });
955
+ };
956
+
957
+ // ---------- links ----------
958
+
959
+ /**
960
+ * Gives newly linked text Word's "Hyperlink" character style (blue, underlined), adding Word's
961
+ * definition where the document does not have it yet.
962
+ */
963
+ export function styleLink(tr: Transaction, state: EditorState, from: number, to: number): void {
964
+ const context = wordContext(state);
965
+ const type = state.schema.marks.characterStyle;
966
+ const style = context && type && ensureStyle(context, "Hyperlink", "character");
967
+ if (!context || !type || !style) return;
968
+ tr.addMark(from, to, type.create({ id: style.id }));
969
+ if (style.envelope !== context.envelope) withEnvelope(tr, style.envelope);
970
+ }
971
+
972
+ /** Takes the "Hyperlink" character style off text whose link is removed. */
973
+ export function unstyleLink(tr: Transaction, state: EditorState, from: number, to: number): void {
974
+ const context = wordContext(state);
975
+ const type = state.schema.marks.characterStyle;
976
+ const style = context && styleNamed(context, "Hyperlink", "character");
977
+ if (!style || !type) return;
978
+ tr.doc.nodesBetween(from, to, (node, pos) => {
979
+ if (type.isInSet(node.marks)?.attrs.id === style)
980
+ tr.removeMark(Math.max(from, pos), Math.min(to, pos + node.nodeSize), type);
981
+ });
982
+ }