@stll/folio-core 0.76.0 → 0.78.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 (92) hide show
  1. package/dist/ai-edits/headless.d.ts +6 -4
  2. package/dist/ai-edits/headless.js +32 -15
  3. package/dist/ai-edits/pending-suggestions.d.ts +9 -0
  4. package/dist/ai-edits/pending-suggestions.js +11 -0
  5. package/dist/ai-edits/read.js +24 -1
  6. package/dist/ai-edits/table-geometry.js +12 -4
  7. package/dist/canonical/canonicalBatchReview.js +7 -6
  8. package/dist/canonical/canonicalInlineProjection.d.ts +2 -2
  9. package/dist/canonical/canonicalInlineProjection.js +2 -2
  10. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  11. package/dist/canonical/canonicalPublicOperations.js +19 -40
  12. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  13. package/dist/canonical/canonicalSeedContent.js +28 -15
  14. package/dist/canonical/canonicalSession.d.ts +22 -12
  15. package/dist/canonical/canonicalSession.js +190 -194
  16. package/dist/compare/inline-provenance.js +8 -1
  17. package/dist/controller/canonicalClipboard.d.ts +2 -1
  18. package/dist/controller/canonicalClipboard.js +312 -47
  19. package/dist/controller/canonicalComposition.js +67 -14
  20. package/dist/controller/canonicalStoryEditor.js +2 -0
  21. package/dist/controller/hiddenEditorManager.js +2 -0
  22. package/dist/docx/importedIdCollisions.js +29 -4
  23. package/dist/docx/paragraphParser.js +1 -1
  24. package/dist/docx/reviewResolutionProvenance.d.ts +2 -0
  25. package/dist/docx/reviewResolutionProvenance.js +22 -2
  26. package/dist/docx/server/templatePlan/apply.js +47 -2
  27. package/dist/docx/server/templatePlan/blocks.d.ts +34 -7
  28. package/dist/docx/server/templatePlan/blocks.js +190 -13
  29. package/dist/docx/server/templatePlan/builders.d.ts +8 -1
  30. package/dist/docx/server/templatePlan/builders.js +21 -5
  31. package/dist/docx/server/templatePlan/emit.d.ts +2 -0
  32. package/dist/docx/server/templatePlan/emit.js +108 -6
  33. package/dist/docx/server/templatePlan/plan.d.ts +26 -1
  34. package/dist/docx/server/templatePlan/plan.js +181 -21
  35. package/dist/docx/server/templatePlan/planShape.js +15 -3
  36. package/dist/docx/server/templatePlan/revisions.d.ts +55 -0
  37. package/dist/docx/server/templatePlan/revisions.js +276 -2
  38. package/dist/docx/server/templatePlan/story.d.ts +58 -1
  39. package/dist/docx/server/templatePlan/story.js +176 -12
  40. package/dist/docx/server/templatePlan/types.d.ts +153 -1
  41. package/dist/docx/server/templatePlan/verify.js +58 -15
  42. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  43. package/dist/docx/tableGridXml.d.ts +3 -7
  44. package/dist/docx/tableGridXml.js +23 -15
  45. package/dist/docx/tableParser.js +3 -1
  46. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  47. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  48. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  49. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  50. package/dist/prosemirror/canonicalTableCommands.js +7 -9
  51. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  52. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  53. package/dist/prosemirror/conversion/toProseDoc.d.ts +8 -0
  54. package/dist/prosemirror/conversion/toProseDoc.js +43 -19
  55. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  56. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  57. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  58. package/dist/prosemirror/markupViewNotes.js +24 -27
  59. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  60. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  61. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  62. package/dist/prosemirror/markupViewProjection.js +90 -17
  63. package/dist/prosemirror/replacedAnnotations.d.ts +4 -78
  64. package/dist/prosemirror/replacedAnnotations.js +11 -194
  65. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  66. package/dist/prosemirror/styles/styleResolver.js +4 -1
  67. package/dist/server.d.ts +2 -2
  68. package/dist/types/canonicalCapabilities.d.ts +3 -10
  69. package/dist/types/canonicalCapabilities.js +3 -10
  70. package/package.json +2 -2
  71. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  72. package/dist/internal/revisionResolutionEdits.js +0 -18
  73. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  74. package/dist/internal/revisionResolutionInline.js +0 -302
  75. package/dist/internal/revisionResolutionStep.d.ts +0 -3
  76. package/dist/internal/revisionResolutionStep.js +0 -113
  77. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  78. package/dist/internal/revisionResolutionTracking.js +0 -124
  79. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  80. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  81. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  82. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  83. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  84. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  85. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -8
  86. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -56
  87. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  88. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  89. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  90. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  91. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  92. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -1,6 +1,6 @@
1
1
  import { sourceDocumentOf, styleResolverOf } from "../ai-edits/snapshot.js";
2
2
  import { addTrackedDeletionMark } from "../prosemirror/addTrackedDeletionMark.js";
3
- import { expectHyperlinkMarkAttrs, expectRunPropertyChangeMarkAttrs, expectTableCellAttrs } from "../prosemirror/attrs/index.js";
3
+ import { expectHyperlinkMarkAttrs, expectRunPropertyChangeMarkAttrs, expectTableCellAttrs, expectTableRowAttrs } from "../prosemirror/attrs/index.js";
4
4
  import { getDocumentStyleResolver } from "../prosemirror/plugins/documentStyleState.js";
5
5
  import { applyMarksToRunFormattingRepresentation, expandRunFormattingCarrier, runFormattingCarrierReviewText } from "../prosemirror/runFormattingInlineCarriers.js";
6
6
  import { readAuthoredRunFormatting, reconcileRunFormattingMarks } from "../prosemirror/runFormattingReconciliation.js";
@@ -75,6 +75,13 @@ const collectCarriers = ({ doc, targetSnapshot }) => {
75
75
  node,
76
76
  end: position + node.nodeSize
77
77
  });
78
+ if (node.type.name === "table" && node.childCount > 0) {
79
+ let retainedRows = node.childCount;
80
+ node.forEach((row) => {
81
+ if (expectTableRowAttrs(row).trDel != null) retainedRows--;
82
+ });
83
+ if (retainedRows === 0) return false;
84
+ }
78
85
  if ((node.type.name === "tableCell" || node.type.name === "tableHeader") && !isTableCellRetainedInReviewView(expectTableCellAttrs(node).cellMarker?.kind, "final")) return false;
79
86
  if (!node.isInline) return true;
80
87
  const carrier = expandRunFormattingCarrier(node, position);
@@ -12,7 +12,8 @@ type ClipboardAnnotationsOptions = {
12
12
  * The notes and comments the clipboard's references and markers name, read
13
13
  * from the document they were copied from; the paste copies each under a
14
14
  * fresh id. Without that document the ids could name the destination's own
15
- * notes and comments, so the paste refuses.
15
+ * notes and comments: the paste keeps the text and leaves the markers and
16
+ * references out, as a copy made outside the editor holds no comment or note.
16
17
  */
17
18
  export declare const clipboardAnnotations: ({ paragraphs, source }: ClipboardAnnotationsOptions) => Result<PasteAnnotations | undefined, CanonicalSessionError>;
18
19
  /** Clipboard slices are input payloads; their paragraph identities and private captures are not owners. */
@@ -1,5 +1,6 @@
1
1
  import { groundForDocumentOpRefusal } from "../canonical/canonicalRefusalGrounds.js";
2
2
  import { CanonicalSessionError } from "../canonical/canonicalSession.js";
3
+ import { takeDrawingId, usedDrawingIds, withDrawingId } from "../docx/drawingIdNormalization.js";
3
4
  import { createNumberingIdAllocator, numberingNumIdsTaken } from "../docx/numberingIds.js";
4
5
  import { copyParagraphIndentationProjection } from "../docx/paragraphPropertySource.js";
5
6
  import { visitInlineContentSlots, visitParagraphRuns } from "../docx/paragraphTraversal.js";
@@ -30,11 +31,10 @@ const refuse = (message, ground) => Result.err(new CanonicalSessionError({
30
31
  /** Clipboard content the paste cannot read or resolve as given. */
31
32
  const INVALID_CLIPBOARD = { condition: CANONICAL_CONDITION.invalidRequest };
32
33
  /**
33
- * The gap a clipboard block the paste cannot place falls under: a block
34
- * other than a paragraph or a table, at the top or in a cell, is story
35
- * content the session cannot project.
34
+ * The ground of a clipboard block the paste cannot place: every block kind
35
+ * the editor shows pastes, so one it cannot place is a slice it cannot read.
36
36
  */
37
- const UNPLACED_BLOCK = { gap: CANONICAL_GAP.storyContentProjection };
37
+ const UNPLACED_BLOCK = INVALID_CLIPBOARD;
38
38
  const tableRole = (node) => node?.type.spec["tableRole"];
39
39
  /**
40
40
  * A table the clipboard holds part of, opened `left` levels deep at its start
@@ -87,19 +87,126 @@ const withClosedTableEdges = (slice) => {
87
87
  return new Slice(Fragment.from(blocks), opensTable ? 1 : slice.openStart, closesTable ? 1 : slice.openEnd);
88
88
  };
89
89
  /**
90
+ * The slice with each container it is open through at an edge given up for
91
+ * the content copied from it: a copy that starts or ends inside a block
92
+ * content control, custom XML element, text box or inline content control
93
+ * holds part of it, which pastes as that content, as a copy from inside a
94
+ * paragraph pastes as its text. A block wrapper open at an edge is given up
95
+ * however deep the slice opens through it, its first or last paragraph then
96
+ * pasting whole; a paragraph open only at depth one keeps its inline content.
97
+ */
98
+ const withOpenContainersUnwrapped = (slice) => {
99
+ /**
100
+ * One edge unwrapped. A node the edge gives up that is also the other
101
+ * edge's, the only child where both edges run through it, takes a depth
102
+ * from the other edge too.
103
+ */
104
+ const unwrapEdge = (fragment, open, other, edge) => {
105
+ let current = fragment;
106
+ let depth = open;
107
+ let otherDepth = other;
108
+ let shared = true;
109
+ while (depth > 0) {
110
+ const node = edge === "start" ? current.firstChild : current.lastChild;
111
+ if (node === null || node.type.name === "table") break;
112
+ const children = [];
113
+ current.forEach((child) => children.push(child));
114
+ if (node.type.name !== "paragraph") {
115
+ if (node.isTextblock || node.isLeaf || node.childCount === 0) break;
116
+ if (depth === 1 && node.isInline) break;
117
+ const inner = [];
118
+ node.forEach((child) => inner.push(child));
119
+ current = Fragment.from(edge === "start" ? [...inner, ...children.slice(1)] : [...children.slice(0, -1), ...inner]);
120
+ shared &&= children.length === 1 && otherDepth > 0;
121
+ if (shared) otherDepth -= 1;
122
+ depth -= 1;
123
+ continue;
124
+ }
125
+ if (depth === 1) break;
126
+ const inline = edge === "start" ? node.content.firstChild : node.content.lastChild;
127
+ if (inline === null || inline.isText || inline.isLeaf) break;
128
+ const siblings = [];
129
+ node.content.forEach((child) => siblings.push(child));
130
+ const lifted = [];
131
+ inline.forEach((child) => lifted.push(child));
132
+ const paragraph = node.copy(Fragment.from(edge === "start" ? [...lifted, ...siblings.slice(1)] : [...siblings.slice(0, -1), ...lifted]));
133
+ current = Fragment.from(edge === "start" ? [paragraph, ...children.slice(1)] : [...children.slice(0, -1), paragraph]);
134
+ shared &&= children.length === 1 && siblings.length === 1 && otherDepth > 1;
135
+ if (shared) otherDepth -= 1;
136
+ depth -= 1;
137
+ }
138
+ return {
139
+ fragment: current,
140
+ open: depth,
141
+ other: otherDepth
142
+ };
143
+ };
144
+ const start = unwrapEdge(slice.content, slice.openStart, slice.openEnd, "start");
145
+ const end = unwrapEdge(start.fragment, start.other, start.open, "end");
146
+ return new Slice(end.fragment, end.other, end.open);
147
+ };
148
+ /** Range markers between blocks hold no text; a paste leaves them behind. */
149
+ const BETWEEN_BLOCK_MARKERS = /* @__PURE__ */ new Set([
150
+ "bookmarkStart",
151
+ "bookmarkEnd",
152
+ "commentRangeStart",
153
+ "commentRangeEnd",
154
+ "moveFromRangeStart",
155
+ "moveFromRangeEnd",
156
+ "moveToRangeStart",
157
+ "moveToRangeEnd"
158
+ ]);
159
+ /** A converted clipboard block the paste places, or `undefined` for a marker it leaves. */
160
+ const pastedBlockOf = (block) => {
161
+ switch (block.type) {
162
+ case "paragraph":
163
+ case "table":
164
+ case "blockSdt":
165
+ case "blockCustomXml":
166
+ case "preservedBlock": return block;
167
+ default: return BETWEEN_BLOCK_MARKERS.has(block.type) ? void 0 : panic(`A clipboard block of kind ${block.type} has no placement.`);
168
+ }
169
+ };
170
+ /** `blocks` without the range markers between them, at any depth. */
171
+ const withoutBlockMarkers = (blocks) => {
172
+ for (let index = blocks.length - 1; index >= 0; index -= 1) {
173
+ const block = blocks[index];
174
+ if (block === void 0) continue;
175
+ if (BETWEEN_BLOCK_MARKERS.has(block.type)) {
176
+ blocks.splice(index, 1);
177
+ continue;
178
+ }
179
+ if (block.type === "blockSdt" || block.type === "blockCustomXml") withoutBlockMarkers(block.content);
180
+ }
181
+ };
182
+ /**
90
183
  * A pasted block's paragraphs in document order, a table's cell paragraphs
91
- * among them, each with the place it fills; undefined when a cell holds a
92
- * block other than a paragraph or a table.
184
+ * and a container's among them, each with the place it fills.
93
185
  */
94
186
  const clipboardParagraphs = (block, replace = () => {}) => {
95
187
  if (block.type === "paragraph") return [{
96
188
  paragraph: block,
97
189
  replace
98
190
  }];
191
+ if (block.type === "preservedBlock") return [];
192
+ if (block.type === "blockSdt" || block.type === "blockCustomXml") {
193
+ const places = [];
194
+ for (const [index, inner] of block.content.entries()) {
195
+ const pasted = pastedBlockOf(inner);
196
+ if (pasted === void 0) continue;
197
+ const found = clipboardParagraphs(pasted, (next) => {
198
+ block.content[index] = next;
199
+ });
200
+ if (found === void 0) return void 0;
201
+ places.push(...found);
202
+ }
203
+ return places;
204
+ }
99
205
  const places = [];
100
206
  for (const row of block.rows) for (const cell of row.cells) for (const [index, inner] of cell.content.entries()) {
101
- if (inner.type !== "paragraph" && inner.type !== "table") return void 0;
102
- const found = clipboardParagraphs(inner, (next) => {
207
+ const pasted = pastedBlockOf(inner);
208
+ if (pasted === void 0) continue;
209
+ const found = clipboardParagraphs(pasted, (next) => {
103
210
  cell.content[index] = next;
104
211
  });
105
212
  if (found === void 0) return void 0;
@@ -111,8 +218,26 @@ const clipboardParagraphs = (block, replace = () => {}) => {
111
218
  * A table's verbatim captures describe the markup it was read from; a pasted
112
219
  * copy is new content the serializer writes from its model.
113
220
  */
114
- /** Every table among the blocks, those nested in cells included. */
115
- const clipboardTables = (blocks) => blocks.flatMap((block) => block.type === "table" ? [block, ...clipboardTables(block.rows.flatMap((row) => row.cells.flatMap((cell) => cell.content.filter((inner) => inner.type === "paragraph" || inner.type === "table"))))] : []);
221
+ /** Every table among the blocks, those nested in cells and containers included. */
222
+ const clipboardTables = (blocks) => blocks.flatMap((block) => {
223
+ switch (block.type) {
224
+ case "table": return [block, ...clipboardTables(block.rows.flatMap((row) => row.cells.flatMap((cell) => cell.content)))];
225
+ case "blockSdt":
226
+ case "blockCustomXml": return clipboardTables(block.content);
227
+ default: return [];
228
+ }
229
+ });
230
+ /** Every piece of kept block markup among the blocks, at any depth. */
231
+ const clipboardPreservedBlocks = (blocks) => blocks.flatMap((block) => {
232
+ switch (block.type) {
233
+ case "preservedBlock": return [block.xml];
234
+ case "table": return clipboardPreservedBlocks(block.rows.flatMap((row) => row.cells.flatMap((cell) => cell.content)));
235
+ case "blockSdt":
236
+ case "blockCustomXml": return clipboardPreservedBlocks(block.content);
237
+ default: return [];
238
+ }
239
+ });
240
+ /** A table's own captures; the tables in its cells are their own. */
116
241
  const withoutTableCaptures = (table) => {
117
242
  if (table.formatting !== void 0) {
118
243
  delete table.formatting.sourceXml;
@@ -120,16 +245,21 @@ const withoutTableCaptures = (table) => {
120
245
  }
121
246
  for (const row of table.rows) {
122
247
  if (row.formatting !== void 0) delete row.formatting.sourceXml;
123
- for (const cell of row.cells) {
124
- if (cell.formatting !== void 0) delete cell.formatting.sourceXml;
125
- for (const inner of cell.content) if (inner.type === "table") withoutTableCaptures(inner);
126
- }
248
+ for (const cell of row.cells) if (cell.formatting !== void 0) delete cell.formatting.sourceXml;
127
249
  }
128
250
  };
251
+ /**
252
+ * Every table among the blocks freed of its verbatim captures, those nested
253
+ * in cells and containers, a container in a cell among them, included.
254
+ */
255
+ const withoutContainedTableCaptures = (blocks) => {
256
+ for (const table of clipboardTables(blocks)) withoutTableCaptures(table);
257
+ };
129
258
  /** A pasted block's own copy, each paragraph keeping its indentation provenance. */
130
259
  const cloneClipboardBlock = (block) => {
131
260
  const clone = structuredClone(block);
132
- if (clone.type === "table") withoutTableCaptures(clone);
261
+ withoutContainedTableCaptures([clone]);
262
+ if (clone.type === "blockSdt" || clone.type === "blockCustomXml") withoutBlockMarkers(clone.content);
133
263
  const sources = clipboardParagraphs(block) ?? [];
134
264
  const targets = clipboardParagraphs(clone) ?? [];
135
265
  for (const [index, { paragraph: target }] of targets.entries()) {
@@ -296,10 +426,39 @@ const importNumbering = ({ destination, source, paragraphs, mode, sourceKind, ex
296
426
  });
297
427
  };
298
428
  /**
429
+ * The paragraphs without their comment markers, comment references and note
430
+ * references: their text stays, and nothing names a comment or note.
431
+ */
432
+ const withoutAnnotationMarkers = (paragraphs) => {
433
+ for (const paragraph of paragraphs) {
434
+ const marked = [];
435
+ visitInlineContentSlots(paragraph, ({ content, index, item }) => {
436
+ if (item.type === "commentRangeStart" || item.type === "commentRangeEnd" || item.type === "commentReference") marked.push({
437
+ content,
438
+ index
439
+ });
440
+ });
441
+ for (const { content, index } of marked.toReversed()) content.splice(index, 1);
442
+ const emptied = [];
443
+ visitInlineContentSlots(paragraph, ({ content, index, item }) => {
444
+ if (item.type !== "run") return;
445
+ const kept = item.content.filter((child) => child.type !== "footnoteRef" && child.type !== "endnoteRef");
446
+ if (kept.length === item.content.length) return;
447
+ if (kept.length === 0) emptied.push({
448
+ content,
449
+ index
450
+ });
451
+ else item.content = kept;
452
+ });
453
+ for (const { content, index } of emptied.toReversed()) content.splice(index, 1);
454
+ }
455
+ };
456
+ /**
299
457
  * The notes and comments the clipboard's references and markers name, read
300
458
  * from the document they were copied from; the paste copies each under a
301
459
  * fresh id. Without that document the ids could name the destination's own
302
- * notes and comments, so the paste refuses.
460
+ * notes and comments: the paste keeps the text and leaves the markers and
461
+ * references out, as a copy made outside the editor holds no comment or note.
303
462
  */
304
463
  const clipboardAnnotations = ({ paragraphs, source }) => {
305
464
  const comments = /* @__PURE__ */ new Set();
@@ -313,19 +472,71 @@ const clipboardAnnotations = ({ paragraphs, source }) => {
313
472
  });
314
473
  }
315
474
  if (comments.size === 0 && notes.size === 0) return Result.ok(void 0);
316
- const refusal = (message) => Result.err(new CanonicalSessionError({
317
- ground: { gap: CANONICAL_GAP.storyContentProjection },
318
- reason: "refused",
319
- message
320
- }));
321
- if (source === void 0) return refusal("Clipboard comments and note references require the document they were copied from.");
475
+ if (source === void 0) {
476
+ withoutAnnotationMarkers(paragraphs);
477
+ return Result.ok(void 0);
478
+ }
322
479
  const annotations = {
323
480
  notes: [...source.package.footnotes ?? [], ...source.package.endnotes ?? []].filter(({ type, id }) => notes.has(`${type}:${String(id)}`)),
324
481
  comments: (source.package.document.comments ?? []).filter(({ id }) => comments.has(id))
325
482
  };
326
- if (annotations.notes.length !== notes.size || annotations.comments.length !== comments.size) return refusal("A clipboard comment or note reference names none in the document it was copied from.");
483
+ if (annotations.notes.length !== notes.size || annotations.comments.length !== comments.size) return refuse("A clipboard comment or note reference names none in the document it was copied from.", INVALID_CLIPBOARD);
327
484
  return Result.ok(annotations);
328
485
  };
486
+ /** The relationship ids markup names, in any office relationship attribute. */
487
+ const relationshipIdsIn = (xml) => {
488
+ const parsed = Result.try({
489
+ try: () => parseXml(`<root>${xml}</root>`, OOXML_NAMESPACE_SCOPE),
490
+ catch: () => new CanonicalSessionError({
491
+ ground: INVALID_CLIPBOARD,
492
+ reason: "refused",
493
+ message: "The clipboard block markup is malformed."
494
+ })
495
+ });
496
+ if (parsed.isErr()) return parsed;
497
+ const ids = [];
498
+ const visit = (element) => {
499
+ for (const name of Object.keys(element.attributes ?? {})) {
500
+ const attribute = findAttributeByNamespaceUri(element, OFFICE_RELATIONSHIP_NAMESPACE_URIS, getLocalName(name));
501
+ if (attribute !== null && attribute.name === name) ids.push(attribute.value);
502
+ }
503
+ for (const child of element.elements ?? []) visit(child);
504
+ };
505
+ visit(parsed.value);
506
+ return Result.ok(ids);
507
+ };
508
+ /** Whether the paragraphs hold an image or an external link. */
509
+ const namesPartRelationships = (paragraphs) => paragraphs.some((paragraph) => {
510
+ let related = false;
511
+ visitInlineContentSlots(paragraph, ({ item }) => {
512
+ if (item.type === "hyperlink" && item.anchor === void 0) related = true;
513
+ });
514
+ visitParagraphRuns(paragraph, (run) => {
515
+ if (run.content.some((child) => child.type === "drawing")) related = true;
516
+ });
517
+ return related;
518
+ });
519
+ /** Whether two relationships name the same target in the same way. */
520
+ const sameRelationship = (left, right) => left !== void 0 && right !== void 0 && left.type === right.type && left.target === right.target && left.targetMode === right.targetMode;
521
+ /**
522
+ * The image relationship ids and the markup a range of the editor's own
523
+ * document holds. A move carries what it drags within the part whose
524
+ * relationships it names, so what this range holds stays that part's own.
525
+ */
526
+ const rangeHoldings = (doc, { from, to }) => {
527
+ const relationshipIds = /* @__PURE__ */ new Set();
528
+ const markup = /* @__PURE__ */ new Set();
529
+ doc.nodesBetween(from, to, (node) => {
530
+ const rId = node.attrs["rId"];
531
+ if (node.type.name === "image" && typeof rId === "string") relationshipIds.add(rId);
532
+ for (const value of Object.values(node.attrs)) if (typeof value === "string" && value.startsWith("<")) markup.add(value);
533
+ return true;
534
+ });
535
+ return {
536
+ relationshipIds,
537
+ markup
538
+ };
539
+ };
329
540
  const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, moveTarget, pasteTarget, sourceDocument, moveSource }) => {
330
541
  if (session.isComposing) return refuse("Composition must finish before using the clipboard.", { condition: CANONICAL_CONDITION.composing });
331
542
  if (copied.content.size === 0) return Result.err(new CanonicalSessionError({
@@ -333,21 +544,22 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
333
544
  message: "The clipboard contains no content.",
334
545
  reason: "noChange"
335
546
  }));
336
- const slice = withClosedTableEdges(copied);
547
+ const closed = withClosedTableEdges(copied);
548
+ if (closed === void 0) return refuse("The clipboard table holds no cells.", INVALID_CLIPBOARD);
549
+ const slice = withClosedTableEdges(withOpenContainersUnwrapped(closed));
337
550
  if (slice === void 0) return refuse("The clipboard table holds no cells.", INVALID_CLIPBOARD);
338
551
  if (slice.openStart > 1 || slice.openEnd > 1) return refuse("Clipboard tables and nested block containers require canonical table editing.", UNPLACED_BLOCK);
339
552
  const paragraphType = state.schema.nodes["paragraph"];
340
553
  if (paragraphType === void 0) return refuse("Clipboard input requires a paragraph schema.", { condition: CANONICAL_CONDITION.internal });
341
- const tableType = state.schema.nodes["table"];
342
554
  let inline = true;
343
555
  let blocksOnly = true;
344
556
  slice.content.forEach((node) => {
345
557
  inline &&= node.isInline;
346
- blocksOnly &&= node.type === paragraphType || node.type === tableType;
558
+ blocksOnly &&= node.isBlock;
347
559
  });
348
560
  if (!inline && !blocksOnly) return refuse("Clipboard tables and embedded blocks require canonical table editing.", UNPLACED_BLOCK);
349
561
  const importedSlice = inline ? new Slice(Fragment.from(paragraphType.create(null, slice.content)), 1, 1) : slice;
350
- const converted = Result.try({
562
+ const convertedBlocks = Result.try({
351
563
  try: () => proseDocToBlocks(state.schema.topNodeType.create(null, importedSlice.content), []),
352
564
  catch: (cause) => new CanonicalSessionError({
353
565
  ground: INVALID_CLIPBOARD,
@@ -355,12 +567,20 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
355
567
  message: `Clipboard normalization failed: ${cause instanceof Error ? cause.message : String(cause)}`
356
568
  })
357
569
  });
358
- if (converted.isErr()) return converted;
570
+ if (convertedBlocks.isErr()) return convertedBlocks;
359
571
  const blocks = [];
360
- for (const block of converted.value) {
361
- if (block.type !== "paragraph" && block.type !== "table" || clipboardParagraphs(block) === void 0) return refuse("The clipboard contains an unsupported block.", UNPLACED_BLOCK);
362
- blocks.push(cloneClipboardBlock(block));
572
+ for (const converted of convertedBlocks.value) {
573
+ const block = pastedBlockOf(converted);
574
+ if (block === void 0) continue;
575
+ const clone = cloneClipboardBlock(block);
576
+ if (clipboardParagraphs(clone) === void 0) return refuse("The clipboard contains an unsupported block.", UNPLACED_BLOCK);
577
+ blocks.push(clone);
363
578
  }
579
+ if (blocks.length === 0) return Result.err(new CanonicalSessionError({
580
+ ground: INVALID_CLIPBOARD,
581
+ message: "The clipboard contains no content.",
582
+ reason: "noChange"
583
+ }));
364
584
  const places = blocks.flatMap((block, index) => clipboardParagraphs(block, (next) => {
365
585
  blocks[index] = next;
366
586
  }) ?? []);
@@ -403,16 +623,7 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
403
623
  }
404
624
  });
405
625
  const annotationParagraphs = annotationBodies.map(({ paragraph }) => paragraph);
406
- for (const paragraph of annotationParagraphs) {
407
- let related = false;
408
- visitInlineContentSlots(paragraph, ({ item }) => {
409
- if (item.type === "hyperlink" && item.anchor === void 0) related = true;
410
- });
411
- visitParagraphRuns(paragraph, (run) => {
412
- if (run.content.some((child) => child.type === "drawing")) related = true;
413
- });
414
- if (related) return refuse("Copied notes and comments holding images or external links require their part's relationships.", { gap: CANONICAL_GAP.storyContentProjection });
415
- }
626
+ for (const comment of annotations?.comments ?? []) if (namesPartRelationships(comment.content)) return refuse("Copied comments holding images or external links require their part's relationships.", { gap: CANONICAL_GAP.storyContentProjection });
416
627
  const destination = readModel(session.document);
417
628
  let styles = destination.package.styles;
418
629
  let styleIds;
@@ -473,8 +684,9 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
473
684
  let importedResource = false;
474
685
  let imageIndex = 1;
475
686
  let relationshipIndex = 1;
687
+ let sourceRelationships = sourceDocument?.package.relationships;
476
688
  const importExternalLink = (href, previousId) => {
477
- const source = previousId === void 0 ? void 0 : sourceDocument?.package.relationships?.get(previousId);
689
+ const source = previousId === void 0 ? void 0 : sourceRelationships?.get(previousId);
478
690
  let target = href;
479
691
  if (target === void 0 || target.length === 0) target = source?.targetMode === "External" ? source.target : void 0;
480
692
  if (target === void 0 || target.length === 0) return refuse("The clipboard hyperlink has no resolved target.", INVALID_CLIPBOARD);
@@ -526,7 +738,9 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
526
738
  if (imported.isErr()) return imported;
527
739
  return Result.ok((parsed.value.elements ?? []).map(captureVerbatimXml).join(""));
528
740
  };
529
- for (const paragraph of paragraphs) {
741
+ let drawingIds;
742
+ const moved = moveTarget === void 0 ? void 0 : rangeHoldings(state.doc, moveSource ?? selectionRange);
743
+ const importResources = (paragraph) => {
530
744
  if (moveTarget === void 0) {
531
745
  const links = [];
532
746
  visitInlineContentSlots(paragraph, ({ item }) => {
@@ -547,9 +761,14 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
547
761
  visitParagraphRuns(paragraph, (run) => runs.push(run));
548
762
  for (const item of runs) {
549
763
  if (plain) item.formatting = marksToTextFormatting(state.storedMarks ?? state.doc.resolve(pasteTarget ?? moveSource?.from ?? selectionRange.from).marks());
550
- for (const child of item.content) {
764
+ for (const [index, child] of item.content.entries()) {
551
765
  if (child.type !== "drawing") continue;
552
- if (child.rawXmlMode !== void 0) return refuse("Opaque drawings and embedded objects require their source package parts.", { gap: CANONICAL_GAP.storyContentProjection });
766
+ if (child.rawXmlMode !== void 0) {
767
+ const kept = keptOpaqueDrawing(child);
768
+ if (kept.isErr()) return kept;
769
+ item.content[index] = kept.value;
770
+ continue;
771
+ }
553
772
  delete child.rawXml;
554
773
  delete child.rawImageFingerprint;
555
774
  const image = child.image;
@@ -580,11 +799,12 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
580
799
  if (rebound.isErr()) return rebound;
581
800
  image.hlinkHoverXml = rebound.value;
582
801
  }
802
+ if (moved !== void 0 && image.rId !== void 0 && moved.relationshipIds.has(image.rId)) continue;
583
803
  const relationship = image.rId === void 0 ? void 0 : relationships.get(image.rId);
584
804
  const ownedPath = relationship?.target.startsWith("/") ? relationship.target.slice(1) : `word/${relationship?.target ?? ""}`;
585
- const ownedMedia = relationship === void 0 ? void 0 : media.get(ownedPath);
805
+ const ownedMedia = relationship === void 0 || sourceRelationships === void 0 ? void 0 : media.get(ownedPath);
586
806
  if (ownedMedia !== void 0 && (moveTarget !== void 0 || image.src !== void 0 && ownedMedia.dataUrl === image.src)) continue;
587
- const sourceRelationship = image.rId === void 0 ? void 0 : sourceDocument?.package.relationships?.get(image.rId);
807
+ const sourceRelationship = image.rId === void 0 ? void 0 : sourceRelationships?.get(image.rId);
588
808
  const sourcePath = sourceRelationship?.target.startsWith("/") ? sourceRelationship.target.slice(1) : `word/${sourceRelationship?.target ?? ""}`;
589
809
  const sourceMedia = sourceDocument?.package.media?.get(sourcePath);
590
810
  if (sourceMedia !== void 0 && sourceMedia.data.byteLength > MAX_CLIPBOARD_IMAGE_BYTES) return refuse("The clipboard image exceeds the import size limit.", INVALID_CLIPBOARD);
@@ -636,6 +856,51 @@ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, m
636
856
  importedResource = true;
637
857
  }
638
858
  }
859
+ return Result.ok(void 0);
860
+ };
861
+ /**
862
+ * An opaque drawing or embedded object, kept as its markup with a fresh
863
+ * drawing id: its parts (a chart, an embedding, a diagram) are carried by
864
+ * the package it was read from, not by the model, so it pastes only into
865
+ * that package, where every relationship it names is the one it named.
866
+ */
867
+ const keptMarkupPlaced = (xml, message) => {
868
+ const referenced = relationshipIdsIn(xml);
869
+ if (referenced.isErr()) return referenced;
870
+ if (referenced.value.length === 0 || moved?.markup.has(xml) === true) return Result.ok(void 0);
871
+ if (!(sourceDocument !== void 0 && sourceDocument.originalBuffer !== void 0 && sourceDocument.originalBuffer === destination.originalBuffer) || referenced.value.some((id) => !sameRelationship(sourceRelationships?.get(id), relationships.get(id)))) return refuse(message, { gap: CANONICAL_GAP.storyContentProjection });
872
+ return Result.ok(void 0);
873
+ };
874
+ const keptOpaqueDrawing = (drawing) => {
875
+ const placed = keptMarkupPlaced(drawing.rawXml ?? "", "Opaque drawings and embedded objects paste only into the package holding their parts.");
876
+ if (placed.isErr()) return placed;
877
+ drawingIds ??= usedDrawingIds({
878
+ documentBody: destination.package.document,
879
+ headers: destination.package.headers,
880
+ footers: destination.package.footers,
881
+ footnotes: destination.package.footnotes,
882
+ endnotes: destination.package.endnotes
883
+ });
884
+ const id = takeDrawingId(drawingIds);
885
+ const kept = structuredClone(drawing);
886
+ kept.image.id = id;
887
+ const renumbered = withDrawingId(drawing, id).rawXml;
888
+ if (renumbered !== void 0) kept.rawXml = renumbered;
889
+ return Result.ok(kept);
890
+ };
891
+ for (const paragraph of paragraphs) {
892
+ const imported = importResources(paragraph);
893
+ if (imported.isErr()) return imported;
894
+ }
895
+ for (const xml of clipboardPreservedBlocks(blocks)) {
896
+ const placed = keptMarkupPlaced(xml, "Kept block markup naming package parts pastes only into the package holding them.");
897
+ if (placed.isErr()) return placed;
898
+ }
899
+ sourceRelationships = void 0;
900
+ for (const note of annotations?.notes ?? []) for (const block of note.content) {
901
+ if (block.type !== "paragraph") continue;
902
+ const imported = importResources(block);
903
+ if (imported.isErr()) return imported;
639
904
  }
640
905
  const resourceOps = [];
641
906
  if (importedResource || numbering !== destination.package.numbering || styles !== destination.package.styles) {
@@ -1,13 +1,20 @@
1
1
  import { splitsSurrogatePair } from "../ai-edits/character-boundaries.js";
2
2
  import { CanonicalSessionError } from "../canonical/canonicalSession.js";
3
- import { CANONICAL_CONDITION, CANONICAL_GAP } from "../types/canonicalCapabilities.js";
3
+ import { CANONICAL_CONDITION } from "../types/canonicalCapabilities.js";
4
4
  import { setCanonicalInputTimer } from "./canonicalInputTimer.js";
5
5
  import { Result } from "better-result";
6
6
  import { EditorState, TextSelection } from "prosemirror-state";
7
7
  import { DOMParser, DOMSerializer, Fragment } from "prosemirror-model";
8
8
  // src/controller/canonicalComposition.ts
9
- /** A composition over content the session cannot project, restored. */
10
- const UNSUPPORTED_COMPOSITION = { gap: CANONICAL_GAP.storyContentProjection };
9
+ /**
10
+ * A composition the browser's own input did not reduce to one text
11
+ * replacement, restored. The commit reads what native input changed from the
12
+ * view; where it changed an atom (an image, a field, a note reference) or
13
+ * more than one textblock, or a plugin rewrote more than text, the DOM states
14
+ * no edit the session can tell from noise. The user types the text again, as
15
+ * input outside a composition reaches the session as intents.
16
+ */
17
+ const UNSUPPORTED_COMPOSITION = { condition: CANONICAL_CONDITION.invalidRequest };
11
18
  const REVIEW_MARK_NAMES = /* @__PURE__ */ new Set(["insertion", "deletion"]);
12
19
  const readBackCache = /* @__PURE__ */ new WeakMap();
13
20
  /**
@@ -31,6 +38,35 @@ const readBack = (mark) => {
31
38
  readBackCache.set(mark, read);
32
39
  return read;
33
40
  };
41
+ /** The depth of the innermost textblock holding `position`, if one does. */
42
+ const textblockDepth = (position) => {
43
+ for (let depth = position.depth; depth >= 0; depth -= 1) if (position.node(depth).isTextblock) return depth;
44
+ };
45
+ /** The child of `fragment` that `position` falls in, with its offset. */
46
+ const childAround = (fragment, position) => {
47
+ let found;
48
+ fragment.forEach((node, offset) => {
49
+ if (found === void 0 && position < offset + node.nodeSize) found = {
50
+ node,
51
+ offset
52
+ };
53
+ });
54
+ return found;
55
+ };
56
+ /**
57
+ * One character for each position of `fragment`: a text node's own, the
58
+ * object replacement character for an inline atom, and a private-use
59
+ * character for each edge of an inline node holding content.
60
+ */
61
+ const positionText = (fragment) => {
62
+ let text = "";
63
+ fragment.forEach((node) => {
64
+ if (node.isText) text += node.text ?? "";
65
+ else if (node.isLeaf) text += "".repeat(node.nodeSize);
66
+ else text += `\uE000${positionText(node.content)}\uE001`;
67
+ });
68
+ return text;
69
+ };
34
70
  /**
35
71
  * Whether a native proposal is one plain replacement. The commit is a text
36
72
  * replacement over the captured model, so this only has to tell DOM noise from a
@@ -142,7 +178,9 @@ const createCanonicalComposition = (options) => {
142
178
  };
143
179
  const replacement = (baseline, proposed) => {
144
180
  const { $from, $to } = baseline.selection;
145
- if (!$from.parent.isTextblock || !$to.parent.isTextblock) return null;
181
+ const fromDepth = textblockDepth($from);
182
+ const toDepth = textblockDepth($to);
183
+ if (fromDepth === void 0 || toDepth === void 0) return null;
146
184
  const selected = selectedReplacement(baseline, proposed);
147
185
  if (selected) {
148
186
  if ($from.sameParent($to) && selected.text === baseline.doc.textBetween(selected.from, selected.to, "", "")) return {
@@ -153,12 +191,12 @@ const createCanonicalComposition = (options) => {
153
191
  };
154
192
  return selected;
155
193
  }
156
- if (!$from.sameParent($to)) return null;
157
- const start = $from.start();
158
- const next = proposed.doc.nodeAt(start - 1);
159
- if (!next || next.type !== $from.parent.type) return null;
160
- const previous = $from.parent.content;
161
- const changedFrom = previous.findDiffStart(next.content);
194
+ const paragraphStart = $from.start(fromDepth);
195
+ if (paragraphStart !== $to.start(toDepth)) return null;
196
+ const textblock = $from.node(fromDepth);
197
+ const proposedParagraph = proposed.doc.nodeAt(paragraphStart - 1);
198
+ if (!proposedParagraph || proposedParagraph.type !== textblock.type) return null;
199
+ const changedFrom = textblock.content.findDiffStart(proposedParagraph.content);
162
200
  if (changedFrom === null) {
163
201
  if (!baseline.doc.eq(proposed.doc)) return null;
164
202
  return {
@@ -168,7 +206,7 @@ const createCanonicalComposition = (options) => {
168
206
  semantic: "composition"
169
207
  };
170
208
  }
171
- const changedEnd = previous.findDiffEnd(next.content);
209
+ const changedEnd = textblock.content.findDiffEnd(proposedParagraph.content);
172
210
  if (changedEnd === null) return null;
173
211
  let from = changedFrom;
174
212
  let oldEnd = changedEnd.a;
@@ -178,8 +216,23 @@ const createCanonicalComposition = (options) => {
178
216
  oldEnd += overlap;
179
217
  newEnd += overlap;
180
218
  }
181
- const before = previous.textBetween(0, previous.size, "", "");
182
- const after = next.content.textBetween(0, next.content.size, "", "");
219
+ let start = paragraphStart;
220
+ let previous = textblock.content;
221
+ let next = proposedParagraph.content;
222
+ for (;;) {
223
+ const held = childAround(previous, from);
224
+ const read = childAround(next, from);
225
+ if (held === void 0 || read === void 0 || held.node.isText || held.node.isLeaf || held.offset !== read.offset || !held.node.sameMarkup(read.node) || from <= held.offset || oldEnd >= held.offset + held.node.nodeSize || newEnd >= read.offset + read.node.nodeSize) break;
226
+ const inner = held.offset + 1;
227
+ start += inner;
228
+ from -= inner;
229
+ oldEnd -= inner;
230
+ newEnd -= inner;
231
+ previous = held.node.content;
232
+ next = read.node.content;
233
+ }
234
+ const before = positionText(previous);
235
+ const after = positionText(next);
183
236
  while (from < oldEnd && from < newEnd && before[from] === after[from]) from++;
184
237
  while (oldEnd > from && newEnd > from && before[oldEnd - 1] === after[newEnd - 1]) {
185
238
  oldEnd--;
@@ -191,7 +244,7 @@ const createCanonicalComposition = (options) => {
191
244
  newEnd++;
192
245
  }
193
246
  const removed = previous.cut(from, oldEnd);
194
- const inserted = next.content.cut(from, newEnd);
247
+ const inserted = next.cut(from, newEnd);
195
248
  const text = inserted.textBetween(0, inserted.size, "", "");
196
249
  if (removed.textBetween(0, removed.size, "", "").length !== removed.size || text.length !== inserted.size) return null;
197
250
  if (!matchesNativeReplacement({