@stll/docx-core 0.47.0 → 0.48.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.
@@ -1,5 +1,5 @@
1
- import { N as PARAGRAPH_ALIGNMENTS, X as preservedChildGap, at as isNumberingReference, c as MAX_REVISION_ID, d as REVIEW_CARRIERS, kt as getSingularRunPropertyChange, lt as paragraphNumberingReference, nt as isNumberingLevel, o as HELD_PARAGRAPH_JOINS, s as INSERTION_SEAM_POLICIES, t as COMMENT_PART_RELATIONSHIPS, vt as finalizeParagraphFormatting, xt as setDocumentBodyComments } from "../document-BuoCvTcR.js";
2
- import { a as preservedCommentRangeMarkersAt, i as preservedCommentRangeMarker, n as sanitizeExternalUrl, o as withPreservedCommentRangeId, s as maxOf, t as itemBefore } from "../listItems-bPpOKnLB.js";
1
+ import { At as gridColumnsInRows, N as PARAGRAPH_ALIGNMENTS, X as preservedChildGap, at as isNumberingReference, c as MAX_REVISION_ID, d as REVIEW_CARRIERS, jt as getSingularRunPropertyChange, kt as MAX_TABLE_GRID_COLUMNS, lt as paragraphNumberingReference, nt as isNumberingLevel, o as HELD_PARAGRAPH_JOINS, s as INSERTION_SEAM_POLICIES, t as COMMENT_PART_RELATIONSHIPS, vt as finalizeParagraphFormatting, xt as setDocumentBodyComments } from "../document-d_O4GWz3.js";
2
+ import { a as preservedCommentRangeMarkersAt, i as preservedCommentRangeMarker, n as sanitizeExternalUrl, o as withPreservedCommentRangeId, s as maxOf, t as itemBefore } from "../listItems-BM4hecVF.js";
3
3
  import { g as hasIllegalXmlCharacters } from "../streamingXmlParser-BqnCIEZd.js";
4
4
  import { Result, TaggedError, panic } from "better-result";
5
5
  import { encodeUtf8 } from "@stll/utf8-boundaries";
