@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,245 @@
1
+ /**
2
+ * Editing a schema v3 document as Word edits it (8.7). An editor holding a v3 document keeps
3
+ * the document's envelope (styles, numbering, defaults, theme) in a plugin state field, and the
4
+ * generic commands consult it: Enter splits a paragraph as Word does, the bold, italic,
5
+ * underline and strike toggles act on the formatting text shows (a heading's style bold
6
+ * included), and Backspace and Delete step over the invisible markers (bookmarks, comment
7
+ * ranges) and select opaque content before deleting it.
8
+ *
9
+ * shortcut: v2 and v3 editing live side by side until 8.7d makes v3 the only schema; then these
10
+ * become the commands themselves.
11
+ */
12
+ import type { Attrs, Mark, MarkType, Node } from "../model/index.js";
13
+ import type { FoliDocument } from "../v3/document.js";
14
+ import { Resolver, type RunFormat } from "../v3/resolve.js";
15
+ import { MARK_ATTRS } from "./mark.js";
16
+ import { NodeSelection, TextSelection } from "./selection.js";
17
+ import { type EditorState, Plugin, PluginKey, type Transaction } from "./state.js";
18
+
19
+ /** A v3 document without its content: what the editor keeps beside the edited tree. */
20
+ export type WordEnvelope = Omit<FoliDocument, "content">;
21
+
22
+ export interface WordContext {
23
+ readonly envelope: WordEnvelope;
24
+ readonly resolver: Resolver;
25
+ /**
26
+ * Made when the document is loaded and kept while it is edited: a copy carries it, so a paste
27
+ * tells this document's lists from another's (Word's `w:nsid`; Foli makes equal definitions
28
+ * in every document).
29
+ */
30
+ readonly id: string;
31
+ }
32
+
33
+ const key = new PluginKey<WordContext>("word");
34
+
35
+ /**
36
+ * The plugin that gives commands a v3 document's envelope. A transaction changes it with
37
+ * `withEnvelope` (a new list's numbering definition); undo leaves such additions, as Word does.
38
+ */
39
+ export function wordPlugin(envelope: WordEnvelope): Plugin<WordContext> {
40
+ // Not a secret: only tells documents apart.
41
+ const id = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
42
+ const context: WordContext = { envelope, resolver: new Resolver(envelope), id };
43
+ return new Plugin({
44
+ key,
45
+ state: {
46
+ init: () => context,
47
+ apply: (tr, value) => {
48
+ const next = tr.getMeta(key) as WordEnvelope | undefined;
49
+ return next ? { envelope: next, resolver: new Resolver(next), id: value.id } : value;
50
+ },
51
+ },
52
+ });
53
+ }
54
+
55
+ /** Makes `tr` change the document's envelope to `envelope` (styles, numbering…). */
56
+ export function withEnvelope(tr: Transaction, envelope: WordEnvelope): Transaction {
57
+ return tr.setMeta(key, envelope);
58
+ }
59
+
60
+ /** The envelope and resolver of the v3 document in `state`, or null for a v2 editor. */
61
+ export function wordContext(state: EditorState): WordContext | null {
62
+ return key.getState(state) ?? null;
63
+ }
64
+
65
+ /**
66
+ * What the paragraph mark carries alone (`MARK_ATTRS`): a split leaves it on the second
67
+ * paragraph, which keeps the original mark.
68
+ */
69
+ const MARK_ONLY = Object.fromEntries(MARK_ATTRS.map((key) => [key, null]));
70
+
71
+ /** The id of the default paragraph style: the last one marked default, as `Resolver` reads it. */
72
+ function defaultParagraphStyle(envelope: WordEnvelope): string | undefined {
73
+ let id: string | undefined;
74
+ for (const style of envelope.styles)
75
+ if (style.type === "paragraph" && style.isDefault) id = style.id;
76
+ return id;
77
+ }
78
+
79
+ /**
80
+ * The attributes of the two paragraphs Enter makes of `paragraph`. The first gets a new mark
81
+ * with the same properties; the second keeps the original mark. At the end of a paragraph whose
82
+ * style names another as the next (a heading: Normal), the second paragraph is in that style,
83
+ * without the first's direct formatting. `before` is null when the first keeps every attribute.
84
+ */
85
+ export function splitAttrs(
86
+ context: WordContext,
87
+ paragraph: Node,
88
+ atEnd: boolean,
89
+ ): { before: Attrs | null; after: Attrs } {
90
+ const attrs = paragraph.attrs;
91
+ const markOnly = Object.keys(MARK_ONLY).some((k) => attrs[k] !== null);
92
+ const before = markOnly ? { ...attrs, ...MARK_ONLY } : null;
93
+ if (!atEnd) return { before, after: attrs };
94
+ const id = (attrs.style as string | null) ?? defaultParagraphStyle(context.envelope);
95
+ const style = context.envelope.styles.find((s) => s.id === id);
96
+ const next = style?.next;
97
+ if (next === undefined || next === id) return { before, after: attrs };
98
+ const mark = Object.fromEntries(Object.keys(MARK_ONLY).map((k) => [k, attrs[k] ?? null]));
99
+ return { before, after: { ...mark, style: next } };
100
+ }
101
+
102
+ /** Run toggles: whether text shows the property, from its resolved formatting. */
103
+ const TOGGLES: Record<string, (run: RunFormat) => boolean> = {
104
+ bold: (run) => run.bold,
105
+ italic: (run) => run.italic,
106
+ underline: (run) => run.underline !== null,
107
+ strike: (run) => run.strike,
108
+ doubleStrike: (run) => run.doubleStrike,
109
+ caps: (run) => run.caps,
110
+ smallCaps: (run) => run.smallCaps,
111
+ hidden: (run) => run.hidden,
112
+ };
113
+
114
+ /** Whether `type` is a run property the toggles handle on a v3 document. */
115
+ export function isWordToggle(context: WordContext | null, type: MarkType): boolean {
116
+ return context !== null && Object.hasOwn(TOGGLES, type.name);
117
+ }
118
+
119
+ /** Whether text with `marks` in `paragraph` shows the toggle `type` (marks included or not). */
120
+ function shows(
121
+ context: WordContext,
122
+ paragraph: Node,
123
+ marks: readonly Mark[],
124
+ type: MarkType,
125
+ own = true,
126
+ ): boolean {
127
+ const { run } = context.resolver.paragraph(paragraph.attrs);
128
+ const json = marks.filter((m) => own || m.type !== type).map((m) => m.toJSON());
129
+ return (TOGGLES[type.name] as (run: RunFormat) => boolean)(context.resolver.run(run, json));
130
+ }
131
+
132
+ /**
133
+ * The direct mark that makes text show the toggle `type` as `on`, given what it shows without
134
+ * one (`inherited`); null when no mark is needed. Bold and italic keep their complex-script twin.
135
+ */
136
+ function directMark(type: MarkType, on: boolean, inherited: boolean, existing?: Mark): Mark | null {
137
+ const twin = existing?.attrs.complexScript ?? null;
138
+ const hasTwin = Object.hasOwn(type.spec.attrs ?? {}, "complexScript");
139
+ if (on === inherited)
140
+ return hasTwin && twin !== null ? type.create({ value: null, complexScript: twin }) : null;
141
+ if (type.name === "underline") return type.create({ style: on ? "single" : "none" });
142
+ return type.create(hasTwin ? { value: on, complexScript: twin } : { value: on });
143
+ }
144
+
145
+ /**
146
+ * The inline nodes a toggle formats in a range (not markers: nothing to format), and those it
147
+ * judges: text nodes, or every one when there is none.
148
+ */
149
+ function inlineIn(state: EditorState, from: number, to: number, type: MarkType) {
150
+ const found: { node: Node; pos: number; parent: Node }[] = [];
151
+ state.doc.nodesBetween(from, to, (node, pos, parent) => {
152
+ if (!node.isInline || !parent?.type.allowsMarkType(type)) return undefined;
153
+ if (MARKERS.has(node.type.name)) return false;
154
+ found.push({ node, pos, parent });
155
+ return false;
156
+ });
157
+ const text = found.filter((f) => f.node.isText);
158
+ return text.length ? { all: found, judged: text } : { all: found, judged: found };
159
+ }
160
+
161
+ /** Whether all the selected text (or the text typed at a caret) shows the toggle `type`. */
162
+ export function wordToggleActive(
163
+ context: WordContext,
164
+ state: EditorState,
165
+ type: MarkType,
166
+ caretMarks: readonly Mark[] | null,
167
+ ): boolean {
168
+ const { selection } = state;
169
+ if (caretMarks) return shows(context, selection.$from.parent, caretMarks, type);
170
+ const { judged } = inlineIn(state, selection.from, selection.to, type);
171
+ return judged.length > 0 && judged.every((f) => shows(context, f.parent, f.node.marks, type));
172
+ }
173
+
174
+ /**
175
+ * The stored marks for a toggle at a caret: what makes the next typed text show the opposite of
176
+ * what text typed there would show now.
177
+ */
178
+ export function toggledCaretMarks(
179
+ context: WordContext,
180
+ paragraph: Node,
181
+ marks: readonly Mark[],
182
+ type: MarkType,
183
+ ): readonly Mark[] {
184
+ const on = !shows(context, paragraph, marks, type);
185
+ const existing = type.isInSet(marks);
186
+ const rest = existing ? existing.removeFromSet(marks) : marks;
187
+ const mark = directMark(type, on, shows(context, paragraph, marks, type, false), existing);
188
+ return mark ? mark.addToSet(rest) : rest;
189
+ }
190
+
191
+ /**
192
+ * The mark changes that make every inline node in `from..to` show the toggle `type` as `on`:
193
+ * per node, a direct mark where its style does not already give that, none where it does.
194
+ */
195
+ export function toggleRanges(
196
+ context: WordContext,
197
+ state: EditorState,
198
+ from: number,
199
+ to: number,
200
+ type: MarkType,
201
+ on: boolean,
202
+ ): { from: number; to: number; mark: Mark | null }[] {
203
+ return inlineIn(state, from, to, type).all.map(({ node, pos, parent }) => ({
204
+ from: Math.max(from, pos),
205
+ to: Math.min(to, pos + node.nodeSize),
206
+ mark: directMark(
207
+ type,
208
+ on,
209
+ shows(context, parent, node.marks, type, false),
210
+ type.isInSet(node.marks),
211
+ ),
212
+ }));
213
+ }
214
+
215
+ /** Zero-width markers: nothing to see, so the caret and deletion step over them. */
216
+ const MARKERS = new Set([
217
+ "bookmarkStart",
218
+ "bookmarkEnd",
219
+ "commentStart",
220
+ "commentEnd",
221
+ // A comment's reference mark: deleting it would take the comment's anchor.
222
+ "commentReference",
223
+ ]);
224
+
225
+ /** Whether `node` is an invisible marker of a v3 document. */
226
+ export function isMarker(context: WordContext | null, node: Node | null | undefined): boolean {
227
+ return context !== null && !!node && MARKERS.has(node.type.name);
228
+ }
229
+
230
+ /** Opaque content: deleted only once selected, as Word selects a field before deleting it. */
231
+ export function isOpaque(context: WordContext | null, node: Node | null | undefined): boolean {
232
+ return (
233
+ context !== null &&
234
+ !!node &&
235
+ (node.type.name === "opaqueInline" || node.type.name === "opaqueBlock")
236
+ );
237
+ }
238
+
239
+ /** A node selection of the node at `pos`, or a text selection when it cannot be selected. */
240
+ export function selectionAt(state: EditorState, pos: number): NodeSelection | TextSelection {
241
+ const node = state.doc.nodeAt(pos);
242
+ return node && NodeSelection.isSelectable(node)
243
+ ? NodeSelection.create(state.doc, pos)
244
+ : TextSelection.create(state.doc, pos);
245
+ }
@@ -0,0 +1,445 @@
1
+ /**
2
+ * Copy and paste of schema v3 content (8.7c). A copy carries the definitions its content
3
+ * references (styles, numbering, comments); a paste fits them to the target document, as Word
4
+ * does with its default "use destination styles":
5
+ * - A style the target has by name is used; any other is added (a free id if its id is taken).
6
+ * - A list copied inside one document (the copy carries the document's id, `WordContext.id`)
7
+ * goes on; otherwise it gets an instance of its own (the target's definition when one is the
8
+ * same). Lists of different documents are never taken for each other: Foli makes equal ids
9
+ * and definitions in every document.
10
+ * - Comments are copied with new ids, as Word duplicates them; an anchor without its comment
11
+ * is left out.
12
+ * - A bookmark whose name the target already uses (outside the selection the paste replaces)
13
+ * is left out, as in Word; others get new ids.
14
+ * - From another document, a style or list the copy does not define is not one: the text is in
15
+ * the default style, not numbered (not the target's style or list of that id).
16
+ * - Paragraph ids (`w14:paraId`, `w14:textId`) are left out: export makes the ones it needs.
17
+ *
18
+ * shortcut: ids inside opaque content (a table's bookmarks and paragraph ids) and tracked-change
19
+ * ids are pasted as they are; Word tolerates repeats of both. Map them when a file shows otherwise.
20
+ */
21
+ import { DEFAULT_SETTINGS } from "../document.js";
22
+ import type { MarkJSON, Node, NodeJSON } from "../model/index.js";
23
+ import { type DocJSON, isSafeLink } from "../schema.js";
24
+ import {
25
+ type AbstractNumberingJSON,
26
+ type CommentJSON,
27
+ type NumberingInstanceJSON,
28
+ type NumberingLevelJSON,
29
+ type ParagraphPropertiesJSON,
30
+ parseContent,
31
+ parseDocument,
32
+ type StyleJSON,
33
+ } from "../v3/document.js";
34
+ import { migrateToV3 } from "../v3/migrate.js";
35
+ import { Resolver } from "../v3/resolve.js";
36
+ import type { EditorState } from "./state.js";
37
+ import { type WordContext, type WordEnvelope, wordContext } from "./word.js";
38
+ import { builtinStyle, levels } from "./wordformat.js";
39
+
40
+ /** What a v3 copy carries beside its content: the definitions the content references. */
41
+ export interface WordDefinitions {
42
+ /** The document copied from (`WordContext.id`). */
43
+ document?: string;
44
+ styles: StyleJSON[];
45
+ numbering: { abstracts: AbstractNumberingJSON[]; instances: NumberingInstanceJSON[] };
46
+ comments: CommentJSON[];
47
+ }
48
+
49
+ type Json = Record<string, unknown>;
50
+
51
+ function visit(nodes: readonly NodeJSON[], f: (node: NodeJSON) => void): void {
52
+ for (const node of nodes) {
53
+ f(node);
54
+ visit(node.content ?? [], f);
55
+ }
56
+ }
57
+
58
+ const COMMENT_ANCHORS = new Set(["commentStart", "commentEnd", "commentReference"]);
59
+
60
+ type Properties = Pick<ParagraphPropertiesJSON, "style" | "numbering" | "markFormat">;
61
+
62
+ /**
63
+ * The definitions `content` (copied from the document of `context`) references: its paragraphs'
64
+ * and runs' styles (the paragraph mark's and a tracked change's too) with the styles they are
65
+ * based on, link to or are followed by, its lists' numbering (a style's included), and its
66
+ * comments; with the document's id.
67
+ */
68
+ export function copiedDefinitions(context: WordContext, content: Node): WordDefinitions {
69
+ const { styles, numbering, comments } = context.envelope;
70
+ const styleIds = new Set<string>();
71
+ const numberingIds = new Set<number>();
72
+ const commentIds = new Set<number>();
73
+ const marks = (list: readonly MarkJSON[] | null | undefined) => {
74
+ for (const mark of list ?? [])
75
+ if (mark.type === "characterStyle") styleIds.add(String(mark.attrs?.id));
76
+ };
77
+ const properties = (p: Properties | null | undefined) => {
78
+ if (p?.style) styleIds.add(p.style);
79
+ if (p?.numbering?.id) numberingIds.add(p.numbering.id);
80
+ marks(p?.markFormat);
81
+ };
82
+ const references = (node: NodeJSON) => {
83
+ const attrs = (node.attrs ?? {}) as Properties & {
84
+ id?: number;
85
+ formatChange?: { previous: Properties } | null;
86
+ };
87
+ if (node.type === "paragraph") {
88
+ properties(attrs);
89
+ properties(attrs.formatChange?.previous);
90
+ }
91
+ if (COMMENT_ANCHORS.has(node.type)) commentIds.add(attrs.id as number);
92
+ marks(node.marks);
93
+ };
94
+ visit([content.toJSON()], references);
95
+ const copied = comments.filter((c) => commentIds.has(c.id));
96
+ visit(
97
+ copied.flatMap((c) => c.content),
98
+ references,
99
+ );
100
+ const instances = () => numbering.instances.filter((n) => numberingIds.has(n.id));
101
+ const abstracts = () => {
102
+ const ids = new Set(instances().map((n) => n.abstract));
103
+ return numbering.abstracts.filter((a) => ids.has(a.id));
104
+ };
105
+ // Until nothing new: styles name styles and numbering; numbering levels name styles.
106
+ for (let size = -1; size !== styleIds.size + numberingIds.size; ) {
107
+ size = styleIds.size + numberingIds.size;
108
+ for (const style of styles) {
109
+ if (!styleIds.has(style.id)) continue;
110
+ for (const id of [style.basedOn, style.next, style.link]) if (id) styleIds.add(id);
111
+ const id = style.paragraph?.numbering?.id;
112
+ if (id) numberingIds.add(id);
113
+ }
114
+ for (const abstract of abstracts())
115
+ for (const id of [
116
+ abstract.styleLink,
117
+ abstract.numStyleLink,
118
+ ...abstract.levels.map((l) => l.style),
119
+ ])
120
+ if (id) styleIds.add(id);
121
+ for (const instance of instances())
122
+ for (const o of instance.overrides ?? [])
123
+ if (o.definition?.style) styleIds.add(o.definition.style);
124
+ }
125
+ return {
126
+ document: context.id,
127
+ styles: styles.filter((s) => styleIds.has(s.id)),
128
+ numbering: { abstracts: abstracts(), instances: instances() },
129
+ comments: copied,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * Pasted HTML, read as schema v2 content (`htmlToDoc`, validated), fitted to the v3 document in
135
+ * `state` like `fitPaste`: structured by `migrateToV3`, with Word's built-in heading, List
136
+ * Paragraph and Hyperlink styles where the document lacks them, and the list levels the list
137
+ * buttons make (the document's definition where it has one). Each list is a new one.
138
+ */
139
+ export function fitPastedV2(
140
+ state: EditorState,
141
+ content: Node,
142
+ ): { doc: Node; envelope: WordEnvelope } {
143
+ const migrated = migrateToV3({
144
+ schemaVersion: 2,
145
+ settings: DEFAULT_SETTINGS,
146
+ content: content.toJSON() as DocJSON,
147
+ });
148
+ const definitions: WordDefinitions = {
149
+ styles: migrated.styles.map((style) => {
150
+ // Based on the paste's Normal, which is the target's by name.
151
+ const builtin = style.name ? builtinStyle({ envelope: migrated }, style.name) : null;
152
+ return builtin ? { ...builtin, id: style.id } : style;
153
+ }),
154
+ numbering: {
155
+ // The definitions `newList` makes, so a paste reuses the document's where it has them.
156
+ abstracts: migrated.numbering.abstracts.map((a) => ({
157
+ id: a.id,
158
+ multiLevelType: "hybridMultilevel" as const,
159
+ levels: levels(a.levels[0]?.format === "bullet" ? "bulletList" : "orderedList"),
160
+ })),
161
+ instances: migrated.numbering.instances,
162
+ },
163
+ comments: [],
164
+ };
165
+ const fitted = fit(state, definitions, migrated.content, false);
166
+ // Bold, italic, underline and strike the paragraph's style already gives (HTML writes a
167
+ // heading's bold on its text) are not the text's own, so a style change still applies.
168
+ const resolver = new Resolver(fitted.envelope);
169
+ const json = fitted.doc.toJSON();
170
+ for (const block of json.content ?? []) {
171
+ const { run } = resolver.paragraph(block.attrs ?? {});
172
+ const given: Record<string, boolean> = {
173
+ bold: run.bold,
174
+ italic: run.italic,
175
+ underline: run.underline === "single",
176
+ strike: run.strike,
177
+ };
178
+ for (const child of block.content ?? []) {
179
+ const marks = child.marks?.filter((m) => !given[m.type]);
180
+ if (marks?.length) child.marks = marks;
181
+ else delete child.marks;
182
+ }
183
+ }
184
+ return { doc: parseContent(json), envelope: fitted.envelope };
185
+ }
186
+
187
+ const equal = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
188
+ const PARAGRAPH_IDS = ["w14:paraId", "w14:textId"];
189
+
190
+ /** `json` without the link marks that are not safe (`isSafeLink`; the text stays). */
191
+ function safeLinks(json: NodeJSON): NodeJSON {
192
+ const marks = json.marks?.filter((m) => m.type !== "link" || isSafeLink(m.attrs));
193
+ return {
194
+ ...json,
195
+ ...(marks && { marks }),
196
+ ...(json.content && { content: json.content.map(safeLinks) }),
197
+ };
198
+ }
199
+
200
+ /**
201
+ * Fits pasted v3 `content` (untrusted) to the document in `state`: `definitions` are the ones
202
+ * the copy carried (`copiedDefinitions`, untrusted), or none for content of this document (plain
203
+ * text, older copies). Returns the content to insert and the envelope with what it added (the
204
+ * same object when nothing was added). Throws FoliDocumentError on invalid input.
205
+ */
206
+ export function fitPaste(
207
+ state: EditorState,
208
+ content: unknown,
209
+ definitions?: unknown,
210
+ ): { doc: Node; envelope: WordEnvelope } {
211
+ const context = wordContext(state) as WordContext;
212
+ const target = context.envelope;
213
+ // Taken as this document's own, but it cannot be told to be: no unsafe link comes in.
214
+ if (definitions === undefined || definitions === null)
215
+ return fit(state, target, safeLinks(parseContent(content).toJSON()), true);
216
+ const { document, styles, numbering, comments } = definitions as Partial<WordDefinitions>;
217
+ // Validated as a document's envelope: types, ranges, no style based on itself.
218
+ const checked = parseDocument({
219
+ schemaVersion: 3,
220
+ section: target.section,
221
+ defaults: {},
222
+ styles,
223
+ numbering,
224
+ comments,
225
+ content,
226
+ });
227
+ return fit(state, checked, checked.content, document === context.id);
228
+ }
229
+
230
+ /**
231
+ * `fitPaste` on validated input. `same`: the content is the target document's own (its lists go
232
+ * on, and an id the definitions lack is kept; from elsewhere it names nothing).
233
+ */
234
+ function fit(
235
+ state: EditorState,
236
+ source: WordDefinitions,
237
+ json: NodeJSON,
238
+ same: boolean,
239
+ ): { doc: Node; envelope: WordEnvelope } {
240
+ const target = (wordContext(state) as WordContext).envelope;
241
+ let styles = target.styles;
242
+ let { abstracts, instances } = target.numbering;
243
+ const styleIds = new Map<string, string>();
244
+ const numberingIds = new Map<number, number>();
245
+
246
+ const mapStyle = (id: string): string | null => {
247
+ const known = styleIds.get(id);
248
+ if (known !== undefined) return known;
249
+ const style = source.styles.find((s) => s.id === id);
250
+ if (!style) return same ? id : null;
251
+ const name = style.name?.toLowerCase();
252
+ const found = styles.find(
253
+ (s) =>
254
+ s.type === style.type && (name ? s.name?.toLowerCase() === name : !s.name && s.id === id),
255
+ );
256
+ if (found) {
257
+ styleIds.set(id, found.id);
258
+ return found.id;
259
+ }
260
+ const ids = new Set(styles.map((s) => s.id));
261
+ let next = id;
262
+ for (let i = 1; ids.has(next); i++) next = `${id}${i}`;
263
+ // Reserved first: styles name each other (a paragraph style and its linked character style).
264
+ styleIds.set(id, next);
265
+ const copy: StyleJSON = { ...style, id: next };
266
+ // The target keeps its own default style.
267
+ delete copy.isDefault;
268
+ styles = [...styles, copy];
269
+ for (const key of ["basedOn", "next", "link"] as const) {
270
+ const ref = style[key] && mapStyle(style[key]);
271
+ if (ref) copy[key] = ref;
272
+ else delete copy[key];
273
+ }
274
+ if (style.paragraph) copy.paragraph = paragraphProperties(style.paragraph);
275
+ return next;
276
+ };
277
+
278
+ const mapLevel = (level: NumberingLevelJSON): NumberingLevelJSON => {
279
+ const { style, ...rest } = level;
280
+ const mapped = style && mapStyle(style);
281
+ return mapped ? { ...level, style: mapped } : rest;
282
+ };
283
+
284
+ const mapNumbering = (id: number): number => {
285
+ const known = numberingIds.get(id);
286
+ if (known !== undefined) return known;
287
+ const instance = source.numbering.instances.find((n) => n.id === id);
288
+ const abstract = source.numbering.abstracts.find((a) => a.id === instance?.abstract);
289
+ if (!instance || !abstract) return same ? id : 0;
290
+ // The target's own list, not one this paste added.
291
+ const own = same && target.numbering.instances.find((n) => n.id === id);
292
+ if (
293
+ own &&
294
+ equal(own, instance) &&
295
+ equal(
296
+ target.numbering.abstracts.find((a) => a.id === own.abstract),
297
+ abstract,
298
+ )
299
+ ) {
300
+ numberingIds.set(id, id);
301
+ return id;
302
+ }
303
+ // Reserved first: a level's style may be numbered by this list.
304
+ const copy: NumberingInstanceJSON = {
305
+ ...instance,
306
+ id: Math.max(0, ...instances.map((n) => n.id)) + 1,
307
+ };
308
+ numberingIds.set(id, copy.id);
309
+ instances = [...instances, copy];
310
+ if (instance.overrides)
311
+ copy.overrides = instance.overrides.map((o) =>
312
+ o.definition ? { ...o, definition: mapLevel(o.definition) } : o,
313
+ );
314
+ const mapped: AbstractNumberingJSON = { ...abstract, levels: abstract.levels.map(mapLevel) };
315
+ for (const key of ["styleLink", "numStyleLink"] as const) {
316
+ const ref = abstract[key] && mapStyle(abstract[key]);
317
+ if (ref) mapped[key] = ref;
318
+ else delete mapped[key];
319
+ }
320
+ let existing = abstracts.find((a) => equal({ ...a, id: 0 }, { ...mapped, id: 0 }));
321
+ if (!existing) {
322
+ existing = { ...mapped, id: Math.max(-1, ...abstracts.map((a) => a.id)) + 1 };
323
+ abstracts = [...abstracts, existing];
324
+ }
325
+ copy.abstract = existing.id;
326
+ return copy.id;
327
+ };
328
+
329
+ const runMarks = (marks: readonly MarkJSON[]) =>
330
+ marks.flatMap((m) => {
331
+ // A document keeps any link target its file has; another source gives only safe ones.
332
+ if (m.type === "link") return same || isSafeLink(m.attrs) ? [m] : [];
333
+ if (m.type !== "characterStyle") return [m];
334
+ const id = mapStyle(String(m.attrs?.id));
335
+ return id ? [{ ...m, attrs: { id } }] : [];
336
+ });
337
+
338
+ /** Properties with their style, list and the mark's character style mapped (none: left out). */
339
+ function paragraphProperties<T extends ParagraphPropertiesJSON>(properties: T): T {
340
+ const { style, numbering, markFormat } = properties;
341
+ const next: T = { ...properties };
342
+ const mapped = style && mapStyle(style);
343
+ if (mapped) next.style = mapped;
344
+ else if (style) delete next.style;
345
+ if (numbering?.id) next.numbering = { ...numbering, id: mapNumbering(numbering.id) };
346
+ if (markFormat) next.markFormat = runMarks(markFormat);
347
+ return next;
348
+ }
349
+
350
+ // New ids start above the target's; a pasted bookmark whose name it uses is left out.
351
+ const nextId = { comment: 0, bookmark: 0 };
352
+ for (const c of target.comments) nextId.comment = Math.max(nextId.comment, c.id + 1);
353
+ const names = new Set<string>();
354
+ const { from, to } = state.selection;
355
+ state.doc.descendants((node, pos) => {
356
+ const id = (node.attrs.id as number) + 1;
357
+ if (COMMENT_ANCHORS.has(node.type.name)) nextId.comment = Math.max(nextId.comment, id);
358
+ // A bookmark in the selection goes with it.
359
+ if (node.type.name === "bookmarkStart" && (pos < from || pos >= to))
360
+ names.add(String(node.attrs.name));
361
+ if (node.type.name.startsWith("bookmark")) nextId.bookmark = Math.max(nextId.bookmark, id);
362
+ return node.type.name === "doc" || node.isTextblock;
363
+ });
364
+ const fresh = (kind: keyof typeof nextId, map: Map<number, number>, id: number) => {
365
+ let next = map.get(id);
366
+ if (next === undefined) {
367
+ next = nextId[kind]++;
368
+ map.set(id, next);
369
+ }
370
+ return next;
371
+ };
372
+ const commentIds = new Map<number, number>();
373
+ const defined = new Set(source.comments.map((c) => c.id));
374
+ const bookmarkIds = new Map<number, number>();
375
+ const leftOut = new Set<number>();
376
+
377
+ const mapNode = (node: NodeJSON): NodeJSON | null => {
378
+ const attrs = node.attrs as Json | undefined;
379
+ let next: Json | undefined = attrs;
380
+ if (node.type === "paragraph" && attrs) {
381
+ next = paragraphProperties(attrs as ParagraphPropertiesJSON) as Json;
382
+ const change = attrs.formatChange as { previous: ParagraphPropertiesJSON } | null | undefined;
383
+ if (change) next.formatChange = { ...change, previous: paragraphProperties(change.previous) };
384
+ const own = attrs.attributes as Record<string, string> | null | undefined;
385
+ if (own && PARAGRAPH_IDS.some((key) => key in own)) {
386
+ const rest = Object.fromEntries(
387
+ Object.entries(own).filter(([key]) => !PARAGRAPH_IDS.includes(key)),
388
+ );
389
+ if (Object.keys(rest).length) next.attributes = rest;
390
+ else delete next.attributes;
391
+ }
392
+ } else if (COMMENT_ANCHORS.has(node.type)) {
393
+ const id = attrs?.id as number;
394
+ if (!defined.has(id)) return null;
395
+ next = { ...attrs, id: fresh("comment", commentIds, id) };
396
+ } else if (node.type === "bookmarkStart" || node.type === "bookmarkEnd") {
397
+ const id = attrs?.id as number;
398
+ if (node.type === "bookmarkStart" && names.has(String(attrs?.name))) leftOut.add(id);
399
+ if (leftOut.has(id)) return null;
400
+ if (node.type === "bookmarkStart") names.add(String(attrs?.name));
401
+ next = { ...attrs, id: fresh("bookmark", bookmarkIds, id) };
402
+ }
403
+ const marks = node.marks && runMarks(node.marks);
404
+ const children = node.content
405
+ ?.map(mapNode)
406
+ .filter((child): child is NodeJSON => child !== null);
407
+ return {
408
+ ...node,
409
+ ...(next ? { attrs: next } : {}),
410
+ ...(marks ? { marks } : {}),
411
+ ...(node.content ? { content: children } : {}),
412
+ } as NodeJSON;
413
+ };
414
+
415
+ const doc = parseContent(mapNode(json));
416
+ let comments = target.comments;
417
+ const copiedComments = source.comments.filter((c) => commentIds.has(c.id));
418
+ if (copiedComments.length) {
419
+ comments = [
420
+ ...comments,
421
+ ...copiedComments.map(
422
+ ({ parent, ...comment }): CommentJSON => ({
423
+ ...comment,
424
+ id: commentIds.get(comment.id) as number,
425
+ // A reply whose comment was not copied becomes a comment of its own.
426
+ ...(parent !== undefined && commentIds.has(parent)
427
+ ? { parent: commentIds.get(parent) as number }
428
+ : {}),
429
+ content: comment.content.map((block) => mapNode(block) as NodeJSON),
430
+ }),
431
+ ),
432
+ ];
433
+ }
434
+ const changed =
435
+ styles !== target.styles ||
436
+ abstracts !== target.numbering.abstracts ||
437
+ instances !== target.numbering.instances ||
438
+ comments !== target.comments;
439
+ return {
440
+ doc,
441
+ envelope: changed
442
+ ? { ...target, styles, numbering: { abstracts, instances }, comments }
443
+ : target,
444
+ };
445
+ }