@stll/folio-core 0.75.0 → 0.77.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 (143) hide show
  1. package/dist/ai-edits/headless.d.ts +8 -5
  2. package/dist/ai-edits/headless.js +49 -26
  3. package/dist/ai-edits/pending-suggestions.d.ts +9 -0
  4. package/dist/ai-edits/pending-suggestions.js +13 -3
  5. package/dist/ai-edits/read.js +33 -4
  6. package/dist/ai-edits/table-geometry.js +12 -4
  7. package/dist/ai-edits/types.d.ts +9 -4
  8. package/dist/canonical/batchCommentReferences.js +2 -1
  9. package/dist/canonical/canonicalBatchReview.js +5 -8
  10. package/dist/canonical/canonicalComments.js +8 -2
  11. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  12. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  13. package/dist/canonical/canonicalInlineProjection.d.ts +2 -2
  14. package/dist/canonical/canonicalInlineProjection.js +2 -2
  15. package/dist/canonical/canonicalProjectionBlocks.d.ts +10 -1
  16. package/dist/canonical/canonicalPublicOperations.js +214 -107
  17. package/dist/canonical/canonicalSeedContent.d.ts +18 -3
  18. package/dist/canonical/canonicalSeedContent.js +28 -15
  19. package/dist/canonical/canonicalSession.d.ts +22 -12
  20. package/dist/canonical/canonicalSession.js +181 -187
  21. package/dist/controller/canonicalClipboard.d.ts +3 -2
  22. package/dist/controller/canonicalClipboard.js +377 -58
  23. package/dist/controller/canonicalComposition.js +67 -14
  24. package/dist/controller/canonicalContentControlValue.js +7 -7
  25. package/dist/controller/canonicalReview.d.ts +21 -0
  26. package/dist/controller/canonicalReview.js +44 -9
  27. package/dist/controller/canonicalStoryEditor.js +2 -0
  28. package/dist/controller/canonicalStructure.d.ts +1 -2
  29. package/dist/controller/canonicalStructure.js +51 -24
  30. package/dist/controller/fontReadiness.js +50 -23
  31. package/dist/controller/hiddenEditorManager.js +7 -20
  32. package/dist/docx/bulletMarkers.d.ts +8 -0
  33. package/dist/docx/bulletMarkers.js +9 -1
  34. package/dist/docx/canonicalSessionInput.js +25 -11
  35. package/dist/docx/ensureParaIds.d.ts +31 -0
  36. package/dist/docx/ensureParaIds.js +57 -32
  37. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  38. package/dist/docx/ensureUniqueControlIds.js +47 -29
  39. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  40. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  41. package/dist/docx/importedIdCollisions.js +29 -4
  42. package/dist/docx/server/templatePlan/apply.js +108 -9
  43. package/dist/docx/server/templatePlan/blocks.d.ts +77 -5
  44. package/dist/docx/server/templatePlan/blocks.js +281 -14
  45. package/dist/docx/server/templatePlan/builders.d.ts +22 -1
  46. package/dist/docx/server/templatePlan/builders.js +37 -3
  47. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  48. package/dist/docx/server/templatePlan/effects.js +188 -0
  49. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  50. package/dist/docx/server/templatePlan/emit.js +152 -8
  51. package/dist/docx/server/templatePlan/inspect.js +21 -1
  52. package/dist/docx/server/templatePlan/labels.js +16 -1
  53. package/dist/docx/server/templatePlan/plan.d.ts +35 -3
  54. package/dist/docx/server/templatePlan/plan.js +197 -20
  55. package/dist/docx/server/templatePlan/planShape.js +58 -22
  56. package/dist/docx/server/templatePlan/revisions.d.ts +101 -0
  57. package/dist/docx/server/templatePlan/revisions.js +681 -0
  58. package/dist/docx/server/templatePlan/story.d.ts +61 -2
  59. package/dist/docx/server/templatePlan/story.js +175 -13
  60. package/dist/docx/server/templatePlan/types.d.ts +313 -1
  61. package/dist/docx/server/templatePlan/verify.js +175 -12
  62. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  63. package/dist/docx/server/templatePlan/xml.js +4 -1
  64. package/dist/docx/settingsHeaderFooterUpdate.d.ts +1 -1
  65. package/dist/docx/tableGridXml.d.ts +3 -7
  66. package/dist/docx/tableGridXml.js +5 -13
  67. package/dist/layout-bridge/convert/footnoteLayout.js +34 -8
  68. package/dist/prosemirror/canonicalMarkupDocument.d.ts +20 -0
  69. package/dist/prosemirror/canonicalMarkupDocument.js +73 -0
  70. package/dist/prosemirror/canonicalTableCommands.d.ts +1 -1
  71. package/dist/prosemirror/canonicalTableCommands.js +1 -3
  72. package/dist/prosemirror/commands/comments.d.ts +6 -234
  73. package/dist/prosemirror/commands/comments.js +5 -2464
  74. package/dist/prosemirror/commands/index.d.ts +4 -2
  75. package/dist/prosemirror/commands/index.js +4 -2
  76. package/dist/prosemirror/conversion/markupViewSource.d.ts +17 -0
  77. package/dist/prosemirror/conversion/markupViewSource.js +11 -0
  78. package/dist/prosemirror/conversion/toProseDoc.d.ts +3 -0
  79. package/dist/prosemirror/conversion/toProseDoc.js +31 -14
  80. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  81. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  82. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  83. package/dist/prosemirror/independentMarkupProjection.d.ts +27 -0
  84. package/dist/prosemirror/independentMarkupProjection.js +147 -0
  85. package/dist/prosemirror/markupViewNotes.d.ts +1 -1
  86. package/dist/prosemirror/markupViewNotes.js +24 -27
  87. package/dist/prosemirror/markupViewPositionMap.d.ts +16 -0
  88. package/dist/prosemirror/markupViewPositionMap.js +316 -0
  89. package/dist/prosemirror/markupViewProjection.d.ts +3 -46
  90. package/dist/prosemirror/markupViewProjection.js +90 -17
  91. package/dist/prosemirror/paraIds.d.ts +1 -14
  92. package/dist/prosemirror/paraIds.js +1 -14
  93. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  94. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  95. package/dist/prosemirror/projectionReview.d.ts +49 -0
  96. package/dist/prosemirror/projectionReview.js +292 -0
  97. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  98. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  99. package/dist/prosemirror/replacedAnnotations.d.ts +6 -83
  100. package/dist/prosemirror/replacedAnnotations.js +11 -203
  101. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  102. package/dist/prosemirror/revisionCarriers.js +15 -1
  103. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  104. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  105. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  106. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  107. package/dist/prosemirror/styles/styleResolver.d.ts +1 -0
  108. package/dist/prosemirror/styles/styleResolver.js +4 -1
  109. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  110. package/dist/prosemirror/suggestionQueries.js +320 -0
  111. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  112. package/dist/prosemirror/tableGridMutation.js +1 -78
  113. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  114. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  115. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  116. package/dist/server.d.ts +2 -2
  117. package/dist/types/canonicalCapabilities.d.ts +4 -35
  118. package/dist/types/canonicalCapabilities.js +4 -33
  119. package/package.json +2 -2
  120. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  121. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
  122. package/dist/internal/revisionResolutionEdits.d.ts +0 -11
  123. package/dist/internal/revisionResolutionEdits.js +0 -18
  124. package/dist/internal/revisionResolutionInline.d.ts +0 -24
  125. package/dist/internal/revisionResolutionInline.js +0 -302
  126. package/dist/internal/revisionResolutionStep.d.ts +0 -32
  127. package/dist/internal/revisionResolutionStep.js +0 -282
  128. package/dist/internal/revisionResolutionTracking.d.ts +0 -9
  129. package/dist/internal/revisionResolutionTracking.js +0 -124
  130. package/dist/internal/wholeStoryRevisionResolution.d.ts +0 -56
  131. package/dist/internal/wholeStoryRevisionResolution.js +0 -783
  132. package/dist/prosemirror/commands/resolveAllTableChanges.d.ts +0 -38
  133. package/dist/prosemirror/commands/resolveAllTableChanges.js +0 -642
  134. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.d.ts +0 -13
  135. package/dist/prosemirror/commands/resolveNodePropertyChangeAttrs.js +0 -45
  136. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +0 -18
  137. package/dist/prosemirror/commands/tableCellMergeResolution.js +0 -207
  138. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +0 -60
  139. package/dist/prosemirror/commands/tableMergeFoldDecisions.js +0 -78
  140. package/dist/prosemirror/rejoinRunCarriers.d.ts +0 -42
  141. package/dist/prosemirror/rejoinRunCarriers.js +0 -65
  142. package/dist/prosemirror/runPropertyChangeResolution.d.ts +0 -15
  143. package/dist/prosemirror/runPropertyChangeResolution.js +0 -34
@@ -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";
@@ -9,6 +10,7 @@ import { canonicalSelectionRange } from "../prosemirror/canonicalSelectionRange.
9
10
  import { proseDocToBlocks } from "../prosemirror/conversion/fromProseDoc.js";
10
11
  import { completeNumberingForDoc } from "../prosemirror/listInstanceReferences.js";
11
12
  import { marksToTextFormatting } from "../prosemirror/runFormattingFromMarks.js";
13
+ import { pastedCells } from "../prosemirror/tableCellPaste.js";
12
14
  import { CANONICAL_CONDITION, CANONICAL_GAP } from "../types/canonicalCapabilities.js";
13
15
  import { readModel } from "../types/documentModel.js";
14
16
  import { bytesToDataUrl } from "../utils/base64.js";
@@ -17,7 +19,7 @@ import { flattenClipboardStyleReferences, importClipboardStyles } from "./canoni
17
19
  import { Result, panic } from "better-result";
18
20
  import { NUMBER_FORMATS, paragraphNumberingReference, relationshipIdOf } from "@stll/docx-core/model";
19
21
  import { packageResourcesOpOf } from "@stll/docx-core/ops";
20
- import { CellSelection } from "prosemirror-tables";
22
+ import { CellSelection, tableNodeTypes } from "prosemirror-tables";
21
23
  import { Fragment, Slice } from "prosemirror-model";
22
24
  // src/controller/canonicalClipboard.ts
23
25
  /** A refusal under the gap, rule or condition it belongs to. */
@@ -29,31 +31,182 @@ const refuse = (message, ground) => Result.err(new CanonicalSessionError({
29
31
  /** Clipboard content the paste cannot read or resolve as given. */
30
32
  const INVALID_CLIPBOARD = { condition: CANONICAL_CONDITION.invalidRequest };
31
33
  /**
32
- * The gap a clipboard block the paste cannot place falls under: a table's,
33
- * or for any other block, the story 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.
34
36
  */
35
- const unplacedBlockGround = (slice) => {
36
- let table = false;
37
- slice.content.descendants((node) => {
38
- if (node.type.name === "table") table = true;
39
- return !table;
40
- });
41
- return { gap: table ? CANONICAL_GAP.trackedTableStructure : CANONICAL_GAP.storyContentProjection };
37
+ const UNPLACED_BLOCK = INVALID_CLIPBOARD;
38
+ const tableRole = (node) => node?.type.spec["tableRole"];
39
+ /**
40
+ * A table the clipboard holds part of, opened `left` levels deep at its start
41
+ * and `right` at its end, as the table of the cells it holds: a first or last
42
+ * row cut short keeps the cells copied and is filled out with empty ones.
43
+ * Undefined when the part holds no cells.
44
+ */
45
+ const closedTable = (table, left, right) => {
46
+ if (left <= 1 && right <= 1) return table;
47
+ const cells = pastedCells(new Slice(Fragment.from(table), left, right));
48
+ if (cells === null) return void 0;
49
+ const rowType = tableNodeTypes(table.type.schema).row;
50
+ return table.type.create(table.attrs, cells.rows.map((row, index) => rowType.create(index < table.childCount ? table.child(index).attrs : null, row)), table.marks);
51
+ };
52
+ /**
53
+ * A slice that opens or closes inside a table, its edges closed at the table:
54
+ * it pastes the table of the cells it holds, as a selection of cells pastes.
55
+ * Selected cells, rows or cells without their table, paste as a table
56
+ * of their own. The slice is returned as given when no table edge is open,
57
+ * and undefined when an open table edge holds no cells.
58
+ */
59
+ const withClosedTableEdges = (slice) => {
60
+ const { content } = slice;
61
+ const first = content.firstChild;
62
+ const last = content.lastChild;
63
+ const role = tableRole(first);
64
+ if (role === "row" || role === "cell" || role === "header_cell") {
65
+ if (first === null) return slice;
66
+ const cells = pastedCells(slice);
67
+ if (cells === null) return void 0;
68
+ const { table, row } = tableNodeTypes(first.type.schema);
69
+ return new Slice(Fragment.from(table.create(null, cells.rows.map((cellsOfRow) => row.create(null, cellsOfRow)))), 0, 0);
70
+ }
71
+ const opensTable = slice.openStart > 1 && tableRole(first) === "table";
72
+ const closesTable = slice.openEnd > 1 && tableRole(last) === "table";
73
+ if (!opensTable && !closesTable) return slice;
74
+ const blocks = [];
75
+ content.forEach((node) => blocks.push(node));
76
+ const lastIndex = blocks.length - 1;
77
+ const edges = /* @__PURE__ */ new Set();
78
+ if (opensTable) edges.add(0);
79
+ if (closesTable) edges.add(lastIndex);
80
+ for (const index of edges) {
81
+ const node = blocks[index];
82
+ if (node === void 0) continue;
83
+ const closed = closedTable(node, opensTable && index === 0 ? slice.openStart : 0, closesTable && index === lastIndex ? slice.openEnd : 0);
84
+ if (closed === void 0) return void 0;
85
+ blocks[index] = closed;
86
+ }
87
+ return new Slice(Fragment.from(blocks), opensTable ? 1 : slice.openStart, closesTable ? 1 : slice.openEnd);
88
+ };
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
+ }
42
181
  };
43
182
  /**
44
183
  * A pasted block's paragraphs in document order, a table's cell paragraphs
45
- * among them, each with the place it fills; undefined when a cell holds a
46
- * block other than a paragraph or a table.
184
+ * and a container's among them, each with the place it fills.
47
185
  */
48
186
  const clipboardParagraphs = (block, replace = () => {}) => {
49
187
  if (block.type === "paragraph") return [{
50
188
  paragraph: block,
51
189
  replace
52
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
+ }
53
205
  const places = [];
54
206
  for (const row of block.rows) for (const cell of row.cells) for (const [index, inner] of cell.content.entries()) {
55
- if (inner.type !== "paragraph" && inner.type !== "table") return void 0;
56
- const found = clipboardParagraphs(inner, (next) => {
207
+ const pasted = pastedBlockOf(inner);
208
+ if (pasted === void 0) continue;
209
+ const found = clipboardParagraphs(pasted, (next) => {
57
210
  cell.content[index] = next;
58
211
  });
59
212
  if (found === void 0) return void 0;
@@ -65,8 +218,26 @@ const clipboardParagraphs = (block, replace = () => {}) => {
65
218
  * A table's verbatim captures describe the markup it was read from; a pasted
66
219
  * copy is new content the serializer writes from its model.
67
220
  */
68
- /** Every table among the blocks, those nested in cells included. */
69
- 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. */
70
241
  const withoutTableCaptures = (table) => {
71
242
  if (table.formatting !== void 0) {
72
243
  delete table.formatting.sourceXml;
@@ -74,16 +245,21 @@ const withoutTableCaptures = (table) => {
74
245
  }
75
246
  for (const row of table.rows) {
76
247
  if (row.formatting !== void 0) delete row.formatting.sourceXml;
77
- for (const cell of row.cells) {
78
- if (cell.formatting !== void 0) delete cell.formatting.sourceXml;
79
- for (const inner of cell.content) if (inner.type === "table") withoutTableCaptures(inner);
80
- }
248
+ for (const cell of row.cells) if (cell.formatting !== void 0) delete cell.formatting.sourceXml;
81
249
  }
82
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
+ };
83
258
  /** A pasted block's own copy, each paragraph keeping its indentation provenance. */
84
259
  const cloneClipboardBlock = (block) => {
85
260
  const clone = structuredClone(block);
86
- if (clone.type === "table") withoutTableCaptures(clone);
261
+ withoutContainedTableCaptures([clone]);
262
+ if (clone.type === "blockSdt" || clone.type === "blockCustomXml") withoutBlockMarkers(clone.content);
87
263
  const sources = clipboardParagraphs(block) ?? [];
88
264
  const targets = clipboardParagraphs(clone) ?? [];
89
265
  for (const [index, { paragraph: target }] of targets.entries()) {
@@ -250,10 +426,39 @@ const importNumbering = ({ destination, source, paragraphs, mode, sourceKind, ex
250
426
  });
251
427
  };
252
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
+ /**
253
457
  * The notes and comments the clipboard's references and markers name, read
254
458
  * from the document they were copied from; the paste copies each under a
255
459
  * fresh id. Without that document the ids could name the destination's own
256
- * 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.
257
462
  */
258
463
  const clipboardAnnotations = ({ paragraphs, source }) => {
259
464
  const comments = /* @__PURE__ */ new Set();
@@ -267,39 +472,94 @@ const clipboardAnnotations = ({ paragraphs, source }) => {
267
472
  });
268
473
  }
269
474
  if (comments.size === 0 && notes.size === 0) return Result.ok(void 0);
270
- const refusal = (message) => Result.err(new CanonicalSessionError({
271
- ground: { gap: CANONICAL_GAP.storyContentProjection },
272
- reason: "refused",
273
- message
274
- }));
275
- 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
+ }
276
479
  const annotations = {
277
480
  notes: [...source.package.footnotes ?? [], ...source.package.endnotes ?? []].filter(({ type, id }) => notes.has(`${type}:${String(id)}`)),
278
481
  comments: (source.package.document.comments ?? []).filter(({ id }) => comments.has(id))
279
482
  };
280
- 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);
281
484
  return Result.ok(annotations);
282
485
  };
283
- const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarget, pasteTarget, sourceDocument, moveSource }) => {
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
+ };
540
+ const prepareCanonicalPaste = ({ session, state, slice: copied, plain = false, moveTarget, pasteTarget, sourceDocument, moveSource }) => {
284
541
  if (session.isComposing) return refuse("Composition must finish before using the clipboard.", { condition: CANONICAL_CONDITION.composing });
285
- if (slice.content.size === 0) return Result.err(new CanonicalSessionError({
542
+ if (copied.content.size === 0) return Result.err(new CanonicalSessionError({
286
543
  ground: INVALID_CLIPBOARD,
287
544
  message: "The clipboard contains no content.",
288
545
  reason: "noChange"
289
546
  }));
290
- if (slice.openStart > 1 || slice.openEnd > 1) return refuse("Clipboard tables and nested block containers require canonical table editing.", unplacedBlockGround(slice));
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));
550
+ if (slice === void 0) return refuse("The clipboard table holds no cells.", INVALID_CLIPBOARD);
551
+ if (slice.openStart > 1 || slice.openEnd > 1) return refuse("Clipboard tables and nested block containers require canonical table editing.", UNPLACED_BLOCK);
291
552
  const paragraphType = state.schema.nodes["paragraph"];
292
553
  if (paragraphType === void 0) return refuse("Clipboard input requires a paragraph schema.", { condition: CANONICAL_CONDITION.internal });
293
- const tableType = state.schema.nodes["table"];
294
554
  let inline = true;
295
555
  let blocksOnly = true;
296
556
  slice.content.forEach((node) => {
297
557
  inline &&= node.isInline;
298
- blocksOnly &&= node.type === paragraphType || node.type === tableType;
558
+ blocksOnly &&= node.isBlock;
299
559
  });
300
- if (!inline && !blocksOnly) return refuse("Clipboard tables and embedded blocks require canonical table editing.", unplacedBlockGround(slice));
560
+ if (!inline && !blocksOnly) return refuse("Clipboard tables and embedded blocks require canonical table editing.", UNPLACED_BLOCK);
301
561
  const importedSlice = inline ? new Slice(Fragment.from(paragraphType.create(null, slice.content)), 1, 1) : slice;
302
- const converted = Result.try({
562
+ const convertedBlocks = Result.try({
303
563
  try: () => proseDocToBlocks(state.schema.topNodeType.create(null, importedSlice.content), []),
304
564
  catch: (cause) => new CanonicalSessionError({
305
565
  ground: INVALID_CLIPBOARD,
@@ -307,12 +567,20 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
307
567
  message: `Clipboard normalization failed: ${cause instanceof Error ? cause.message : String(cause)}`
308
568
  })
309
569
  });
310
- if (converted.isErr()) return converted;
570
+ if (convertedBlocks.isErr()) return convertedBlocks;
311
571
  const blocks = [];
312
- for (const block of converted.value) {
313
- if (block.type !== "paragraph" && block.type !== "table" || clipboardParagraphs(block) === void 0) return refuse("The clipboard contains an unsupported block.", unplacedBlockGround(slice));
314
- 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);
315
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
+ }));
316
584
  const places = blocks.flatMap((block, index) => clipboardParagraphs(block, (next) => {
317
585
  blocks[index] = next;
318
586
  }) ?? []);
@@ -355,16 +623,7 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
355
623
  }
356
624
  });
357
625
  const annotationParagraphs = annotationBodies.map(({ paragraph }) => paragraph);
358
- for (const paragraph of annotationParagraphs) {
359
- let related = false;
360
- visitInlineContentSlots(paragraph, ({ item }) => {
361
- if (item.type === "hyperlink" && item.anchor === void 0) related = true;
362
- });
363
- visitParagraphRuns(paragraph, (run) => {
364
- if (run.content.some((child) => child.type === "drawing")) related = true;
365
- });
366
- if (related) return refuse("Copied notes and comments holding images or external links require their part's relationships.", { gap: CANONICAL_GAP.storyContentProjection });
367
- }
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 });
368
627
  const destination = readModel(session.document);
369
628
  let styles = destination.package.styles;
370
629
  let styleIds;
@@ -425,8 +684,9 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
425
684
  let importedResource = false;
426
685
  let imageIndex = 1;
427
686
  let relationshipIndex = 1;
687
+ let sourceRelationships = sourceDocument?.package.relationships;
428
688
  const importExternalLink = (href, previousId) => {
429
- const source = previousId === void 0 ? void 0 : sourceDocument?.package.relationships?.get(previousId);
689
+ const source = previousId === void 0 ? void 0 : sourceRelationships?.get(previousId);
430
690
  let target = href;
431
691
  if (target === void 0 || target.length === 0) target = source?.targetMode === "External" ? source.target : void 0;
432
692
  if (target === void 0 || target.length === 0) return refuse("The clipboard hyperlink has no resolved target.", INVALID_CLIPBOARD);
@@ -478,7 +738,9 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
478
738
  if (imported.isErr()) return imported;
479
739
  return Result.ok((parsed.value.elements ?? []).map(captureVerbatimXml).join(""));
480
740
  };
481
- 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) => {
482
744
  if (moveTarget === void 0) {
483
745
  const links = [];
484
746
  visitInlineContentSlots(paragraph, ({ item }) => {
@@ -499,9 +761,14 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
499
761
  visitParagraphRuns(paragraph, (run) => runs.push(run));
500
762
  for (const item of runs) {
501
763
  if (plain) item.formatting = marksToTextFormatting(state.storedMarks ?? state.doc.resolve(pasteTarget ?? moveSource?.from ?? selectionRange.from).marks());
502
- for (const child of item.content) {
764
+ for (const [index, child] of item.content.entries()) {
503
765
  if (child.type !== "drawing") continue;
504
- 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
+ }
505
772
  delete child.rawXml;
506
773
  delete child.rawImageFingerprint;
507
774
  const image = child.image;
@@ -532,11 +799,12 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
532
799
  if (rebound.isErr()) return rebound;
533
800
  image.hlinkHoverXml = rebound.value;
534
801
  }
802
+ if (moved !== void 0 && image.rId !== void 0 && moved.relationshipIds.has(image.rId)) continue;
535
803
  const relationship = image.rId === void 0 ? void 0 : relationships.get(image.rId);
536
804
  const ownedPath = relationship?.target.startsWith("/") ? relationship.target.slice(1) : `word/${relationship?.target ?? ""}`;
537
- const ownedMedia = relationship === void 0 ? void 0 : media.get(ownedPath);
805
+ const ownedMedia = relationship === void 0 || sourceRelationships === void 0 ? void 0 : media.get(ownedPath);
538
806
  if (ownedMedia !== void 0 && (moveTarget !== void 0 || image.src !== void 0 && ownedMedia.dataUrl === image.src)) continue;
539
- 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);
540
808
  const sourcePath = sourceRelationship?.target.startsWith("/") ? sourceRelationship.target.slice(1) : `word/${sourceRelationship?.target ?? ""}`;
541
809
  const sourceMedia = sourceDocument?.package.media?.get(sourcePath);
542
810
  if (sourceMedia !== void 0 && sourceMedia.data.byteLength > MAX_CLIPBOARD_IMAGE_BYTES) return refuse("The clipboard image exceeds the import size limit.", INVALID_CLIPBOARD);
@@ -588,6 +856,51 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
588
856
  importedResource = true;
589
857
  }
590
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;
591
904
  }
592
905
  const resourceOps = [];
593
906
  if (importedResource || numbering !== destination.package.numbering || styles !== destination.package.styles) {
@@ -651,17 +964,23 @@ const prepareCanonicalPaste = ({ session, state, slice, plain = false, moveTarge
651
964
  resourceOps,
652
965
  semantic: "paste"
653
966
  });
654
- if (topParagraphs.length !== blocks.length) return refuse("Moving a table by dragging requires a table move operation.", { gap: CANONICAL_GAP.trackedTableStructure });
655
967
  const target = session.projection.addressAt(moveTarget);
656
968
  if (target.isErr()) return target;
657
969
  return session.prepareIntents(state, {
658
- intents: [{
970
+ intents: [topParagraphs.length === blocks.length ? {
659
971
  type: "moveFragment",
660
972
  target: target.value,
661
973
  ...range,
662
974
  paragraphs: topParagraphs,
663
975
  openStart,
664
976
  openEnd
977
+ } : {
978
+ type: "moveBlocks",
979
+ target: target.value,
980
+ ...range,
981
+ blocks,
982
+ openStart,
983
+ openEnd
665
984
  }],
666
985
  resourceOps,
667
986
  semantic: "paste"