@@ -1382,6 +1382,35 @@ const withFieldResult = (field, result) => field.type === "simpleField" ? {
1382
1382
  * this, not {@link childNodes}, which keeps a field one unit.
1383
1383
  */
1384
1384
  const nestedRecords = (node) => childNodes(node) ?? fieldResultOf(node);
1385
+ const FIELD_HELD_CHANGE_TYPES = /* @__PURE__ */ new Set([
1386
+ "insertion",
1387
+ "deletion",
1388
+ "moveFrom",
1389
+ "moveTo"
1390
+ ]);
1391
+ const isFieldHeldChange = (node) => FIELD_HELD_CHANGE_TYPES.has(node.type);
1392
+ /**
1393
+ * The ids of the tracked changes a field's result holds at any depth:
1394
+ * `CT_SimpleField` is `EG_PContent`, so `w:fldSimple` may hold `w:ins`,
1395
+ * `w:del`, `w:moveFrom` and `w:moveTo` around the runs that show it. Only a
1396
+ * change whose content the field can hold in its place is listed: resolving
1397
+ * one keeps or drops its content where it stood, inside the field's one
1398
+ * unit, so no offset or seam outside the field moves. A complex field's
1399
+ * result holds runs alone; one whose result carries a change is read as its
1400
+ * field characters, which stand in the paragraph.
1401
+ */
1402
+ const fieldHeldChangeIds = (node) => {
1403
+ const out = [];
1404
+ const holdable = (nodes) => nodes.every(isSimpleFieldContent);
1405
+ const visit = (nodes) => {
1406
+ for (const child of nodes) {
1407
+ if (isFieldHeldChange(child) && holdable(child.content)) out.push(child.info.id);
1408
+ visit(childNodes(child) ?? []);
1409
+ }
1410
+ };
1411
+ visit(fieldResultOf(node) ?? []);
1412
+ return out;
1413
+ };
1385
1414
  /** The same record holding other {@link nestedRecords}. */
1386
1415
  const withNestedRecords = (node, children) => node.type === "simpleField" || node.type === "complexField" ? withFieldResult(node, children) : rebuildNode(node, children);
1387
1416
  /**
@@ -2087,8 +2116,10 @@ const DOCUMENT_OP_REFUSAL_REASONS = Object.freeze({
2087
2116
  INSIDE_INLINE_CONTROL: "insideInlineControl",
2088
2117
  /**
2089
2118
  * No tracked change can record the edit, or no resolution op can carry it
2090
- * out yet: comment boundaries in a tracked range, the paragraph mark's run
2091
- * properties, a join at a section break, a record inside a field.
2119
+ * out yet: the paragraph mark's run properties, a deleted paragraph whose
2120
+ * hyperlink or content control holds a comment anchor, a section-ending
2121
+ * mark resolved across a standing range boundary, a change inside a
2122
+ * simple field holding content the field cannot hold.
2092
2123
  */
2093
2124
  UNTRACKABLE: "untrackable",
2094
2125
  /** A second tracked column insertion beside a pending grid change. */
@@ -3483,11 +3514,11 @@ const restoreCommentBoundaries = (document, boundaries) => {
3483
3514
  };
3484
3515
  // src/ops/blockListCheck.ts
3485
3516
  /**
3486
- * Whether a block list or a container in it holds what `paragraph` looks for,
3517
+ * Whether a block list or a container in it holds what the checks look for,
3487
3518
  * reusing unchanged lists: operation documents and their block lists are
3488
3519
  * immutable once validated.
3489
3520
  */
3490
- const blockListCheck = ({ paragraph, cell }) => {
3521
+ const blockListCheck = ({ paragraph, table, cell }) => {
3491
3522
  const checked = /* @__PURE__ */ new WeakMap();
3492
3523
  const holds = (blocks) => {
3493
3524
  const key = listKey(blocks);
@@ -3497,7 +3528,7 @@ const blockListCheck = ({ paragraph, cell }) => {
3497
3528
  const found = (splice !== void 0 && checked.get(splice.previous) === false ? blocks.slice(splice.start, splice.end) : blocks).some((block) => {
3498
3529
  switch (block.type) {
3499
3530
  case "paragraph": return paragraph(block);
3500
- case "table": return block.rows.some((row) => row.cells.some(({ content }) => (cell ?? holds)(content)));
3531
+ case "table": return table?.(block) === true || block.rows.some((row) => row.cells.some(({ content }) => (cell ?? holds)(content)));
3501
3532
  case "blockSdt":
3502
3533
  case "blockCustomXml": return holds(block.content);
3503
3534
  case "preservedBlock":
@@ -4285,6 +4316,8 @@ const spanningAction = (node, kind, stamp) => {
4285
4316
  if (isRemovedRevisionNode(node)) return kind === WRAP_KINDS.DELETION ? "keep" : "refuse";
4286
4317
  return "cut";
4287
4318
  };
4319
+ /** Whether the wrap takes this comment reference in ({@link WrapOptions.takenReferences}). */
4320
+ const takesReference = (node, state) => node.type === "commentReference" && state.commentAnchorsStand && state.takenReferences.has(node.id);
4288
4321
  /** Whether a record holds a comment anchor at any depth. */
4289
4322
  const holdsCommentAnchor = (node) => (childNodes(node) ?? []).some((child) => isCommentAnchor(child) || holdsCommentAnchor(child));
4290
4323
  /**
@@ -4303,7 +4336,10 @@ const holdsCommentAnchor = (node) => (childNodes(node) ?? []).some((child) => is
4303
4336
  * boundary it held.
4304
4337
  */
4305
4338
  const coveredAction = (node, state) => {
4306
- if (isCommentAnchor(node)) return state.commentAnchorsStand ? "skip" : "refuse";
4339
+ if (isCommentAnchor(node)) {
4340
+ if (takesReference(node, state)) return "wrap";
4341
+ return state.commentAnchorsStand ? "skip" : "refuse";
4342
+ }
4307
4343
  if (state.kind === WRAP_KINDS.DELETION) {
4308
4344
  if (isRemovedRevisionNode(node)) return "skip";
4309
4345
  if (isAddedRevision(node)) return "descend";
@@ -4413,7 +4449,7 @@ const mergeWithStampedNeighbour = (out, index, state) => {
4413
4449
  const trackedContent$1 = (nodes, state) => {
4414
4450
  const out = [];
4415
4451
  for (const node of nodes) {
4416
- if (!isParagraphContent(node) || !isTrackedChild(node) || node.type === "commentReference") {
4452
+ if (!isParagraphContent(node) || !isTrackedChild(node) || node.type === "commentReference" && !takesReference(node, state)) {
4417
4453
  state.refusal = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE;
4418
4454
  return;
4419
4455
  }
@@ -4610,7 +4646,7 @@ const wrapList = (nodes, cursor, state) => {
4610
4646
  * `unchanged` when there is nothing to record: every leaf is already
4611
4647
  * deleted, or an insertion sits inside a wrapper carrying the same stamp.
4612
4648
  */
4613
- const wrapTracked = ({ items, from, to, kind, stamp, resolutionJoin, startJoin = 0, acceptance, copiedBoundaries, commentAnchors }) => {
4649
+ const wrapTracked = ({ items, from, to, kind, stamp, resolutionJoin, startJoin = 0, acceptance, copiedBoundaries, commentAnchors, takenReferences = /* @__PURE__ */ new Set() }) => {
4614
4650
  const state = {
4615
4651
  gaps: [from, to],
4616
4652
  resolutionJoin,
@@ -4625,7 +4661,8 @@ const wrapTracked = ({ items, from, to, kind, stamp, resolutionJoin, startJoin =
4625
4661
  recorded: false,
4626
4662
  recordedContent: false,
4627
4663
  refusal: void 0,
4628
- commentAnchorsStand: commentAnchors === "stand"
4664
+ commentAnchorsStand: commentAnchors === "stand",
4665
+ takenReferences
4629
4666
  };
4630
4667
  const content = wrapList(items, startCursor(), state);
4631
4668
  if (content === void 0) return {
@@ -5959,6 +5996,7 @@ const removedNoteStories = (before, after) => {
5959
5996
  * - no revision id (tracked changes, property changes) or content-control id
5960
5997
  * repeats, so the one record carrying an id is the one it names;
5961
5998
  * - the body's section view says what its blocks say;
5999
+ * - table grids and their snapshots fit the supported model width;
5962
6000
  * - each editable story holds no empty run, text node, or revision wrapper.
5963
6001
  *
5964
6002
  * Headers, footers and notes are independently addressable stories. Text-box
@@ -5973,6 +6011,10 @@ const DocumentOpsContractErrorBase = TaggedError("DocumentOpsContractError");
5973
6011
  var DocumentOpsContractError = class extends DocumentOpsContractErrorBase {};
5974
6012
  const holdsEmptyRecord$1 = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord$1(childNodes(node) ?? []));
5975
6013
  const blocksHaveMultiplePropertyChanges = blockListCheck({ paragraph: ({ propertyChanges }) => (propertyChanges?.length ?? 0) > 1 });
6014
+ const blocksHaveOversizedTableGrid = blockListCheck({
6015
+ paragraph: () => false,
6016
+ table: ({ rows, columnWidths, formatting }) => gridColumnsInRows(rows) > 4096 || (columnWidths?.length ?? 0) > 4096 || (formatting?.gridChange?.columnWidths?.length ?? 0) > 4096
6017
+ });
5976
6018
  /** Check every editable story and nested block container, reusing unchanged lists. */
5977
6019
  const hasMultipleParagraphPropertyChanges = (document, boxes = []) => [...documentStories(document), ...boxes].some((story) => blocksHaveMultiplePropertyChanges(storyBody$1(document, story).content));
5978
6020
  /**
@@ -5994,6 +6036,10 @@ const violation = (document) => {
5994
6036
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
5995
6037
  message: "A paragraph cannot carry more than one property change."
5996
6038
  });
6039
+ if (documentStories(document).some((story) => blocksHaveOversizedTableGrid(storyBody$1(document, story).content))) return new DocumentOpsContractError({
6040
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6041
+ message: `A table grid can hold at most ${MAX_TABLE_GRID_COLUMNS} columns.`
6042
+ });
5997
6043
  const body = document.package.document;
5998
6044
  const paragraphs = documentStories(document).flatMap((story) => storyParagraphs(storyBody$1(document, story)));
5999
6045
  if (paragraphs.some(({ paragraph }) => paragraph.paraId === void 0)) return new DocumentOpsContractError({
@@ -8984,10 +9030,6 @@ const recordedOnlyBy = (value, owner) => {
8984
9030
  * document.
8985
9031
  */
8986
9032
  const deletedContent = (paragraph, stamp, rangedComments) => {
8987
- if (!liveReferencesAreRanged(paragraph.content, rangedComments)) return {
8988
- kind: "refused",
8989
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE
8990
- };
8991
9033
  const wrapped = wrapTracked({
8992
9034
  items: paragraph.content,
8993
9035
  from: {
@@ -9000,7 +9042,8 @@ const deletedContent = (paragraph, stamp, rangedComments) => {
9000
9042
  },
9001
9043
  kind: WRAP_KINDS.DELETION,
9002
9044
  stamp,
9003
- commentAnchors: "stand"
9045
+ commentAnchors: "stand",
9046
+ takenReferences: pointReferenceIds(paragraph.content, rangedComments)
9004
9047
  });
9005
9048
  if (wrapped.kind === "refused") return wrapped;
9006
9049
  if (wrapped.kind === "unchanged") return {
@@ -9093,15 +9136,21 @@ const takenOverBreakRecords = ({ broken, paragraphs, owner, held }) => {
9093
9136
  */
9094
9137
  const holdsRangeBoundary = (nodes, held = /* @__PURE__ */ new Set()) => nodes.some((node) => isBoundary(node) && !isHeldAnchor(node, held) || holdsRangeBoundary(childNodes(node) ?? [], held));
9095
9138
  /**
9096
- * Every comment reference in `nodes` outside a removal already pending
9097
- * belongs to a comment with a range (`rangedComments`); one inside such a
9098
- * removal goes with it either way.
9139
+ * The ids of the comment references in `nodes` whose comment has no range
9140
+ * (`rangedComments` names those that do): a point comment, whose reference
9141
+ * is its only anchor.
9099
9142
  */
9100
- const liveReferencesAreRanged = (nodes, rangedComments) => nodes.every((node) => {
9101
- if (isRemovedRevisionNode(node)) return true;
9102
- if (node.type === "commentReference") return rangedComments.has(node.id);
9103
- return liveReferencesAreRanged(childNodes(node) ?? [], rangedComments);
9104
- });
9143
+ const pointReferenceIds = (nodes, rangedComments) => {
9144
+ const ids = /* @__PURE__ */ new Set();
9145
+ const visit = (items) => {
9146
+ for (const node of items) {
9147
+ if (node.type === "commentReference" && !rangedComments.has(node.id)) ids.add(node.id);
9148
+ visit(childNodes(node) ?? []);
9149
+ }
9150
+ };
9151
+ visit(nodes);
9152
+ return ids;
9153
+ };
9105
9154
  /** The ids of the comments whose range ends somewhere in `value`. */
9106
9155
  const rangeEndIdsIn = (value, ids = /* @__PURE__ */ new Set()) => {
9107
9156
  if (Array.isArray(value)) {
@@ -14079,6 +14128,54 @@ const edgeChainPastRemoved = (chain, index, edge) => {
14079
14128
  return [...chain.slice(0, index), ...edgeChain(next, edge)];
14080
14129
  };
14081
14130
  // src/ops/positionedMarkers.ts
14131
+ const carriers = (item) => item?.carrierStack ?? (item?.contentControls ?? []).map((properties) => ({
14132
+ type: "sdt",
14133
+ properties
14134
+ }));
14135
+ const sameCarrier = (left, right) => left.type === "customXml" ? right.type === "customXml" && left.wrapper.id === right.wrapper.id : right.type === "sdt" && structurallyEqual(left.properties, right.properties);
14136
+ const sharedDepth = (left, right) => {
14137
+ let depth = 0;
14138
+ for (const [index, carrier] of left.entries()) {
14139
+ const peer = right[index];
14140
+ if (peer === void 0 || !sameCarrier(carrier, peer)) break;
14141
+ depth += 1;
14142
+ }
14143
+ return depth;
14144
+ };
14145
+ /** A new sibling between two members of one wrapper stays inside it. */
14146
+ const inheritCarriers = (siblings, origins) => {
14147
+ if (!origins.includes(null)) return siblings;
14148
+ let changed = false;
14149
+ const next = [...siblings];
14150
+ for (let start = 0; start < siblings.length; start++) {
14151
+ if (origins[start] !== null) continue;
14152
+ const left = carriers(siblings[start - 1]);
14153
+ let end = start + 1;
14154
+ while (origins[end] === null) end += 1;
14155
+ const right = carriers(siblings[end]);
14156
+ const depth = sharedDepth(left, right);
14157
+ if (depth > 0) {
14158
+ const inherited = left.slice(0, depth);
14159
+ for (let index = start; index < end; index++) {
14160
+ const sibling = siblings[index];
14161
+ if (sibling === void 0) continue;
14162
+ const existing = carriers(sibling);
14163
+ const shared = sharedDepth(inherited, existing);
14164
+ if (shared === inherited.length) continue;
14165
+ const carrierStack = [...inherited, ...existing.slice(shared)];
14166
+ const contentControls = carrierStack.flatMap((carrier) => carrier.type === "sdt" ? [carrier.properties] : []);
14167
+ changed = true;
14168
+ next[index] = {
14169
+ ...sibling,
14170
+ ...contentControls.length === 0 ? {} : { contentControls },
14171
+ ...sibling.carrierStack === void 0 && siblings[start - 1]?.carrierStack === void 0 && siblings[end]?.carrierStack === void 0 ? {} : { carrierStack }
14172
+ };
14173
+ }
14174
+ }
14175
+ start = end - 1;
14176
+ }
14177
+ return changed ? next : siblings;
14178
+ };
14082
14179
  /**
14083
14180
  * For each sibling after an edit, the index of the sibling before it that it
14084
14181
  * continues, or `null` for a new one. A sibling continues the latest one
@@ -14097,51 +14194,102 @@ const originsOf = (before, after) => {
14097
14194
  return origin;
14098
14195
  });
14099
14196
  };
14197
+ const beforeFollowingSibling = (index, origins) => {
14198
+ const following = origins.findIndex((origin) => origin !== null && origin >= index);
14199
+ return following === -1 ? origins.length : following;
14200
+ };
14201
+ /** Keep positioned children beside siblings that share their wrapper. */
14202
+ const relocatedIndex = (item, { origins, siblings }, sticksLeft) => {
14203
+ const { index } = item;
14204
+ const right = beforeFollowingSibling(index, origins);
14205
+ const left = origins.findLastIndex((origin) => origin !== null && origin < index) + 1;
14206
+ if (left === right) return left;
14207
+ const wrapper = carriers(item);
14208
+ if (wrapper.length > 0) {
14209
+ const leftDepth = sharedDepth(wrapper, carriers(siblings[left - 1]));
14210
+ const rightDepth = sharedDepth(wrapper, carriers(siblings[right]));
14211
+ if (leftDepth !== rightDepth) return leftDepth > rightDepth ? left : right;
14212
+ }
14213
+ return sticksLeft ? left : right;
14214
+ };
14100
14215
  /** `markers`, indexed among the siblings `origins` describes. */
14101
- const relocated = (markers, origins) => markers.map((positioned) => {
14102
- const { index } = positioned;
14103
- let next;
14104
- if (positioned.marker.type === "bookmarkStart") {
14105
- const following = origins.findIndex((origin) => origin !== null && origin >= index);
14106
- next = following === -1 ? origins.length : following;
14107
- } else next = origins.findLastIndex((origin) => origin !== null && origin < index) + 1;
14108
- return next === index ? positioned : {
14109
- ...positioned,
14110
- index: next
14111
- };
14112
- });
14113
- const sameIndices = (markers, next) => markers.every((marker, index) => marker === next[index]);
14216
+ const relocated = (markers, destinations) => {
14217
+ let changed = false;
14218
+ const nextMarkers = markers.map((positioned) => {
14219
+ const next = relocatedIndex(positioned, destinations, positioned.marker.type === "bookmarkEnd");
14220
+ if (next === positioned.index) return positioned;
14221
+ changed = true;
14222
+ return {
14223
+ ...positioned,
14224
+ index: next
14225
+ };
14226
+ });
14227
+ return changed ? nextMarkers : markers;
14228
+ };
14229
+ /** Preserve a captured child's gap before the next surviving sibling. */
14230
+ const relocateCaptured = (preserved, destinations) => {
14231
+ if (preserved.children === void 0) return preserved;
14232
+ let changed = false;
14233
+ const children = preserved.children.map((child) => {
14234
+ const index = relocatedIndex(child, destinations, false);
14235
+ if (index === child.index) return child;
14236
+ changed = true;
14237
+ return {
14238
+ ...child,
14239
+ index
14240
+ };
14241
+ });
14242
+ return changed ? {
14243
+ ...preserved,
14244
+ children
14245
+ } : preserved;
14246
+ };
14114
14247
  /**
14115
- * `after`, the table an edit made of `before`, with the markers `before`
14116
- * holds beside its rows, and those each continuing row holds beside its
14117
- * cells, moved to where the edit leaves them.
14248
+ * `after`, with its bookmark markers and captured XML moved to the gaps
14249
+ * where the edit leaves them beside table rows and row cells.
14118
14250
  */
14119
14251
  const relocatePositionedMarkers = (before, after) => {
14120
14252
  const rowOrigins = originsOf(before.rows, after.rows);
14121
- let rowsChanged = false;
14122
- const rows = after.rows.map((row, index) => {
14253
+ const wrappedRows = inheritCarriers(after.rows, rowOrigins);
14254
+ let rowsChanged = wrappedRows !== after.rows;
14255
+ const rows = [...wrappedRows];
14256
+ for (const [index, row] of wrappedRows.entries()) {
14123
14257
  const origin = rowOrigins[index] ?? null;
14124
14258
  const source = origin === null ? void 0 : before.rows[origin];
14125
- if (row.bookmarks === void 0 || source === void 0) return row;
14126
- const markers = relocated(row.bookmarks, originsOf(source.cells, row.cells));
14127
- if (sameIndices(row.bookmarks, markers)) return row;
14259
+ if (source === void 0 || row.bookmarks === void 0 && row.preserved === void 0 && !row.cells.some((cell) => cell.contentControls !== void 0 || cell.carrierStack !== void 0)) continue;
14260
+ const cellOrigins = originsOf(source.cells, row.cells);
14261
+ const cells = inheritCarriers(row.cells, cellOrigins);
14262
+ const destinations = {
14263
+ origins: cellOrigins,
14264
+ siblings: cells
14265
+ };
14266
+ const markers = row.bookmarks !== void 0 && structurallyEqual(row.bookmarks, source.bookmarks) ? relocated(row.bookmarks, destinations) : row.bookmarks;
14267
+ const preserved = row.preserved !== void 0 && structurallyEqual(row.preserved, source.preserved) ? relocateCaptured(row.preserved, destinations) : row.preserved;
14268
+ if (preserved === row.preserved && markers === row.bookmarks && cells === row.cells) continue;
14128
14269
  rowsChanged = true;
14129
- return {
14270
+ rows[index] = {
14130
14271
  ...row,
14131
- bookmarks: markers
14272
+ cells,
14273
+ ...markers === void 0 ? {} : { bookmarks: markers },
14274
+ ...preserved === void 0 ? {} : { preserved }
14132
14275
  };
14133
- });
14134
- const tableMarkers = after.bookmarks === void 0 ? void 0 : relocated(after.bookmarks, rowOrigins);
14135
- const tableChanged = after.bookmarks !== void 0 && tableMarkers !== void 0 && !sameIndices(after.bookmarks, tableMarkers);
14136
- if (!rowsChanged && !tableChanged) return after;
14276
+ }
14277
+ const destinations = {
14278
+ origins: rowOrigins,
14279
+ siblings: rows
14280
+ };
14281
+ const tableMarkers = after.bookmarks === void 0 ? void 0 : relocated(after.bookmarks, destinations);
14282
+ const preserved = after.preserved === void 0 ? void 0 : relocateCaptured(after.preserved, destinations);
14283
+ if (!rowsChanged && tableMarkers === after.bookmarks && preserved === after.preserved) return after;
14137
14284
  return {
14138
14285
  ...after,
14139
14286
  rows,
14140
- ...tableMarkers === void 0 ? {} : { bookmarks: tableMarkers }
14287
+ ...tableMarkers === void 0 ? {} : { bookmarks: tableMarkers },
14288
+ ...preserved === void 0 ? {} : { preserved }
14141
14289
  };
14142
14290
  };
14143
- /** Whether `table` holds a marker beside its rows or beside a row's cells. */
14144
- const holdsPositionedMarkers = (table) => table.bookmarks !== void 0 || table.rows.some((row) => row.bookmarks !== void 0);
14291
+ /** Whether the inverse needs the original row and cell gaps. */
14292
+ const holdsPositionedMarkup = (table) => table.preserved?.children !== void 0 || table.bookmarks !== void 0 || table.rows.some((row) => row.bookmarks !== void 0 || row.preserved?.children !== void 0 || row.contentControls !== void 0 || row.carrierStack !== void 0 || row.cells.some((cell) => cell.contentControls !== void 0 || cell.carrierStack !== void 0));
14145
14293
  // src/model/tableCellVerticalMerge.ts
14146
14294
  const TABLE_CELL_VERTICAL_MERGES = {
14147
14295
  NONE: "none",
@@ -14202,7 +14350,7 @@ const tableGrid = (table, opType) => {
14202
14350
  for (const cell of cells) previous.set(cell.start, cell);
14203
14351
  }
14204
14352
  const width = maxOf(covered, table.columnWidths?.length ?? 0);
14205
- if (width === 0) return refuse();
14353
+ if (width === 0 || width > 4096) return refuse();
14206
14354
  const stated = covered.every((columns) => columns === width) && (table.columnWidths === void 0 || table.columnWidths.length === width);
14207
14355
  return Result.ok({
14208
14356
  width,
@@ -14321,25 +14469,27 @@ const withMergesEnded = (table, rowIndex) => {
14321
14469
  };
14322
14470
  };
14323
14471
  const BOUNDARIES = rangeBoundaryDefinitions();
14324
- /** Every range boundary in `value`, at any depth, in source order. */
14472
+ /** Every range boundary and comment reference in `value`, at any depth, in source order. */
14325
14473
  const boundariesIn = (value, out = []) => {
14326
14474
  if (typeof value !== "object" || value === null) return out;
14327
14475
  const type = Reflect.get(value, "type");
14328
- if (typeof type === "string" && Object.hasOwn(BOUNDARIES, type)) out.push(value);
14476
+ if (typeof type === "string" && (Object.hasOwn(BOUNDARIES, type) || type === "commentReference")) out.push(value);
14329
14477
  else for (const field of Object.values(value)) boundariesIn(field, out);
14330
14478
  return out;
14331
14479
  };
14332
14480
  /**
14333
14481
  * The range boundaries in `removed`, other than those `kept` still holds,
14334
14482
  * whose other end stands outside it. Removed content takes its words, not
14335
- * the end of a range reaching past it: these ends stay where it was. A range
14336
- * wholly inside goes with it.
14483
+ * the end of a range reaching past it: these ends stay where it was, and a
14484
+ * comment's reference stays beside its range's end. A range wholly inside
14485
+ * goes with it.
14337
14486
  */
14338
14487
  const rangeEndsReachingPast = (removed, kept) => {
14339
14488
  const keeps = new Set(boundariesIn(kept));
14340
- const key = (node) => `${BOUNDARIES[node.type].family}:${node.id}`;
14341
14489
  const lost = boundariesIn(removed).filter((node) => !keeps.has(node));
14342
- return lost.filter((node) => lost.filter((other) => key(other) === key(node)).length === 1);
14490
+ const key = ({ type, id }) => type === "commentReference" ? "" : `${BOUNDARIES[type].family}:${id}`;
14491
+ const reaching = lost.filter((node) => key(node) !== "" && lost.filter((other) => key(other) === key(node)).length === 1);
14492
+ return lost.filter((node) => reaching.includes(node) || node.type === "commentReference" && reaching.some(({ type, id }) => type === "commentRangeEnd" && id === node.id));
14343
14493
  };
14344
14494
  /**
14345
14495
  * `rows` with the ends of ranges reaching past the removed row
@@ -14390,10 +14540,72 @@ const rowsWithoutRow = (table, rowIndex) => {
14390
14540
  const removed = table.rows[rowIndex];
14391
14541
  return removed === void 0 ? rows : withRangeEndsKept(removed, rows, rowIndex);
14392
14542
  };
14543
+ const VERTICAL = TABLE_CELL_VERTICAL_MERGES;
14544
+ const spansOf = (row) => {
14545
+ let at = row?.formatting?.gridBefore ?? 0;
14546
+ return (row?.cells ?? []).map((cell) => {
14547
+ const start = at;
14548
+ at += cell.formatting?.gridSpan ?? 1;
14549
+ return {
14550
+ cell,
14551
+ key: `${start}:${at}`
14552
+ };
14553
+ });
14554
+ };
14555
+ const withVerticalMerge = (cell, vMerge) => {
14556
+ const { vMerge: _vMerge, sourceXml: _sourceXml, ...formatting } = cell.formatting ?? {};
14557
+ if (vMerge !== void 0) return {
14558
+ ...cell,
14559
+ formatting: {
14560
+ ...formatting,
14561
+ vMerge
14562
+ }
14563
+ };
14564
+ if (Object.keys(formatting).length > 0) return {
14565
+ ...cell,
14566
+ formatting
14567
+ };
14568
+ const { formatting: _formatting, ...plain } = cell;
14569
+ return plain;
14570
+ };
14571
+ /**
14572
+ * The table's rows with `row` put in at `at`, its vertical merges matched to
14573
+ * the rows it lands between, which the batch may have changed since the row
14574
+ * was built. A cell under a merge the row below continues continues it too; a
14575
+ * continuation goes on a merge of its span above, making the cell above start
14576
+ * one when the removal of the merge's last row ended it; with no cell of its
14577
+ * span above, it is a cell of its own.
14578
+ */
14579
+ const rowsWithRow = (rows, at, row) => {
14580
+ const above = spansOf(rows[at - 1]);
14581
+ const below = spansOf(rows[at]);
14582
+ const restarted = /* @__PURE__ */ new Set();
14583
+ const cells = spansOf(row).map(({ cell, key }) => {
14584
+ const over = above.find((entry) => entry.key === key)?.cell;
14585
+ const merge = tableCellVerticalMerge(cell.formatting?.vMerge);
14586
+ if (over !== void 0 && below.some((entry) => entry.key === key && tableCellVerticalMerge(entry.cell.formatting?.vMerge) === VERTICAL.CONTINUE)) return withVerticalMerge(cell, VERTICAL.CONTINUE);
14587
+ if (merge !== VERTICAL.CONTINUE) return cell;
14588
+ if (over === void 0) return withVerticalMerge(cell, void 0);
14589
+ if (tableCellVerticalMerge(over.formatting?.vMerge) === VERTICAL.NONE) restarted.add(over);
14590
+ return cell;
14591
+ });
14592
+ const out = [...rows];
14593
+ const previous = rows[at - 1];
14594
+ if (previous !== void 0 && restarted.size > 0) out[at - 1] = {
14595
+ ...previous,
14596
+ cells: previous.cells.map((cell) => restarted.has(cell) ? withVerticalMerge(cell, VERTICAL.RESTART) : cell)
14597
+ };
14598
+ out.splice(at, 0, {
14599
+ ...row,
14600
+ cells
14601
+ });
14602
+ return out;
14603
+ };
14393
14604
  /**
14394
- * Whether taking rows out left a vertical merge without the cell that starts
14395
- * it: rows that covered one grid before must still cover one after, or a
14396
- * merged cell's content went with a row that only continued elsewhere.
14605
+ * Whether a row edit left a vertical merge without the cell that starts it:
14606
+ * rows that covered one grid before must still cover one after, or a merged
14607
+ * cell's content went with a row that only continued elsewhere, or an
14608
+ * inserted row continues a merge that is not there.
14397
14609
  */
14398
14610
  const removalOrphansAMerge = (before, rows) => rows.length > 0 && tableGrid(before, DOCUMENT_OP_TYPES.DELETE_ROW).isOk() && tableGrid({
14399
14611
  ...before,
@@ -15168,6 +15380,22 @@ const runParagraphIntoTable = (paragraph, target) => {
15168
15380
  if (replacement.type !== "table") panic("A table receiver has a nonempty table path.");
15169
15381
  return replacement;
15170
15382
  };
15383
+ /** A rejected deletion keeps its receiver. Other pending structures block it. */
15384
+ const authoredTableReceiverIsPending = ({ table, decision, selected }) => {
15385
+ const deletionStays = (id) => decision === REVISION_DECISIONS.REJECT && selected.has(id);
15386
+ let current = table;
15387
+ for (;;) {
15388
+ const row = current.rows.at(0);
15389
+ const rowChange = row?.structuralChange;
15390
+ if (rowChange?.type === "tableRowInsertion" || rowChange?.type === "tableRowDeletion" && !deletionStays(rowChange.info.id)) return true;
15391
+ const cell = row?.cells.at(0);
15392
+ const cellChange = cell?.structuralChange;
15393
+ if (cellChange?.type === "tableCellInsertion" || cellChange?.type === "tableCellMerge" || cellChange?.type === "tableCellDeletion" && !deletionStays(cellChange.info.id)) return true;
15394
+ const first = cell?.content.at(0);
15395
+ if (first?.type !== "table") return false;
15396
+ current = first;
15397
+ }
15398
+ };
15171
15399
  const NO_COMMENT_RANGES = /* @__PURE__ */ new Set();
15172
15400
  const NO_BOUNDARY_PATHS = /* @__PURE__ */ new Set();
15173
15401
  /** Whether a decision removes the content of a tracked change of this kind. */
@@ -15345,29 +15573,47 @@ const resolveRun = (run, { ids, decision }) => {
15345
15573
  else delete next.propertyChanges;
15346
15574
  return next;
15347
15575
  };
15348
- /** Records with the run property changes of their runs resolved, the same list when none is. */
15349
- const resolveRunsIn = (nodes, resolution) => {
15576
+ /**
15577
+ * A field's result with the records it holds resolved: the run property
15578
+ * changes on its runs, and the tracked changes `w:fldSimple` holds around
15579
+ * them ({@link fieldHeldChangeIds}). The result is the field's one unit, so
15580
+ * a resolved change keeps or drops its content where it stood and no seam
15581
+ * outside the field moves. A container that resolving empties goes, as
15582
+ * resolution leaves no emptied record.
15583
+ */
15584
+ const resolveFieldResult = (nodes, resolution, held) => {
15350
15585
  let changed = false;
15351
- const out = nodes.map((node) => {
15586
+ const out = [];
15587
+ for (const node of nodes) {
15588
+ if (isTrackedWrapper(node) && held.has(node.info.id) && resolution.ids.has(node.info.id)) {
15589
+ changed = true;
15590
+ if (!removesContent(node, resolution.decision)) out.push(...resolveFieldResult(node.content, resolution, held));
15591
+ continue;
15592
+ }
15352
15593
  let next = node;
15594
+ const children = node.type === "run" ? void 0 : childNodes(node);
15353
15595
  if (node.type === "run") next = resolveRun(node, resolution);
15354
- else {
15355
- const children = childNodes(node);
15356
- const inner = children === void 0 ? children : resolveRunsIn(children, resolution);
15357
- if (inner !== children && inner !== void 0) next = rebuildNode(node, inner);
15596
+ else if (children !== void 0) {
15597
+ const inner = resolveFieldResult(children, resolution, held);
15598
+ if (inner !== children) {
15599
+ changed = true;
15600
+ if (inner.length === 0 && children.length > 0) continue;
15601
+ next = rebuildNode(node, inner);
15602
+ }
15358
15603
  }
15359
15604
  if (next !== node) changed = true;
15360
- return next;
15361
- });
15605
+ out.push(next);
15606
+ }
15362
15607
  return changed ? out : nodes;
15363
15608
  };
15364
15609
  /**
15365
- * A field with the run property changes on the runs of its result resolved:
15366
- * a run property patch over the field records them there.
15610
+ * A field with the records of its result resolved: the run property changes
15611
+ * a run property patch over the field records there, and the tracked changes
15612
+ * a `w:fldSimple` holds.
15367
15613
  */
15368
15614
  const resolveFieldRuns = (field, resolution) => {
15369
15615
  const result = fieldResultOf(field) ?? [];
15370
- const next = resolveRunsIn(result, resolution);
15616
+ const next = resolveFieldResult(result, resolution, new Set(fieldHeldChangeIds(field)));
15371
15617
  return next === result ? field : withFieldResult(field, next);
15372
15618
  };
15373
15619
  const emptyPieceOf = ({ empty, other, emptied }) => {
@@ -18722,6 +18968,7 @@ const reachableIds = (paragraph) => {
18722
18968
  for (const node of nodes) {
18723
18969
  if (isTrackedWrapper(node)) out.add(node.info.id);
18724
18970
  for (const change of ownRunPropertyChanges(node)) out.add(change.info.id);
18971
+ for (const id of fieldHeldChangeIds(node)) out.add(id);
18725
18972
  visit(childNodes(node) ?? []);
18726
18973
  }
18727
18974
  };
@@ -19005,7 +19252,7 @@ const opensSectionBeforeTrailingBoundaries = (blocks, index) => {
19005
19252
  const before = blocks.findLast((block, at) => at < index && !isBlockBoundary(block));
19006
19253
  return before?.type === "paragraph" && before.sectionProperties !== void 0;
19007
19254
  };
19008
- const joinOps = (document, { op, story, paraId, revisionId, added, depth, holders }, ends, ranInto = /* @__PURE__ */ new Set(), joinsBefore = /* @__PURE__ */ new Set(), rejoined = /* @__PURE__ */ new Map()) => {
19255
+ const joinOps = (document, { op, story, paraId, revisionId, added, depth, holders, pendingReceiverTableIds }, ends, ranInto = /* @__PURE__ */ new Set(), joinsBefore = /* @__PURE__ */ new Set(), rejoined = /* @__PURE__ */ new Map()) => {
19009
19256
  const body = storyBody$1(document, story);
19010
19257
  const location = findStoryParagraph(body, paraId);
19011
19258
  if (location === void 0) return Result.err(refusal$3(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, `No paragraph is ${paraId}.`));
@@ -19157,7 +19404,8 @@ const joinOps = (document, { op, story, paraId, revisionId, added, depth, holder
19157
19404
  const containerFinal = endsItsContainer(body, location);
19158
19405
  const endsBeforeBoundaries = added && next === void 0 && standing.length > 0 && opensSectionBeforeTrailingBoundaries(blocks, location.index);
19159
19406
  const tableBoundary = next?.type === "table" ? paragraphTableRunInBoundary(paragraph, next) : void 0;
19160
- const tableTarget = tableBoundary?.type === "receiver" ? tableBoundary.target : void 0;
19407
+ const stillPendingReceiver = pendingReceiverTableIds !== void 0 && next?.type === "table" && storyParagraphs({ content: [next] }).some(({ paragraph: { paraId: receiverId } }) => receiverId !== void 0 && pendingReceiverTableIds.has(idKey(receiverId)));
19408
+ const tableTarget = tableBoundary?.type === "receiver" && !stillPendingReceiver ? tableBoundary.target : void 0;
19161
19409
  const blockTarget = next !== void 0 && followsBlock ? paragraphBlockRunInTarget(paragraph, next) : void 0;
19162
19410
  const runInReceiver = tableTarget?.receiver ?? blockTarget?.receiver;
19163
19411
  const remains = paragraphRemains(paragraph.content);
@@ -19623,26 +19871,26 @@ const withBelongingPropertyChanges = (document, op) => {
19623
19871
  * Resolve tracked changes by revision id, applied as the primitive
19624
19872
  * operations it expands to. An id no record in the story carries is
19625
19873
  * skipped; one carried by a record resolution does not reach yet (a table,
19626
- * cell or section change, a record inside a field) is refused.
19874
+ * cell or section change, or a change inside a simple field holding content
19875
+ * the field cannot hold) is refused.
19627
19876
  */
19628
19877
  const planRevisionResolution = (options) => {
19629
19878
  const { document, applyOps } = options;
19630
19879
  const op = withBelongingPropertyChanges(document, options.op);
19631
19880
  const sections = settleSectionRecords(document, op);
19632
19881
  if (sections.ops.length === 0) return planMarkResolution({
19633
- document,
19634
- op,
19635
- applyOps
19882
+ ...options,
19883
+ op
19636
19884
  });
19637
19885
  const settled = applyOps(document, sections.ops);
19638
19886
  if (settled.isErr()) return Result.err(settled.error);
19639
19887
  const rest = planMarkResolution({
19888
+ ...options,
19640
19889
  document: settled.value.document,
19641
19890
  op: {
19642
19891
  ...op,
19643
19892
  revisionIds: sections.ids
19644
- },
19645
- applyOps
19893
+ }
19646
19894
  });
19647
19895
  if (rest.isErr()) return Result.err(rest.error);
19648
19896
  return Result.ok({
@@ -19756,12 +20004,12 @@ const planMarkResolution = (options) => {
19756
20004
  const marks = applyOps(document, settled.ops);
19757
20005
  if (marks.isErr()) return Result.err(marks.error);
19758
20006
  const rest = planSingleRecordResolution({
20007
+ ...options,
19759
20008
  document: marks.value.document,
19760
20009
  op: {
19761
20010
  ...op,
19762
20011
  revisionIds: settled.ids
19763
- },
19764
- applyOps
20012
+ }
19765
20013
  }, storyParagraphs(storyBody$1(marks.value.document, op.story)));
19766
20014
  if (rest.isErr()) return Result.err(rest.error);
19767
20015
  return Result.ok({
@@ -19769,7 +20017,7 @@ const planMarkResolution = (options) => {
19769
20017
  receiverEffects: rest.value.receiverEffects
19770
20018
  });
19771
20019
  };
19772
- const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
20020
+ const planSingleRecordResolution = ({ document, op, applyOps, purpose }, paragraphs) => {
19773
20021
  if (!Object.values(REVISION_DECISIONS).includes(op.decision)) return Result.err(refusal$3(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A decision accepts or rejects."));
19774
20022
  if (!op.revisionIds.every((id) => Number.isInteger(id))) return Result.err(refusal$3(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "A revision id is an integer."));
19775
20023
  const finalSectionRevision = storyBody$1(document, op.story).finalSectionProperties?.propertyChanges?.find(({ info }) => op.revisionIds.includes(info.id));
@@ -20068,8 +20316,15 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
20068
20316
  const keepsBreak = markResolved && added === (op.decision === REVISION_DECISIONS.ACCEPT);
20069
20317
  if (markResolved && !keepsBreak) {
20070
20318
  let depth = retiredCutDepths.get(idKey(paraId)) ?? mark.resolutionJoin;
20319
+ const blocks = blockListAt(body.content, location.list);
20320
+ const following = purpose === "markup-view" ? blockFollower(blocks, location.index).block : void 0;
20321
+ const pendingReceiverTableIds = following?.type === "table" && authoredTableReceiverIsPending({
20322
+ table: following,
20323
+ decision: op.decision,
20324
+ selected: ids
20325
+ }) ? new Set(storyParagraphs({ content: [following] }).flatMap(({ paragraph: { paraId: receiverId } }) => receiverId === void 0 ? [] : [idKey(receiverId)])) : void 0;
20071
20326
  if (added && depth !== void 0 && op.decision === REVISION_DECISIONS.REJECT) {
20072
- const next = blockListAt(body.content, location.list).at(location.index + 1);
20327
+ const next = blocks.at(location.index + 1);
20073
20328
  depth = Math.max(depth, resolvedCutEdges.get(idKey(paraId))?.last ?? 0, next?.type === "paragraph" ? resolvedCutEdges.get(idKey(next.paraId ?? ""))?.first ?? 0 : 0);
20074
20329
  }
20075
20330
  joins.push({
@@ -20079,7 +20334,8 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
20079
20334
  revisionId: mark.info.id,
20080
20335
  added,
20081
20336
  depth,
20082
- holders
20337
+ holders,
20338
+ ...pendingReceiverTableIds === void 0 ? {} : { pendingReceiverTableIds }
20083
20339
  });
20084
20340
  }
20085
20341
  let review = resolveParagraphReview(paragraph, resolution, keepsBreak);
@@ -20345,11 +20601,88 @@ const rejoinedRevisions = ({ rejoined, present }) => {
20345
20601
  }
20346
20602
  return absorptions;
20347
20603
  };
20348
- const resolveRevision = (document, op, applyOps) => planRevisionResolution({
20349
- document,
20350
- op,
20351
- applyOps
20352
- }).map(({ edit }) => edit);
20604
+ /**
20605
+ * Resolve an independent text story with the same inline planner. With no
20606
+ * structural records, anchors or cut provenance, a paragraph's resolution
20607
+ * cannot change the next one. A view can keep every unchanged block and skip
20608
+ * building write operations and inverses for the parallel replacements.
20609
+ */
20610
+ const resolveIndependentTextParagraphs = (body, decision) => {
20611
+ if ((body.finalSectionProperties?.propertyChanges?.length ?? 0) > 0) return void 0;
20612
+ const revised = [];
20613
+ const plainRunWidth = (node) => {
20614
+ if (node.type !== "run" || (node.propertyChanges?.length ?? 0) > 0) return 0;
20615
+ let width = 0;
20616
+ for (const leaf of node.content) {
20617
+ if (leaf.type !== "text" || leaf.text.length === 0) return 0;
20618
+ width += leaf.text.length;
20619
+ }
20620
+ return width;
20621
+ };
20622
+ for (const [index, paragraph] of body.content.entries()) {
20623
+ if (paragraph.type !== "paragraph" || paragraph.reviewCarrier !== void 0 || paragraph.pPrMark !== void 0 || (paragraph.propertyChanges?.length ?? 0) > 0 || (paragraph.sectionProperties?.propertyChanges?.length ?? 0) > 0) return void 0;
20624
+ let ids;
20625
+ let omitted;
20626
+ let sourceLength = 0;
20627
+ for (const inline of paragraph.content) {
20628
+ if (inline.type === "run") {
20629
+ const width = plainRunWidth(inline);
20630
+ if (width === 0) return void 0;
20631
+ sourceLength += width;
20632
+ continue;
20633
+ }
20634
+ if (inline.type !== "insertion" && inline.type !== "deletion" || inline.resolutionJoins !== void 0 || !isRevisionId(inline.info.id) || inline.content.length === 0) return void 0;
20635
+ const from = sourceLength;
20636
+ for (const run of inline.content) {
20637
+ const width = plainRunWidth(run);
20638
+ if (width === 0) return void 0;
20639
+ sourceLength += width;
20640
+ }
20641
+ if (removesContent(inline, decision)) (omitted ??= []).push({
20642
+ from,
20643
+ to: sourceLength
20644
+ });
20645
+ (ids ??= /* @__PURE__ */ new Set()).add(inline.info.id);
20646
+ }
20647
+ if (ids !== void 0) revised.push({
20648
+ paragraph,
20649
+ ids,
20650
+ change: {
20651
+ index,
20652
+ sourceLength,
20653
+ omitted: omitted ?? []
20654
+ }
20655
+ });
20656
+ }
20657
+ if (revised.length === 0) return {
20658
+ body,
20659
+ changes: []
20660
+ };
20661
+ const content = [...body.content];
20662
+ for (const { paragraph, ids, change } of revised) {
20663
+ const resolved = resolveList({
20664
+ nodes: paragraph.content,
20665
+ resolution: createResolution(ids, decision),
20666
+ path: []
20667
+ });
20668
+ const resolvedContent = asParagraphContent(resolved.nodes);
20669
+ if (textsIn(resolvedContent).some(hasIllegalXmlCharacters)) return void 0;
20670
+ const target = {
20671
+ ...paragraph,
20672
+ content: resolvedContent
20673
+ };
20674
+ transferParagraphPropertySnapshot({
20675
+ source: paragraph,
20676
+ target
20677
+ });
20678
+ content[change.index] = target;
20679
+ }
20680
+ return {
20681
+ body: withBodyContent(body, content),
20682
+ changes: revised.map(({ change }) => change)
20683
+ };
20684
+ };
20685
+ const resolveRevision = (options) => planRevisionResolution(options).map(({ edit }) => edit);
20353
20686
  // src/ops/revisionInfo.ts
20354
20687
  const refuse$5 = (reason, message) => Result.err(new DocumentOpRefusal({
20355
20688
  reason,
@@ -20722,7 +21055,7 @@ const trackTableRows = ({ document, op, rows, revision, newIds, kind, survivingC
20722
21055
  reason: pendingParagraphMarkReason(reviewedFinalMark),
20723
21056
  message: "A cell's final paragraph already carries a mark revision."
20724
21057
  });
20725
- if (missingFinalParagraph || rows.some((row) => row.preserved !== void 0 || row.bookmarks !== void 0 || row.contentControls !== void 0 || row.carrierStack !== void 0 || row.cells.some((cell) => cell.structuralChange !== void 0 || (cell.propertyChanges?.length ?? 0) > 0 || (cell.contentControls !== void 0 || cell.carrierStack !== void 0) && kind !== WRAP_KINDS.DELETION || !survivingCells.has(cell) && !trackableBlocks(cell.content)))) return refused$1({
21058
+ if (missingFinalParagraph || rows.some((row) => row.cells.some((cell) => cell.structuralChange !== void 0 || (cell.propertyChanges?.length ?? 0) > 0 || !survivingCells.has(cell) && !trackableBlocks(cell.content)))) return refused$1({
20726
21059
  op,
20727
21060
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
20728
21061
  message: rows.some((row) => row.cells.some((cell) => holdsTable(cell.content))) ? "A suggestion cannot record a nested table that holds captured markup or review records." : "The rows contain an unsupported tracked structure."
@@ -20966,6 +21299,12 @@ const validStructure = (blocks) => blocks.every((block) => {
20966
21299
  default: return block;
20967
21300
  }
20968
21301
  });
21302
+ /** Whether `shorter` is `longer` with some of its blocks left out, in order. */
21303
+ const isSubsequence = (shorter, longer) => {
21304
+ let index = 0;
21305
+ for (const block of longer) if (index < shorter.length && structurallyEqual(shorter[index], block)) index += 1;
21306
+ return index === shorter.length;
21307
+ };
20969
21308
  const commitBlocks = ({ document, op, anchor, blocks }) => {
20970
21309
  const body = storyBody$1(document, op.story);
20971
21310
  const before = blockListAt(body.content, anchor.list);
@@ -20992,7 +21331,7 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
20992
21331
  message: "A table has rows and cells; each cell and the story retain a final paragraph."
20993
21332
  });
20994
21333
  const fixedBlocks = (items) => items.filter((block) => block.type !== "table" && block.type !== "paragraph" && !isBlockBoundary(block));
20995
- if (!structurallyEqual(fixedBlocks(before), fixedBlocks(blocks))) return refuse$4({
21334
+ if (!(op.type === DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS ? isSubsequence(fixedBlocks(before), fixedBlocks(blocks)) || isSubsequence(fixedBlocks(blocks), fixedBlocks(before)) : structurallyEqual(fixedBlocks(before), fixedBlocks(blocks)))) return refuse$4({
20996
21335
  op,
20997
21336
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
20998
21337
  message: "A table structural inverse preserves surrounding block wrappers and markers."
@@ -21675,15 +22014,11 @@ const withOmission = (row, side, value) => {
21675
22014
  formatting
21676
22015
  };
21677
22016
  };
21678
- /**
21679
- * Markup a column or cell edit would have to relocate: what a row keeps
21680
- * beside its cells, counted by the cells before it. A column or cell edit
21681
- * keeps every row, so what stands beside or around rows keeps its place as
21682
- * it stands: bookmarks and captured markup beside a table's rows count the
21683
- * rows before them, and a row content control or another wrapper around the
21684
- * table or its rows wraps them whatever cells they hold.
21685
- */
21686
- const hasStructuralMarkup = (table) => table.rows.some((row) => row.preserved !== void 0);
22017
+ /** Captures and cells inside the same wrapper must move as one group. */
22018
+ const hasWrappedCellMarkup = (table) => {
22019
+ const wrapped = ({ contentControls, carrierStack }) => contentControls !== void 0 || carrierStack !== void 0;
22020
+ return table.rows.some((row) => row.preserved?.children !== void 0 && (row.preserved.children.some(wrapped) || row.cells.some(wrapped)));
22021
+ };
21687
22022
  /** A cell holding one paragraph with nothing in it. */
21688
22023
  const isEmptyCell = (cell) => cell.content.length === 1 && cell.content[0]?.type === "paragraph" && cell.content[0].content.length === 0;
21689
22024
  const hasReview = (table) => table.formatting?.gridChange !== void 0 || table.propertyChanges !== void 0 || table.rows.some((row) => row.structuralChange !== void 0 || row.propertyChanges !== void 0 || row.cells.some((cell) => cell.structuralChange !== void 0 || cell.propertyChanges !== void 0));
@@ -22275,14 +22610,10 @@ const columnEdit = ({ document, op, table, grid }) => {
22275
22610
  const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
22276
22611
  const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
22277
22612
  if (!Number.isSafeInteger(count) || count < 1) return mismatch(op, "A column insertion inserts at least one column.");
22613
+ if (insert && count > 4096 - grid.width) return mismatch(op, `A table grid can hold at most ${MAX_TABLE_GRID_COLUMNS} columns.`);
22278
22614
  if (!Number.isSafeInteger(op.column) || op.column < 0 || op.column >= grid.width + (insert ? 1 : 0)) return mismatch(op, "Column is outside the logical grid.");
22279
22615
  if (!insert && grid.width === 1) return mismatch(op, "Deleting the final column requires deleting the table.");
22280
22616
  if (insert && (!Number.isSafeInteger(op.width) || op.width <= 0)) return mismatch(op, "A column width must be a positive twip count.");
22281
- if (hasStructuralMarkup(table)) return refuse$3({
22282
- op,
22283
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
22284
- message: "Indexed table markup must be relocated before changing columns."
22285
- });
22286
22617
  if (insert && op.revision !== void 0 && table.formatting?.gridChange !== void 0) return refuse$3({
22287
22618
  op,
22288
22619
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_GRID_CHANGE,
@@ -22323,7 +22654,7 @@ const columnEdit = ({ document, op, table, grid }) => {
22323
22654
  count: boundaryRows * count
22324
22655
  }) : Result.ok([]);
22325
22656
  if (fresh.isErr()) return Result.err(fresh.error);
22326
- const trackedDeletion = !insert && op.revision !== void 0;
22657
+ const trackedDeletion = suggestedDeletion && removedCells.length > 0;
22327
22658
  const leavesRow = (rowIndex) => {
22328
22659
  const { before, end } = rowExtent(table, grid, rowIndex);
22329
22660
  if (trackedDeletion) return op.column < before || op.column >= end;
@@ -22343,11 +22674,6 @@ const columnEdit = ({ document, op, table, grid }) => {
22343
22674
  stampedRows.set(rowIndex, rowStamps);
22344
22675
  rowStamps += takesNewCells(rowIndex) ? count : 1;
22345
22676
  }
22346
- if (trackedDeletion && stampedRows.size === 0) return refuse$3({
22347
- op,
22348
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
22349
- message: "A suggested column deletion needs a cell in the column to mark."
22350
- });
22351
22677
  const stamps = stampsFor(op, trackedDeletion ? rowStamps : rowStamps + 2);
22352
22678
  if (stamps.isErr()) return Result.err(stamps.error);
22353
22679
  const rowStamp = (rowIndex, cell = 0) => {
@@ -22849,10 +23175,10 @@ const reviewedMergeContent = ({ document, op, changes, words }) => {
22849
23175
  }
22850
23176
  };
22851
23177
  const merge = ({ document, op, table, grid }) => {
22852
- if (hasStructuralMarkup(table)) return refuse$3({
23178
+ if (hasWrappedCellMarkup(table)) return refuse$3({
22853
23179
  op,
22854
23180
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
22855
- message: "Indexed table markup must be relocated before changing cells."
23181
+ message: "Captures inside cell wrappers need a shared destination."
22856
23182
  });
22857
23183
  if (op.revision !== void 0 && hasReviewBlockingMerge({
22858
23184
  table,
@@ -23037,10 +23363,10 @@ const split = ({ document, op, table, grid, location }) => {
23037
23363
  const target = grid.rows[location.rowIndex]?.find((entry) => entry.index === location.cellIndex);
23038
23364
  if (!target) return mismatch(op, "The addressed cell is absent.");
23039
23365
  if (target.row !== target.ownerRow || target.index !== target.ownerIndex) return mismatch(op, "A vertical merge continuation must be addressed through its owner cell.");
23040
- if (hasStructuralMarkup(table)) return refuse$3({
23366
+ if (hasWrappedCellMarkup(table)) return refuse$3({
23041
23367
  op,
23042
23368
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
23043
- message: "Indexed table markup must be relocated before changing cells."
23369
+ message: "Captures inside cell wrappers need a shared destination."
23044
23370
  });
23045
23371
  if (op.revision !== void 0 && hasReview(table)) return refuse$3({
23046
23372
  op,
@@ -23179,6 +23505,7 @@ const tableEditParagraphDemand = (location, op) => {
23179
23505
  if (grid.isErr()) return Result.err(grid.error);
23180
23506
  switch (op.type) {
23181
23507
  case DOCUMENT_OP_TYPES.INSERT_COLUMN: {
23508
+ if ((op.count ?? 1) > 4096 - grid.value.width) return mismatch(op, `A table grid can hold at most ${MAX_TABLE_GRID_COLUMNS} columns.`);
23182
23509
  const plans = recordsPlaceColumnsApart(table, grid.value) ? columnPlanAcrossRecords({
23183
23510
  table,
23184
23511
  grid: grid.value,
@@ -23423,11 +23750,6 @@ const applyTableEdit = (document, op) => {
23423
23750
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
23424
23751
  message: "Resolve the existing grid revision before resizing."
23425
23752
  });
23426
- if (op.revision !== void 0 && table.columnWidths === void 0) return refuse$3({
23427
- op,
23428
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
23429
- message: "A grid revision requires an explicit previous grid."
23430
- });
23431
23753
  if (table.propertyChanges !== void 0) return refuse$3({
23432
23754
  op,
23433
23755
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
@@ -23447,7 +23769,7 @@ const applyTableEdit = (document, op) => {
23447
23769
  ...table.formatting,
23448
23770
  gridChange: {
23449
23771
  id: gridStamp.id,
23450
- columnWidths: [...table.columnWidths ?? []]
23772
+ columnWidths: table.columnWidths === void 0 ? Array.from({ length: grid.value.width }, () => void 0) : [...table.columnWidths]
23451
23773
  }
23452
23774
  };
23453
23775
  next.propertyChanges = [{
@@ -23518,12 +23840,6 @@ const paragraphsIn$1 = (rows) => storyParagraphs({ content: [{
23518
23840
  type: "table",
23519
23841
  rows: [...rows]
23520
23842
  }] }).map(({ paragraph }) => paragraph);
23521
- /**
23522
- * Indexed markup and shared row wrappers need a structural table operation.
23523
- * Bookmark markers beside the rows move with them
23524
- * ({@link relocatePositionedMarkers}).
23525
- */
23526
- const needsTableEdit = (table) => table.preserved !== void 0 || table.carrierStack !== void 0 || table.rows.some((row) => row.contentControls !== void 0 || row.carrierStack !== void 0);
23527
23843
  const withTable = ({ document, story, location, table }) => {
23528
23844
  const body = storyBody$1(document, story);
23529
23845
  const content = updateBlockList(body.content, location.list, (blocks) => {
@@ -23564,10 +23880,10 @@ const commitRows = ({ document, op, location, rows }) => {
23564
23880
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
23565
23881
  message: "Every row has cells, and every cell has a paragraph."
23566
23882
  });
23567
- if (op.type === DOCUMENT_OP_TYPES.DELETE_ROW && removalOrphansAMerge(location.table, rows)) return refused({
23883
+ if (op.type !== DOCUMENT_OP_TYPES.SET_TABLE_ROWS && removalOrphansAMerge(location.table, rows)) return refused({
23568
23884
  op,
23569
23885
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
23570
- message: "A removed row hands the merges it starts to the next row with their content."
23886
+ message: "A row edit keeps every vertical merge under the cell that starts it."
23571
23887
  });
23572
23888
  if (afterParagraphs.some(({ content }) => textsIn(content).some(hasIllegalXmlCharacters))) return refused({
23573
23889
  op,
@@ -23604,18 +23920,18 @@ const commitRows = ({ document, op, location, rows }) => {
23604
23920
  reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
23605
23921
  message: "A row paragraph id is already used in the package."
23606
23922
  });
23923
+ const table = relocatePositionedMarkers(location.table, {
23924
+ ...location.table,
23925
+ rows
23926
+ });
23607
23927
  const remainingRecords = countKeys(packageIdentityKeys(document.package));
23608
- for (const key of identityKeysIn(before)) remainingRecords.set(key, (remainingRecords.get(key) ?? 1) - 1);
23609
- const incomingRecords = identityKeysIn(rows);
23928
+ for (const key of identityKeysIn(location.table)) remainingRecords.set(key, (remainingRecords.get(key) ?? 1) - 1);
23929
+ const incomingRecords = identityKeysIn(table);
23610
23930
  if (incomingRecords.some((key) => (remainingRecords.get(key) ?? 0) > 0) || new Set(incomingRecords).size !== incomingRecords.length) return refused({
23611
23931
  op,
23612
23932
  reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
23613
23933
  message: "A row revision or content-control id is already used in the package."
23614
23934
  });
23615
- const table = relocatePositionedMarkers(location.table, {
23616
- ...location.table,
23617
- rows
23618
- });
23619
23935
  const next = withTable({
23620
23936
  document,
23621
23937
  story: op.story,
@@ -23640,7 +23956,7 @@ const commitRows = ({ document, op, location, rows }) => {
23640
23956
  });
23641
23957
  return Result.ok({
23642
23958
  document: next,
23643
- inverse: [holdsPositionedMarkers(location.table) ? {
23959
+ inverse: [holdsPositionedMarkup(location.table) ? {
23644
23960
  type: DOCUMENT_OP_TYPES.SET_TABLE,
23645
23961
  story: op.story,
23646
23962
  blockId: anchor,
@@ -23650,7 +23966,7 @@ const commitRows = ({ document, op, location, rows }) => {
23650
23966
  type: DOCUMENT_OP_TYPES.SET_TABLE_ROWS,
23651
23967
  story: op.story,
23652
23968
  blockId: anchor,
23653
- expected: rows,
23969
+ expected: table.rows,
23654
23970
  rows: before
23655
23971
  }],
23656
23972
  touched: {
@@ -23675,11 +23991,6 @@ const applyRowOp = (document, op) => {
23675
23991
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET,
23676
23992
  message: "The row index is outside the table."
23677
23993
  });
23678
- if (needsTableEdit(location.table)) return refused({
23679
- op,
23680
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
23681
- message: "Indexed table markup or shared row wrappers require a table operation."
23682
- });
23683
23994
  const incoming = cloneModel(op.row);
23684
23995
  if (paragraphIdsIn(incoming).some((id) => paragraphIdsIn(before).some((existing) => idKey(existing) === idKey(id)))) return refused({
23685
23996
  op,
@@ -23696,12 +24007,11 @@ const applyRowOp = (document, op) => {
23696
24007
  });
23697
24008
  if (tracked.isErr()) return Result.err(tracked.error);
23698
24009
  const row = tracked.value.at(0) ?? panic("A tracked insertion lost its row.");
23699
- rows.splice(op.at, 0, row);
23700
24010
  return commitRows({
23701
24011
  document,
23702
24012
  op,
23703
24013
  location,
23704
- rows
24014
+ rows: rowsWithRow(rows, op.at, row)
23705
24015
  });
23706
24016
  }
23707
24017
  case DOCUMENT_OP_TYPES.DELETE_ROW: {
@@ -23719,11 +24029,6 @@ const applyRowOp = (document, op) => {
23719
24029
  location,
23720
24030
  rows: []
23721
24031
  });
23722
- if (needsTableEdit(location.table)) return refused({
23723
- op,
23724
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
23725
- message: "Indexed table markup or shared row wrappers require a table operation."
23726
- });
23727
24032
  if (removesOutright || op.revision === void 0) return commitRows({
23728
24033
  document,
23729
24034
  op,
@@ -23754,11 +24059,6 @@ const applyRowOp = (document, op) => {
23754
24059
  reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
23755
24060
  message: "The table rows have changed."
23756
24061
  });
23757
- if (op.rows.length > 0 && op.rows.length !== before.length && needsTableEdit(location.table)) return refused({
23758
- op,
23759
- reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
23760
- message: "Indexed table markup or shared row wrappers require a table operation."
23761
- });
23762
24062
  const replacement = op.rows.map((row) => before.find((existing) => structurallyEqual(existing, row)) ?? cloneModel(row));
23763
24063
  return commitRows({
23764
24064
  document,
@@ -25271,7 +25571,12 @@ const dispatchCore = ({ document, op, purpose }) => {
25271
25571
  case DOCUMENT_OP_TYPES.REPLACE_BLOCKS: return replaceBlocks(document, op);
25272
25572
  case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW:
25273
25573
  case DOCUMENT_OP_TYPES.REPLACE_INLINE: return applyParagraphPrimitive(document, op);
25274
- case DOCUMENT_OP_TYPES.RESOLVE_REVISION: return resolveRevision(document, op, applyOps);
25574
+ case DOCUMENT_OP_TYPES.RESOLVE_REVISION: return resolveRevision({
25575
+ document,
25576
+ op,
25577
+ applyOps,
25578
+ purpose
25579
+ });
25275
25580
  case DOCUMENT_OP_TYPES.SET_REVISION_INFO: return setRevisionInfo(document, op);
25276
25581
  case DOCUMENT_OP_TYPES.DELETE_TABLE: {
25277
25582
  const pending = ownPendingTableInsertion(document, op);
@@ -25633,7 +25938,7 @@ const applyAddressedOp = ({ document, op, purpose, boxes }) => {
25633
25938
  }
25634
25939
  }
25635
25940
  if (hasMultipleParagraphPropertyChanges(edit.document, boxes)) return Result.err(refusal$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A paragraph cannot carry more than one property change."));
25636
- if (purpose === "apply" && gainsSectionInTableCell(document, edit.document)) return Result.err(refusal$2(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, "A section cannot end inside a table cell."));
25941
+ if (purpose !== "inspect-inverse" && gainsSectionInTableCell(document, edit.document)) return Result.err(refusal$2(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, "A section cannot end inside a table cell."));
25637
25942
  const repeatedId = repeatedParagraphId(edit.document);
25638
25943
  if (repeatedId !== void 0) return Result.err(refusal$2(op, repeatedId.reason, repeatedId.message));
25639
25944
  meetsContract(edit.document);
@@ -25745,6 +26050,12 @@ const applyDocumentOps = (document, ops) => applyDocumentOpsForPurpose({
25745
26050
  ops,
25746
26051
  purpose: "apply"
25747
26052
  });
26053
+ /** Resolve revisions for a markup view through the same operation engine. */
26054
+ const applyMarkupViewOps = (document, ops) => applyDocumentOpsForPurpose({
26055
+ document,
26056
+ ops,
26057
+ purpose: "markup-view"
26058
+ });
25748
26059
  /**
25749
26060
  * Apply operations to read what they leave, as a rebase takes back a pending
25750
26061
  * edit by its recorded inverse: an inverse that as an operation of its own
@@ -27737,6 +28048,67 @@ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileI
27737
28048
  selection: intent.to
27738
28049
  });
27739
28050
  };
28051
+ // src/ops/pastedBlocks.ts
28052
+ /**
28053
+ * `block` with every paragraph it holds, at any depth, as `paragraph` gives
28054
+ * it, visited in document order: a table's cells and a container's blocks
28055
+ * are descended into, and every other block is kept.
28056
+ */
28057
+ const mapBlockParagraphs = (block, paragraph) => {
28058
+ switch (block.type) {
28059
+ case "paragraph": return paragraph(block);
28060
+ case "table": return {
28061
+ ...block,
28062
+ rows: block.rows.map((row) => ({
28063
+ ...row,
28064
+ cells: row.cells.map((cell) => ({
28065
+ ...cell,
28066
+ content: cell.content.map((inner) => mapBlockParagraphs(inner, paragraph))
28067
+ }))
28068
+ }))
28069
+ };
28070
+ case "blockSdt":
28071
+ case "blockCustomXml": return {
28072
+ ...block,
28073
+ content: block.content.map((inner) => mapBlockParagraphs(inner, paragraph))
28074
+ };
28075
+ default: return block;
28076
+ }
28077
+ };
28078
+ /** {@link mapBlockParagraphs} of a pasted block, which stays the kind it was. */
28079
+ const mapPastedBlockParagraphs = (block, paragraph) => {
28080
+ switch (block.type) {
28081
+ case "paragraph": return paragraph(block);
28082
+ case "table": return {
28083
+ ...block,
28084
+ rows: block.rows.map((row) => ({
28085
+ ...row,
28086
+ cells: row.cells.map((cell) => ({
28087
+ ...cell,
28088
+ content: cell.content.map((inner) => mapBlockParagraphs(inner, paragraph))
28089
+ }))
28090
+ }))
28091
+ };
28092
+ case "blockSdt":
28093
+ case "blockCustomXml": return {
28094
+ ...block,
28095
+ content: block.content.map((inner) => mapBlockParagraphs(inner, paragraph))
28096
+ };
28097
+ case "preservedBlock": return block;
28098
+ default: return block;
28099
+ }
28100
+ };
28101
+ /** Whether `block` is one a paste places. */
28102
+ const isPastedBlock = (block) => block.type === "paragraph" || block.type === "table" || block.type === "blockSdt" || block.type === "blockCustomXml" || block.type === "preservedBlock";
28103
+ /** Every paragraph `block` holds, at any depth, in document order. */
28104
+ const blockParagraphsOf = (block) => {
28105
+ const paragraphs = [];
28106
+ mapBlockParagraphs(block, (paragraph) => {
28107
+ paragraphs.push(paragraph);
28108
+ return paragraph;
28109
+ });
28110
+ return paragraphs;
28111
+ };
27740
28112
  // src/ops/pasteAnchors.ts
27741
28113
  const PLACEHOLDER_STEM = "_folioPasteAnchor";
27742
28114
  /** Where placeholder ids start; an id a bookmark already holds is skipped. */
@@ -27852,20 +28224,10 @@ const withPasteAnchors = (blocks, destination = {
27852
28224
  }
27853
28225
  return out;
27854
28226
  };
27855
- const block = (each) => each.type === "paragraph" ? {
27856
- ...each,
27857
- content: inline(each.content)
27858
- } : {
27859
- ...each,
27860
- rows: each.rows.map((row) => ({
27861
- ...row,
27862
- cells: row.cells.map((cell) => ({
27863
- ...cell,
27864
- content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? block(inner) : inner)
27865
- }))
27866
- }))
27867
- };
27868
- const anchoredBlocks = blocks.map(block);
28227
+ const anchoredBlocks = blocks.map((each) => mapPastedBlockParagraphs(each, (paragraph) => ({
28228
+ ...paragraph,
28229
+ content: inline(paragraph.content)
28230
+ })));
27869
28231
  return {
27870
28232
  prefix,
27871
28233
  ids,
@@ -27947,6 +28309,27 @@ const placedPasteAnchors = ({ paragraphs, prefix, count }) => {
27947
28309
  /** Tracked replacement fragments share deletion's validation and physical-id pool. */
27948
28310
  const rangeParagraph = (body, blockId) => blockId === "" ? storyParagraphs(body).find(({ paragraph }) => (paragraph.paraId ?? "") === "") : findStoryParagraph(body, blockId);
27949
28311
  /**
28312
+ * Where a text replacement leaves the comment anchors it reaches. The direct
28313
+ * edit and the accepted suggestion give the same answer, so a comment's fate
28314
+ * never depends on the mode:
28315
+ *
28316
+ * - A comment marker (range start, range end or reference) inside the
28317
+ * replaced stretch is not deleted with the words. It stays, in its order,
28318
+ * and the new words follow it (this gap). A comment straddling an edge
28319
+ * keeps its outer marker: one ending inside now ends where the new words
28320
+ * start, one starting inside now covers the new words and the rest of its
28321
+ * own.
28322
+ * - A ranged comment whose every word went has nothing left to cover, and
28323
+ * its thread goes, replies included, directly and once the suggestion is
28324
+ * accepted (`newlyExhaustedCommentIds`). A point comment, or a range that
28325
+ * covered nothing before, keeps its thread and stands where the new words
28326
+ * start.
28327
+ * - Tracked, the struck words keep every marker among them
28328
+ * (`replacementDeletionSegments` ends a stretch at each), so rejecting
28329
+ * restores each anchor exactly and accepting leaves the direct result.
28330
+ * - A replacement across paragraphs joins them: the markers of every
28331
+ * paragraph it reaches gather, in order, before the new words.
28332
+ *
27950
28333
  * The gap just after a range deletion, where what replaces the range goes:
27951
28334
  * after the struck content in a redline, and after whatever a deletion keeps
27952
28335
  * in place, so that accepting a tracked replacement gives the direct one.
@@ -28613,7 +28996,7 @@ const createEditorIntentIdAllocator = ({ reservedBlockIds } = {}) => {
28613
28996
  demand += 11;
28614
28997
  for (const block of intent.blocks) {
28615
28998
  if (intent.type === "moveBlocks" && block.type === "table") demand += 2 + block.rows.length;
28616
- const paragraphs = block.type === "table" ? storyParagraphs({ content: [block] }).map(({ paragraph }) => paragraph) : [block];
28999
+ const paragraphs = blockParagraphs(block);
28617
29000
  if (block.type === "table") demand += 2 + block.rows.length;
28618
29001
  for (const paragraph of paragraphs) {
28619
29002
  demand += PARAGRAPH_REVISION_DEMAND;
@@ -28931,12 +29314,53 @@ const bookmarkIdsIn = (items) => items.flatMap((item) => {
28931
29314
  });
28932
29315
  /** Whether a pasted table, or one nested in it, holds bookmarks or records of its own. */
28933
29316
  const holdsTableLevelIdentities = (block) => {
29317
+ if (block.type === "blockSdt" || block.type === "blockCustomXml") return block.content.some(holdsTableLevelIdentities);
28934
29318
  if (block.type !== "table") return false;
28935
29319
  if ((block.bookmarks?.length ?? 0) > 0 || (block.propertyChanges?.length ?? 0) > 0 || (block.carrierStack?.length ?? 0) > 0) return true;
28936
- return block.rows.some((row) => (row.bookmarks?.length ?? 0) > 0 || (row.propertyChanges?.length ?? 0) > 0 || (row.carrierStack?.length ?? 0) > 0 || row.cells.some((cell) => (cell.propertyChanges?.length ?? 0) > 0 || (cell.carrierStack?.length ?? 0) > 0 || cell.content.some((inner) => (inner.type === "paragraph" || inner.type === "table") && holdsTableLevelIdentities(inner))));
29320
+ return block.rows.some((row) => (row.bookmarks?.length ?? 0) > 0 || (row.propertyChanges?.length ?? 0) > 0 || (row.carrierStack?.length ?? 0) > 0 || row.cells.some((cell) => (cell.propertyChanges?.length ?? 0) > 0 || (cell.carrierStack?.length ?? 0) > 0 || cell.content.some(holdsTableLevelIdentities)));
28937
29321
  };
28938
- /** A pasted block's paragraphs in document order, a table's cells' among them. */
28939
- const blockParagraphs = (block) => block.type === "paragraph" ? [block] : block.rows.flatMap((row) => row.cells.flatMap((cell) => cell.content.flatMap((inner) => inner.type === "paragraph" || inner.type === "table" ? blockParagraphs(inner) : [])));
29322
+ /**
29323
+ * A pasted block's paragraphs in document order, a table's cells' and a
29324
+ * container's among them.
29325
+ */
29326
+ const blockParagraphs = (block) => blockParagraphsOf(block);
29327
+ /** The properties of every block content control `blocks` hold, at any depth. */
29328
+ const blockControlsOf = (blocks) => blocks.flatMap((block) => {
29329
+ switch (block.type) {
29330
+ case "blockSdt": return [block.properties, ...blockControlsOf(block.content)];
29331
+ case "blockCustomXml": return blockControlsOf(block.content);
29332
+ case "table": return block.rows.flatMap((row) => row.cells.flatMap((cell) => blockControlsOf(cell.content)));
29333
+ default: return [];
29334
+ }
29335
+ });
29336
+ /** `blocks` with their block content controls' properties, in order, from `controls`. */
29337
+ const withBlockControls = (blocks, controls) => blocks.map((block) => {
29338
+ switch (block.type) {
29339
+ case "blockSdt": {
29340
+ const properties = controls.shift() ?? panic("An identified control is missing.");
29341
+ return {
29342
+ ...block,
29343
+ properties,
29344
+ content: withBlockControls(block.content, controls)
29345
+ };
29346
+ }
29347
+ case "blockCustomXml": return {
29348
+ ...block,
29349
+ content: withBlockControls(block.content, controls)
29350
+ };
29351
+ case "table": return {
29352
+ ...block,
29353
+ rows: block.rows.map((row) => ({
29354
+ ...row,
29355
+ cells: row.cells.map((cell) => ({
29356
+ ...cell,
29357
+ content: withBlockControls(cell.content, controls)
29358
+ }))
29359
+ }))
29360
+ };
29361
+ default: return block;
29362
+ }
29363
+ });
28940
29364
  /**
28941
29365
  * Clipboard blocks placed: once with their placeholders, to find where each
28942
29366
  * lands, and once without, for the operations and the document they leave.
@@ -29029,10 +29453,10 @@ const placeAnchoredBlocks = (document, { intent, plain, prefix, ids, count, mode
29029
29453
  * latest place first so that no copy moves the place of another. A comment
29030
29454
  * whose range the clipboard holds only part of is copied as a point.
29031
29455
  */
29032
- const compileBlockPaste = (document, { intent, mode, firstBlockId }) => {
29456
+ const compileBlockPaste = (document, { intent, mode, firstBlockId, moved }) => {
29033
29457
  const { annotations, ...placement } = intent;
29034
29458
  const anchored = withPasteAnchors(intent.blocks, bookmarksIn(document.package));
29035
- if (anchored.anchors.length === 0) return compileBlockPlacement(document, {
29459
+ if (anchored.anchors.length === 0 || moved === true) return compileBlockPlacement(document, {
29036
29460
  intent: placement,
29037
29461
  mode,
29038
29462
  firstBlockId
@@ -29245,10 +29669,76 @@ const compileBlockPaste = (document, { intent, mode, firstBlockId }) => {
29245
29669
  });
29246
29670
  };
29247
29671
  /**
29248
- * Clipboard blocks with tables: one step after another, each compiled against
29249
- * the document the last left and, suggesting, taking the revision ids the
29250
- * steps before it left unused.
29672
+ * A block content control, custom XML element or kept block markup put in
29673
+ * before `anchor`, in the block list holding it, as its exact list. Neither
29674
+ * has a tracked record of its own: Word records a control's insertion on the
29675
+ * runs inside it, and kept markup is not read, so a suggestion refuses.
29251
29676
  */
29677
+ const placeContainerBlock = ({ document, story, anchor, block, mode }) => {
29678
+ if (mode.type === "suggesting") return Result.err(new DocumentOpRefusal({
29679
+ reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
29680
+ message: "A suggested paste cannot record a block content control, custom XML element or kept block markup.",
29681
+ opType: DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS
29682
+ }));
29683
+ const body = storyBody$1(document, story);
29684
+ const located = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(anchor));
29685
+ if (located === void 0) return Result.err(new DocumentOpRefusal({
29686
+ reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
29687
+ message: "The clipboard destination paragraph does not exist.",
29688
+ opType: DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS
29689
+ }));
29690
+ const expected = blockListAt(body.content, located.list);
29691
+ const op = {
29692
+ type: DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS,
29693
+ story,
29694
+ blockId: anchor,
29695
+ expected,
29696
+ blocks: [
29697
+ ...expected.slice(0, located.index),
29698
+ block,
29699
+ ...expected.slice(located.index)
29700
+ ]
29701
+ };
29702
+ const applied = applyDocumentOps(document, [op]);
29703
+ if (applied.isErr()) return Result.err(applied.error);
29704
+ return Result.ok({
29705
+ op,
29706
+ document: applied.value.document
29707
+ });
29708
+ };
29709
+ /**
29710
+ * A block content control, custom XML element or kept block markup taken out
29711
+ * of the block list holding `anchor`, as its exact list; a suggestion has no
29712
+ * record for it and refuses.
29713
+ */
29714
+ const removeContainerBlock = ({ document, story, anchor, block, mode }) => {
29715
+ const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
29716
+ reason,
29717
+ message,
29718
+ opType: DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS
29719
+ }));
29720
+ if (mode.type === "suggesting") return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A suggested move cannot record a block content control, custom XML element or kept block markup.");
29721
+ const body = storyBody$1(document, story);
29722
+ const located = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(anchor));
29723
+ if (located === void 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "The moved range names a paragraph the story does not hold.");
29724
+ const expected = blockListAt(body.content, located.list);
29725
+ const index = expected.indexOf(block);
29726
+ if (index < 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.STALE, "The moved block is no longer where the range found it.");
29727
+ const op = {
29728
+ type: DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS,
29729
+ story,
29730
+ blockId: anchor,
29731
+ expected,
29732
+ blocks: [...expected.slice(0, index), ...expected.slice(index + 1)]
29733
+ };
29734
+ const applied = applyDocumentOps(document, [op]);
29735
+ if (applied.isErr()) return Result.err(applied.error);
29736
+ return Result.ok({
29737
+ op,
29738
+ document: applied.value.document,
29739
+ inverse: applied.value.inverse
29740
+ });
29741
+ };
29252
29742
  const compileBlockPlacement = (document, { intent, mode, firstBlockId }) => {
29253
29743
  const { from, to, openStart, openEnd } = intent;
29254
29744
  const paragraphs = intent.blocks.filter((block) => block.type === "paragraph");
@@ -29264,26 +29754,25 @@ const compileBlockPlacement = (document, { intent, mode, firstBlockId }) => {
29264
29754
  mode,
29265
29755
  ...firstBlockId === void 0 ? {} : { firstBlockId }
29266
29756
  });
29267
- const identified = identifyClipboardParagraphs({
29757
+ const lastBlock = intent.blocks.at(-1);
29758
+ const identified = identifyClipboardContent({
29268
29759
  document,
29269
29760
  paragraphs: intent.blocks.flatMap(blockParagraphs),
29761
+ controls: blockControlsOf(intent.blocks),
29762
+ identifyLast: lastBlock?.type !== "paragraph" && lastBlock?.type !== "table",
29270
29763
  mode,
29271
29764
  firstBlockId
29272
29765
  });
29273
29766
  if (identified.isErr()) return Result.err(identified.error);
29274
29767
  let next = 0;
29275
- const take = () => identified.value[next++] ?? panic("An identified clipboard paragraph is missing.");
29276
- const rebuilt = (block) => block.type === "paragraph" ? take() : {
29277
- ...block,
29278
- rows: block.rows.map((row) => ({
29279
- ...row,
29280
- cells: row.cells.map((cell) => ({
29281
- ...cell,
29282
- content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? rebuilt(inner) : inner)
29283
- }))
29284
- }))
29285
- };
29286
- const blocks = intent.blocks.map(rebuilt);
29768
+ const take = () => identified.value.paragraphs[next++] ?? panic("An identified clipboard paragraph is missing.");
29769
+ const controls = [...identified.value.controls];
29770
+ const blocks = intent.blocks.map((block) => {
29771
+ const placed = mapPastedBlockParagraphs(block, take);
29772
+ if (placed.type === "paragraph" || placed.type === "preservedBlock") return placed;
29773
+ const [withControls] = withBlockControls([placed], controls);
29774
+ return withControls !== void 0 && isPastedBlock(withControls) ? withControls : panic("A pasted block lost its kind.");
29775
+ });
29287
29776
  const refuseIdentities = (message) => Result.err(new DocumentOpRefusal({
29288
29777
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION,
29289
29778
  message,
@@ -29377,9 +29866,11 @@ const compileBlockPlacement = (document, { intent, mode, firstBlockId }) => {
29377
29866
  from: 0,
29378
29867
  to: caret.offset
29379
29868
  })) {
29869
+ const reserved = new Set(mode.reservedBlockIds);
29870
+ for (const block of blocks) for (const { paraId } of blockParagraphs(block)) if (paraId !== void 0) reserved.add(paraId);
29380
29871
  const fresh = freshParagraphIds({
29381
29872
  document: current,
29382
- reserved: mode.reservedBlockIds,
29873
+ reserved,
29383
29874
  lease: mode.idLease,
29384
29875
  count: 1,
29385
29876
  opType: DOCUMENT_OP_TYPES.SPLIT_BLOCK
@@ -29395,6 +29886,19 @@ const compileBlockPlacement = (document, { intent, mode, firstBlockId }) => {
29395
29886
  }
29396
29887
  const anchor = caret.blockId;
29397
29888
  for (const block of blocks) {
29889
+ if (block.type === "blockSdt" || block.type === "blockCustomXml" || block.type === "preservedBlock") {
29890
+ const placed = placeContainerBlock({
29891
+ document: current,
29892
+ story: caret.story,
29893
+ anchor,
29894
+ block,
29895
+ mode
29896
+ });
29897
+ if (placed.isErr()) return Result.err(placed.error);
29898
+ ops.push(placed.value.op);
29899
+ current = placed.value.document;
29900
+ continue;
29901
+ }
29398
29902
  const placed = step(block.type === "paragraph" ? {
29399
29903
  type: "insertParagraphs",
29400
29904
  story: caret.story,
@@ -29645,8 +30149,14 @@ const withoutMoveAnchors = (nodes) => {
29645
30149
  }
29646
30150
  return out;
29647
30151
  };
29648
- const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId }) => {
30152
+ const identifyClipboardParagraphs = (options) => identifyClipboardContent({
30153
+ ...options,
30154
+ controls: [],
30155
+ identifyLast: false
30156
+ }).map(({ paragraphs }) => paragraphs);
30157
+ const identifyClipboardContent = ({ document, paragraphs, controls, identifyLast, mode, firstBlockId }) => {
29649
30158
  const copy = cloneModel([...paragraphs]);
30159
+ const controlCopies = cloneModel([...controls]);
29650
30160
  let occupancy;
29651
30161
  const packageOccupancy = () => occupancy ??= packageIdOccupancy(document.package);
29652
30162
  const assignedIds = {
@@ -29710,7 +30220,7 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
29710
30220
  from: nextBlock,
29711
30221
  taken: (candidate) => {
29712
30222
  const key = formatParaId(candidate);
29713
- return blockIds.has(key) || packageOccupancy().paragraphs.has(key);
30223
+ return blockIds.has(key) || packageOccupancy().paragraphs.has(key) || (mode.reservedBlockIds?.has(key) ?? false);
29714
30224
  }
29715
30225
  }).at(0);
29716
30226
  if (fresh === void 0) return void 0;
@@ -29746,7 +30256,7 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
29746
30256
  };
29747
30257
  const remintedControls = /* @__PURE__ */ new WeakSet();
29748
30258
  const keptMarkers = [];
29749
- visit(copy, (value) => {
30259
+ visit([copy, controlCopies], (value) => {
29750
30260
  if ("keptCut" in value) keptMarkers.push(value);
29751
30261
  if ("type" in value && value.type === "inlineSdt" && "properties" in value && typeof value.properties === "object" && value.properties !== null && "id" in value.properties && typeof value.properties.id === "number") {
29752
30262
  value.properties.id = freshId(IDENTITY_SPACES.CONTROL, value.properties.id);
@@ -29775,7 +30285,7 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
29775
30285
  }));
29776
30286
  for (const [index, paragraph] of copy.entries()) {
29777
30287
  delete paragraph.paraId;
29778
- if (index === copy.length - 1) continue;
30288
+ if (index === copy.length - 1 && !identifyLast) continue;
29779
30289
  const id = freshBlock();
29780
30290
  if (id === void 0) return Result.err(new DocumentOpRefusal({
29781
30291
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
@@ -29784,7 +30294,10 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
29784
30294
  }));
29785
30295
  paragraph.paraId = id;
29786
30296
  }
29787
- return Result.ok(copy);
30297
+ return Result.ok({
30298
+ paragraphs: copy,
30299
+ controls: controlCopies
30300
+ });
29788
30301
  };
29789
30302
  /**
29790
30303
  * Direct and tracked joins choose paragraph properties from the same
@@ -30008,6 +30521,40 @@ const gapWithoutLeaves = (content, at, removed) => {
30008
30521
  * deletion), and the moved content goes in where the target stands once
30009
30522
  * the deletion is made. A target inside the range moves nothing.
30010
30523
  */
30524
+ /**
30525
+ * The note bodies a direct deletion pruned as it took their references away,
30526
+ * from its inverse: a move puts the references back at its target, so it
30527
+ * restores the bodies the deletion removed.
30528
+ */
30529
+ const noteBodyRestorations = (inverse) => inverse.flatMap((op) => op.type === DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS && (op.parts.footnotes !== void 0 || op.parts.endnotes !== void 0) ? [{
30530
+ type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
30531
+ expected: {
30532
+ ...op.expected.footnotes === void 0 ? {} : { footnotes: op.expected.footnotes },
30533
+ ...op.expected.endnotes === void 0 ? {} : { endnotes: op.expected.endnotes }
30534
+ },
30535
+ parts: {
30536
+ ...op.parts.footnotes === void 0 ? {} : { footnotes: op.parts.footnotes },
30537
+ ...op.parts.endnotes === void 0 ? {} : { endnotes: op.parts.endnotes }
30538
+ }
30539
+ }] : []);
30540
+ /**
30541
+ * The document with the note bodies of `restorations` back, and the ops that
30542
+ * put them back. Each restoration expects the note parts its own deletion
30543
+ * left, so they undo the deletions newest first.
30544
+ */
30545
+ const withNoteBodiesRestored = (document, restorations) => {
30546
+ if (restorations.length === 0) return Result.ok({
30547
+ document,
30548
+ ops: []
30549
+ });
30550
+ const ops = restorations.toReversed();
30551
+ const restored = applyDocumentOps(document, ops);
30552
+ if (restored.isErr()) return Result.err(restored.error);
30553
+ return Result.ok({
30554
+ document: restored.value.document,
30555
+ ops
30556
+ });
30557
+ };
30011
30558
  const compileRangeMove = (document, { intent, mode, insert }) => {
30012
30559
  const range = selectedParagraphRuns(document, intent.from, intent.to);
30013
30560
  if (range.isErr()) return Result.err(range.error);
@@ -30124,25 +30671,12 @@ const compileRangeMove = (document, { intent, mode, insert }) => {
30124
30671
  if (applied.isErr()) return Result.err(applied.error);
30125
30672
  afterDeletion = applied.value.document;
30126
30673
  deletionOps.push(op);
30127
- for (const inverse of applied.value.inverse) if (inverse.type === DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS && (inverse.parts.footnotes !== void 0 || inverse.parts.endnotes !== void 0)) movedNoteBodies.push({
30128
- type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
30129
- expected: {
30130
- ...inverse.expected.footnotes === void 0 ? {} : { footnotes: inverse.expected.footnotes },
30131
- ...inverse.expected.endnotes === void 0 ? {} : { endnotes: inverse.expected.endnotes }
30132
- },
30133
- parts: {
30134
- ...inverse.parts.footnotes === void 0 ? {} : { footnotes: inverse.parts.footnotes },
30135
- ...inverse.parts.endnotes === void 0 ? {} : { endnotes: inverse.parts.endnotes }
30136
- }
30137
- });
30138
- }
30139
- if (movedNoteBodies.length > 0) {
30140
- const restorations = movedNoteBodies.toReversed();
30141
- const restored = applyDocumentOps(afterDeletion, restorations);
30142
- if (restored.isErr()) return Result.err(restored.error);
30143
- afterDeletion = restored.value.document;
30144
- deletionOps.push(...restorations);
30674
+ movedNoteBodies.push(...noteBodyRestorations(applied.value.inverse));
30145
30675
  }
30676
+ const restored = withNoteBodiesRestored(afterDeletion, movedNoteBodies);
30677
+ if (restored.isErr()) return Result.err(restored.error);
30678
+ afterDeletion = restored.value.document;
30679
+ deletionOps.push(...restored.value.ops);
30146
30680
  let target = intent.target;
30147
30681
  for (const op of logicalDeletions) {
30148
30682
  if (op.type === DOCUMENT_OP_TYPES.DELETE_RANGE && op.revision === void 0 && idKey(target.blockId) === idKey(op.from.blockId) && target.story === op.from.story && target.offset >= op.to.offset) {
@@ -30182,17 +30716,11 @@ const compileRangeMove = (document, { intent, mode, insert }) => {
30182
30716
  * with no range.
30183
30717
  */
30184
30718
  const withoutParagraphMoveAnchors = (paragraph) => Object.assign({}, paragraph, { content: asParagraphContent(withoutMoveAnchors(paragraph.content)) });
30185
- /** A block without move range markers, a table's cell paragraphs among them. */
30186
- const withoutBlockMoveAnchors = (block) => block.type === "paragraph" ? withoutParagraphMoveAnchors(block) : {
30187
- ...block,
30188
- rows: block.rows.map((row) => ({
30189
- ...row,
30190
- cells: row.cells.map((cell) => ({
30191
- ...cell,
30192
- content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? withoutBlockMoveAnchors(inner) : inner)
30193
- }))
30194
- }))
30195
- };
30719
+ /**
30720
+ * A block without move range markers, a table's cell paragraphs and a
30721
+ * container's among them.
30722
+ */
30723
+ const withoutBlockMoveAnchors = (block) => mapPastedBlockParagraphs(block, withoutParagraphMoveAnchors);
30196
30724
  /**
30197
30725
  * Blocks, tables among them, moved from a range to a target. The tables
30198
30726
  * standing wholly between the range's paragraphs are removed, the latest
@@ -30237,12 +30765,27 @@ const compileBlockMove = (document, { intent, mode, firstBlockId }) => {
30237
30765
  ops: [],
30238
30766
  selection: intent.target
30239
30767
  });
30240
- const covered = blockListAt(body.content, start.list).slice(start.index + 1, end.index).filter((block) => block.type === "table");
30768
+ const covered = blockListAt(body.content, start.list).slice(start.index + 1, end.index).filter((block) => block.type === "table" || block.type === "blockSdt" || block.type === "blockCustomXml" || block.type === "preservedBlock");
30241
30769
  const reserved = mode.reservedBlockIds === void 0 ? {} : { reservedBlockIds: mode.reservedBlockIds };
30242
30770
  const ops = [];
30243
30771
  let current = document;
30244
30772
  let currentMode = mode;
30773
+ const movedNoteBodies = [];
30245
30774
  for (const table of covered.toReversed()) {
30775
+ if (table.type !== "table") {
30776
+ const removed = removeContainerBlock({
30777
+ document: current,
30778
+ story,
30779
+ anchor: start.paragraph.paraId ?? "",
30780
+ block: table,
30781
+ mode: currentMode
30782
+ });
30783
+ if (removed.isErr()) return removed;
30784
+ ops.push(removed.value.op);
30785
+ current = removed.value.document;
30786
+ movedNoteBodies.push(...noteBodyRestorations(removed.value.inverse));
30787
+ continue;
30788
+ }
30246
30789
  const blockId = storyParagraphs({ content: [table] }).at(0)?.paragraph.paraId;
30247
30790
  if (blockId === void 0) return Result.err(new DocumentOpRefusal({
30248
30791
  reason: DOCUMENT_OP_REFUSAL_REASONS.MISSING_BLOCK_ID,
@@ -30265,11 +30808,16 @@ const compileBlockMove = (document, { intent, mode, firstBlockId }) => {
30265
30808
  if (applied.isErr()) return Result.err(applied.error);
30266
30809
  ops.push(...removed.value.ops);
30267
30810
  current = applied.value.document;
30811
+ if (mode.type === "editing") movedNoteBodies.push(...noteBodyRestorations(applied.value.inverse));
30268
30812
  currentMode = {
30269
30813
  ...modeAfterOps(current, currentMode),
30270
30814
  ...reserved
30271
30815
  };
30272
30816
  }
30817
+ const restored = withNoteBodiesRestored(current, movedNoteBodies);
30818
+ if (restored.isErr()) return Result.err(restored.error);
30819
+ current = restored.value.document;
30820
+ ops.push(...restored.value.ops);
30273
30821
  const moved = compileRangeMove(current, {
30274
30822
  intent: range,
30275
30823
  mode: currentMode,
@@ -30286,7 +30834,8 @@ const compileBlockMove = (document, { intent, mode, firstBlockId }) => {
30286
30834
  ...insertMode,
30287
30835
  ...reserved
30288
30836
  },
30289
- ...firstBlockId === void 0 ? {} : { firstBlockId }
30837
+ ...firstBlockId === void 0 ? {} : { firstBlockId },
30838
+ ...mode.type === "editing" ? { moved: true } : {}
30290
30839
  })
30291
30840
  });
30292
30841
  if (moved.isErr()) return moved;
@@ -30385,7 +30934,7 @@ const beginTrackedInsertionCompilation = ({ document, count, reservedBlockIds })
30385
30934
  }
30386
30935
  };
30387
30936
  };
30388
- const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting = TYPED_TEXT_FORMATTING.CARET, replacementFormattingDocument }) => {
30937
+ const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting = TYPED_TEXT_FORMATTING.CARET, replacementFormattingDocument, moved }) => {
30389
30938
  if (firstBlockId !== void 0 && (!Number.isInteger(firstBlockId) || firstBlockId < 1 || firstBlockId > 2147483648)) return Result.err(new DocumentOpRefusal({
30390
30939
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
30391
30940
  message: "The pasted block identity allocator is exhausted or invalid.",
@@ -30426,7 +30975,8 @@ const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting
30426
30975
  case "pasteBlocks": return compileBlockPaste(document, {
30427
30976
  intent,
30428
30977
  mode,
30429
- ...firstBlockId === void 0 ? {} : { firstBlockId }
30978
+ ...firstBlockId === void 0 ? {} : { firstBlockId },
30979
+ ...moved === void 0 ? {} : { moved }
30430
30980
  });
30431
30981
  case "replaceFragment": {
30432
30982
  if (intent.paragraphs.length === 0) return compileEditorIntent(document, {
@@ -36996,12 +37546,6 @@ const groupInsertionRuns = (operations, insertionPositionOf, keepsGap = () => fa
36996
37546
  * the document agree on every paragraph, table and note it keeps.
36997
37547
  */
36998
37548
  const REVISION_KEY_PREFIX = `${IDENTITY_SPACES.REVISION}:`;
36999
- /** Every revision id a story's content carries, in document order. */
37000
- const storyRevisionIds = (document, story) => {
37001
- const body = findStoryBody$1(document, story);
37002
- if (body === void 0) return [];
37003
- return [...new Set(identityKeysIn(body.content).flatMap((key) => key.startsWith(REVISION_KEY_PREFIX) ? [Number(key.slice(REVISION_KEY_PREFIX.length))] : []))];
37004
- };
37005
37549
  const isPlainRecord = (value) => typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
37006
37550
  /**
37007
37551
  * `value` with `edit` applied to every plain record, bottom up, copying only
@@ -37230,26 +37774,54 @@ const withoutParagraphIds = (document, minted) => {
37230
37774
  package: pkg
37231
37775
  };
37232
37776
  };
37233
- /**
37234
- * `document` with every revision resolved by `decision`, story by story. A
37235
- * story the resolution of an earlier one removed (a note whose every
37236
- * reference went) is not read again.
37237
- */
37238
- const resolvedDocumentView = (document, decision) => {
37777
+ const readResolvedDocument = ({ document, decision, purpose }) => {
37778
+ const pkg = document.package;
37779
+ const body = pkg.document;
37780
+ const known = purpose === "markup-view" && knownToMeetContract(document);
37781
+ if (purpose === "markup-view" && (decision === REVISION_DECISIONS.ACCEPT || decision === REVISION_DECISIONS.REJECT) && (known || body.sections === void 0) && (body.comments?.length ?? 0) === 0 && (pkg.headers?.size ?? 0) === 0 && (pkg.footnotes?.length ?? 0) === 0 && (pkg.footers?.size ?? 0) === 0 && (pkg.endnotes?.length ?? 0) === 0) {
37782
+ const view = resolveIndependentTextParagraphs(body, decision);
37783
+ if (view !== void 0) return {
37784
+ document: view.body === body ? document : {
37785
+ ...document,
37786
+ package: {
37787
+ ...pkg,
37788
+ document: view.body
37789
+ }
37790
+ },
37791
+ ...view.changes.length > 0 ? { independentInline: view.changes } : {},
37792
+ unresolved: []
37793
+ };
37794
+ }
37795
+ const revisionIdsByContent = /* @__PURE__ */ new Map();
37796
+ const storyRevisionIds = (current, story) => {
37797
+ const content = findStoryBody$1(current, story)?.content;
37798
+ if (content === void 0) return [];
37799
+ const cached = revisionIdsByContent.get(content);
37800
+ if (cached !== void 0) return cached;
37801
+ const ids = /* @__PURE__ */ new Set();
37802
+ for (const key of identityKeysIn(content)) if (key.startsWith(REVISION_KEY_PREFIX)) ids.add(Number(key.slice(REVISION_KEY_PREFIX.length)));
37803
+ const revisionIds = [...ids];
37804
+ revisionIdsByContent.set(content, revisionIds);
37805
+ return revisionIds;
37806
+ };
37239
37807
  const stories = documentStories(document);
37240
37808
  const revised = stories.filter((story) => storyRevisionIds(document, story).length > 0);
37241
37809
  if (revised.length === 0) return {
37242
37810
  document,
37243
37811
  unresolved: []
37244
37812
  };
37245
- const identified = withParagraphIds(withDistinctRevisionIds(document));
37813
+ const identified = known ? {
37814
+ document,
37815
+ minted: /* @__PURE__ */ new Map()
37816
+ } : withParagraphIds(withDistinctRevisionIds(document));
37246
37817
  const closed = withClosingParagraphs(identified.document, revised);
37247
37818
  let current = closed.document;
37248
37819
  const unresolved = [];
37820
+ const applyOps = purpose === "markup-view" ? applyMarkupViewOps : applyDocumentOps;
37249
37821
  for (const story of stories) {
37250
37822
  const revisionIds = storyRevisionIds(current, story);
37251
37823
  if (revisionIds.length === 0) continue;
37252
- const resolved = applyDocumentOps(current, [{
37824
+ const resolved = applyOps(current, [{
37253
37825
  type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
37254
37826
  story,
37255
37827
  revisionIds,
@@ -37266,11 +37838,11 @@ const resolvedDocumentView = (document, decision) => {
37266
37838
  for (const paraId of closed.closing.keys()) minted.set(paraId, void 0);
37267
37839
  let resolvedDocument = withoutParagraphIds(withoutBareClosingParagraphs(current, closed.closing), minted);
37268
37840
  for (const story of unresolved) {
37269
- const body = findStoryBody$1(document, story);
37270
- if (body !== void 0) resolvedDocument = replaceStoryBody({
37841
+ const authored = findStoryBody$1(document, story);
37842
+ if (authored !== void 0) resolvedDocument = replaceStoryBody({
37271
37843
  document: resolvedDocument,
37272
37844
  story,
37273
- body
37845
+ body: authored
37274
37846
  });
37275
37847
  }
37276
37848
  return {
@@ -37278,8 +37850,24 @@ const resolvedDocumentView = (document, decision) => {
37278
37850
  unresolved
37279
37851
  };
37280
37852
  };
37853
+ /**
37854
+ * `document` with every revision resolved by `decision`, story by story. A
37855
+ * story the resolution of an earlier one removed (a note whose every
37856
+ * reference went) is not read again.
37857
+ */
37858
+ const resolvedDocumentView = (document, decision) => readResolvedDocument({
37859
+ document,
37860
+ decision,
37861
+ purpose: "apply"
37862
+ });
37863
+ /** Resolve a markup display, keeping paragraphs before pending table receivers. */
37864
+ const resolvedMarkupDocumentView = (document, decision) => readResolvedDocument({
37865
+ document,
37866
+ decision,
37867
+ purpose: "markup-view"
37868
+ });
37281
37869
  // src/ops/documentOps.ts
37282
37870
  const storyBody = storyBody$1;
37283
37871
  const findStoryBody = findStoryBody$1;
37284
37872
  const sameStory = sameStory$2;
37285
- export { BATCH_ANNOTATION_KINDS, BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DEFAULT_ID_BLOCK_SIZES, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, EXCLUSIVE_PARTS, ID_KIND_LIMITS, ID_LEASE_KINDS, ID_LEASE_REFUSAL_REASONS, INHERIT_RUN_PROPS, IdLeaseRefusal, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, TYPED_TEXT_FORMATTING, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyBatch, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, beginTrackedInsertionCompilation, blockControlHolding, captureDocumentOp, captureStoryParts, combineEditEffects, combineEdits, combineRecordedRevisions, commentAnchorSequence, commentDocumentIssue, commentReferenceOffsets, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorParagraphGroupsThroughTextBoxes, editorPositionAtPhysicalPosition, finalBreakCarrier, findStoryBody, formatParaId, formattingEquals, freshCommentId, freshLeasedIds, groupInsertionRuns, idKey, idLeaseHolds, idLeaseRemaining, inlineLeafSpans, introducedDocumentIds, introducedIds, inverseMeetingDocument, isBlockBoundary, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isKeptCut, isKeptCutPiece, isTextOnlyRun, joinPropertyChangeLink, leasedIdCensus, locateParagraphInBlockList, locateParagraphThroughTextBoxes, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteDeletionOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, orphanRootCommentIds, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphHoldsContent, paragraphHoldsContentOnceAccepted, paragraphIdsIn, paragraphKeptCutsFromChanges, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphPropertySnapshotToken, paragraphStatesItsFormatting, paragraphVisibleText, paragraphsThroughTextBoxes, parseDocumentBatch, pendingSuggestionIdsIn, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, planWholeParagraphReplacement, preservedCommentRangeMarkersAt, reconcileDocumentPartRelationships, recordsCopyOrigin, registerParagraphPropertySnapshot, registerStatedParagraphFormatting, rejectCopyOriginAncestors, replaceStoryBody, resolveSectionChange, resolveSectionChanges, resolvedDocumentView, reviewFieldsOf, revisionIdDemand, revisionSpan, runsMergeable, sameStory, sectionPropertiesAt, sectionRejectProperties, sectionResolutionPatch, shiftCopyOriginAncestors, storyBody, storyLacksClosingParagraph, storyParagraphs, storyPartsOpOf, suggestedCommentIds, suggestionOwnersInStory, suggestionRevisionInfos, survivingComments, textBoxContentsIn, toOpEnvelope, transferParagraphPropertySnapshot, transformBatch, transformPosition, trimIdLease, tryTrackedInsertionGroup, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withParagraphCopies, withParagraphRenderings, withTextBoxesClosed, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };
37873
+ export { BATCH_ANNOTATION_KINDS, BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DEFAULT_ID_BLOCK_SIZES, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, EXCLUSIVE_PARTS, ID_KIND_LIMITS, ID_LEASE_KINDS, ID_LEASE_REFUSAL_REASONS, INHERIT_RUN_PROPS, IdLeaseRefusal, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, TYPED_TEXT_FORMATTING, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyBatch, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, beginTrackedInsertionCompilation, blockControlHolding, captureDocumentOp, captureStoryParts, combineEditEffects, combineEdits, combineRecordedRevisions, commentAnchorSequence, commentDocumentIssue, commentReferenceOffsets, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorParagraphGroupsThroughTextBoxes, editorPositionAtPhysicalPosition, finalBreakCarrier, findStoryBody, formatParaId, formattingEquals, freshCommentId, freshLeasedIds, groupInsertionRuns, idKey, idLeaseHolds, idLeaseRemaining, inlineLeafSpans, introducedDocumentIds, introducedIds, inverseMeetingDocument, isBlockBoundary, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isKeptCut, isKeptCutPiece, isTextOnlyRun, joinPropertyChangeLink, leasedIdCensus, locateParagraphInBlockList, locateParagraphThroughTextBoxes, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteDeletionOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, orphanRootCommentIds, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphHoldsContent, paragraphHoldsContentOnceAccepted, paragraphIdsIn, paragraphKeptCutsFromChanges, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphPropertySnapshotToken, paragraphStatesItsFormatting, paragraphVisibleText, paragraphsThroughTextBoxes, parseDocumentBatch, pendingSuggestionIdsIn, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, planWholeParagraphReplacement, preservedCommentRangeMarkersAt, reconcileDocumentPartRelationships, recordsCopyOrigin, registerParagraphPropertySnapshot, registerStatedParagraphFormatting, rejectCopyOriginAncestors, replaceStoryBody, resolveSectionChange, resolveSectionChanges, resolvedDocumentView, resolvedMarkupDocumentView, reviewFieldsOf, revisionIdDemand, revisionSpan, runsMergeable, sameStory, sectionPropertiesAt, sectionRejectProperties, sectionResolutionPatch, shiftCopyOriginAncestors, storyBody, storyLacksClosingParagraph, storyParagraphs, storyPartsOpOf, suggestedCommentIds, suggestionOwnersInStory, suggestionRevisionInfos, survivingComments, textBoxContentsIn, toOpEnvelope, transferParagraphPropertySnapshot, transformBatch, transformPosition, trimIdLease, tryTrackedInsertionGroup, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withParagraphCopies, withParagraphRenderings, withTextBoxesClosed, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };