@stll/docx-core 0.44.0 → 0.45.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.
@@ -512,6 +512,20 @@ const sharedIdentityCensus = censusWalker(ownIdentityKeys, "shared");
512
512
  const CONTENT_CONTROL_STACK = "contentControls";
513
513
  const ownReservedKeys = (entries, { heldBy }) => {
514
514
  const keys = [];
515
+ if (heldBy === "keptCut") {
516
+ const holders = fieldOf(entries, "holders");
517
+ if (typeof holders === "object" && holders !== null) for (const side of ["before", "after"]) {
518
+ const id = Reflect.get(holders, side);
519
+ if (typeof id === "number") keys.push(slotKey({
520
+ space: IDENTITY_SPACES.REVISION,
521
+ id
522
+ }));
523
+ }
524
+ return {
525
+ keys,
526
+ shareable: true
527
+ };
528
+ }
515
529
  if (heldBy === "deferredRemove") {
516
530
  const blockers = fieldOf(entries, "blockers");
517
531
  if (Array.isArray(blockers)) {
@@ -5301,39 +5315,102 @@ const wellFormedRanges = ({ contents, order, relocated }) => {
5301
5315
  return changed;
5302
5316
  };
5303
5317
  // src/ops/keptCut.ts
5318
+ /**
5319
+ * The cut a kept range marker stands in (`KeptCut`): review state a
5320
+ * resolution records on a marker it kept from removed content and could not
5321
+ * place inside a piece of the record that content cut.
5322
+ */
5304
5323
  const carriesKeptCut = (node) => isBoundary(node);
5324
+ const isKeptCutPiece = (value) => value === "before" || value === "after" || value === "both";
5325
+ const keptCutHolders = ({ before, after }) => {
5326
+ if (before === void 0) return after === void 0 ? void 0 : { after };
5327
+ return after === void 0 ? { before } : {
5328
+ before,
5329
+ after
5330
+ };
5331
+ };
5332
+ /** The side `holders` name. */
5333
+ const pieceOf = (holders) => {
5334
+ if (holders === void 0) return void 0;
5335
+ if (holders.scope === "seam" || holders.before !== void 0 && holders.after !== void 0) return "both";
5336
+ return holders.before === void 0 ? "after" : "before";
5337
+ };
5338
+ /** Retain the seam scope when its pending holders change. */
5339
+ const withHolderScope = (holders, scope) => holders === void 0 || scope === void 0 ? holders : {
5340
+ ...holders,
5341
+ scope
5342
+ };
5343
+ /** `cut` with `holders`, or with none. */
5344
+ const cutHeldBy = (cut, holders) => holders === void 0 ? { keptFrom: cut.keptFrom } : {
5345
+ keptFrom: cut.keptFrom,
5346
+ holders
5347
+ };
5305
5348
  /**
5306
5349
  * `node` marked as standing in `cut`, when it is a range marker. A marker
5307
5350
  * already standing in a cut keeps the revision it was first kept from and
5308
- * the piece first named for it: whichever order kept it and then floated it
5309
- * with another removal's seam, it records the same cut.
5351
+ * the holders first named for it: whichever order kept it and then floated
5352
+ * it with another removal's seam, it records the same cut.
5310
5353
  */
5311
5354
  const withKeptCut = (node, cut) => {
5312
5355
  if (!carriesKeptCut(node)) return node;
5313
5356
  const known = node.keptCut;
5314
5357
  if (known === void 0) return Object.assign({}, node, { keptCut: cut });
5315
- if (known.piece !== void 0 || cut.piece === void 0) return node;
5316
- return Object.assign({}, node, { keptCut: {
5317
- ...known,
5318
- piece: cut.piece
5319
- } });
5358
+ if (known.holders !== void 0 || cut.holders === void 0) return node;
5359
+ return Object.assign({}, node, { keptCut: cutHeldBy(known, cut.holders) });
5320
5360
  };
5321
5361
  /**
5322
- * `node` with every marked range marker it stands for naming `piece` as the
5323
- * side whose record is a piece of its cut, keeping what the resolution
5324
- * recorded per marker. An unmarked marker stays unmarked, and one already
5325
- * naming a piece keeps it.
5362
+ * `node` with every marked range marker it stands for naming `holders` as
5363
+ * the pending changes beside it holding a piece of its cut, keeping what the
5364
+ * resolution recorded per marker. An unmarked marker stays unmarked, and one
5365
+ * already naming holders keeps them.
5326
5366
  */
5327
- const withKeptCutPieceRecorded = (node, piece, known) => changeStandingMarkers(node, keepingRecord((marker) => carriesKeptCut(marker) && marker.keptCut !== void 0 ? withKeptCut(marker, {
5328
- ...marker.keptCut,
5329
- piece
5330
- }) : marker, known));
5331
- /** `node` with every marker it stands for naming no side as its cut's piece. */
5367
+ const withKeptCutHoldersRecorded = (node, holders, known) => changeStandingMarkers(node, keepingRecord((marker) => carriesKeptCut(marker) && marker.keptCut !== void 0 ? withKeptCut(marker, cutHeldBy(marker.keptCut, holders)) : marker, known));
5368
+ /** Whether all markers in this record name the revision on the given side. */
5369
+ const keptCutHeldBy = (node, { side, id }) => {
5370
+ if (node.type === "deletion") return node.content.length > 0 && node.content.every((child) => keptCutHeldBy(child, {
5371
+ side,
5372
+ id
5373
+ }));
5374
+ return carriesKeptCut(node) && node.keptCut?.holders?.[side] === id;
5375
+ };
5376
+ /** Move a cut's holder to the revision taking its join. */
5377
+ const withKeptCutHolderHandedOver = (node, { side, from, to }, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5378
+ if (!carriesKeptCut(marker)) return marker;
5379
+ const cut = marker.keptCut;
5380
+ const holders = cut?.holders;
5381
+ if (cut === void 0 || holders?.[side] !== from) return marker;
5382
+ const next = side === "before" ? {
5383
+ ...holders,
5384
+ before: to
5385
+ } : {
5386
+ ...holders,
5387
+ after: to
5388
+ };
5389
+ return Object.assign({}, marker, { keptCut: cutHeldBy(cut, next) });
5390
+ }, known));
5391
+ /** `node` with every marker it stands for naming no holder of its cut. */
5332
5392
  const withKeptCutPieceConsumed = (node, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5333
- if (!carriesKeptCut(marker) || marker.keptCut?.piece === void 0) return marker;
5334
- const { piece: _consumed, ...cut } = marker.keptCut;
5335
- return Object.assign({}, marker, { keptCut: cut });
5393
+ if (!carriesKeptCut(marker) || marker.keptCut?.holders === void 0) return marker;
5394
+ return Object.assign({}, marker, { keptCut: cutHeldBy(marker.keptCut, void 0) });
5336
5395
  }, known));
5396
+ /** Point a cut at the copies or successors of its holders. */
5397
+ const remapKeptCutHolders = (cut, successor) => {
5398
+ const holders = cut.holders;
5399
+ if (holders === void 0) return cut;
5400
+ const before = holders.before === void 0 ? void 0 : successor(holders.before);
5401
+ const after = holders.after === void 0 ? void 0 : successor(holders.after);
5402
+ if (before === holders.before && after === holders.after) return cut;
5403
+ return cutHeldBy(cut, withHolderScope(keptCutHolders({
5404
+ before,
5405
+ after
5406
+ }), holders.scope));
5407
+ };
5408
+ /** Redirect holder references on a marker when its revisions are reminted. */
5409
+ const withKeptCutHoldersRenamed = (node, successor) => {
5410
+ if (!carriesKeptCut(node) || node.keptCut === void 0) return node;
5411
+ const cut = remapKeptCutHolders(node.keptCut, successor);
5412
+ return cut === node.keptCut ? node : Object.assign({}, node, { keptCut: cut });
5413
+ };
5337
5414
  /** The earliest revision a marker `node` stands for was kept from. */
5338
5415
  const keptCutFrom = (node) => {
5339
5416
  if (node.type === "deletion") return node.content.flatMap((child) => keptCutFrom(child) ?? []).toSorted().at(0);
@@ -5348,7 +5425,7 @@ const keptCutPiece = (node) => {
5348
5425
  const pieces = new Set(node.content.map(keptCutPiece));
5349
5426
  return pieces.size === 1 ? pieces.values().next().value : void 0;
5350
5427
  }
5351
- return carriesKeptCut(node) ? node.keptCut?.piece : void 0;
5428
+ return carriesKeptCut(node) ? pieceOf(node.keptCut?.holders) : void 0;
5352
5429
  };
5353
5430
  /**
5354
5431
  * Whether `node` stands in a kept cut: a marked range marker, or a pending
@@ -5413,7 +5490,7 @@ const withKeptCutsFromChanges = (nodes, writtenOnChange) => {
5413
5490
  const marked = withKeptCutsFromChanges(children, writtenOnChange);
5414
5491
  return marked === children ? node : rebuildNode(node, [...marked]);
5415
5492
  });
5416
- const mark = (from, step, { keptFrom, count }, piece) => {
5493
+ const mark = (from, step, { keptFrom, count }, holders) => {
5417
5494
  let boundaries = 0;
5418
5495
  for (let index = from;; index += step) {
5419
5496
  const node = out[index];
@@ -5422,21 +5499,21 @@ const withKeptCutsFromChanges = (nodes, writtenOnChange) => {
5422
5499
  if (boundaries > count) return;
5423
5500
  out[index] = withKeptCuts(node, {
5424
5501
  keptFrom,
5425
- piece
5502
+ holders
5426
5503
  });
5427
5504
  }
5428
5505
  };
5429
5506
  for (const [index, node] of nodes.entries()) {
5430
5507
  const joins = isTrackedWrapper(node) ? node.resolutionJoins : void 0;
5431
5508
  const kept = joins === void 0 ? void 0 : writtenOnChange(joins)?.change;
5432
- if (joins === void 0 || kept === void 0) continue;
5509
+ if (joins === void 0 || kept === void 0 || !isTrackedWrapper(node)) continue;
5433
5510
  const count = kept.keptCount ?? Number.POSITIVE_INFINITY;
5434
5511
  const named = {
5435
5512
  keptFrom: kept.keptFrom,
5436
5513
  count
5437
5514
  };
5438
- if (joins.before > 0) mark(index - 1, -1, named, "after");
5439
- if (joins.after > 0) mark(index + 1, 1, named, "before");
5515
+ if (joins.before > 0) mark(index - 1, -1, named, { after: node.info.id });
5516
+ if (joins.after > 0) mark(index + 1, 1, named, { before: node.info.id });
5440
5517
  }
5441
5518
  const keptGroups = (node) => {
5442
5519
  const joins = node !== void 0 && isTrackedWrapper(node) ? node.resolutionJoins : void 0;
@@ -5466,40 +5543,57 @@ const withKeptCutsFromChanges = (nodes, writtenOnChange) => {
5466
5543
  const afterSeams = new Set(after.map(seamOf));
5467
5544
  const across = before.find((group) => afterSeams.has(seamOf(group)));
5468
5545
  const group = across ?? after.at(0) ?? before.at(0);
5546
+ const beforeId = changeAtEdge(start === 0 ? void 0 : out[start - 1], "end");
5547
+ const afterId = changeAtEdge(out[end], "start");
5469
5548
  if (group !== void 0) {
5470
- let piece = "before";
5471
- if (across !== void 0) piece = "both";
5472
- else if (after.includes(group)) piece = "after";
5473
5549
  const cut = {
5474
5550
  keptFrom: group.keptFrom,
5475
5551
  count: group.keptCount ?? Number.POSITIVE_INFINITY
5476
5552
  };
5477
- if (piece === "after") mark(end - 1, -1, cut, piece);
5478
- else mark(start, 1, cut, piece);
5553
+ if (across !== void 0 && beforeId !== void 0 && afterId !== void 0) mark(start, 1, cut, {
5554
+ before: beforeId,
5555
+ after: afterId
5556
+ });
5557
+ else if (after.includes(group) && afterId !== void 0) mark(end - 1, -1, cut, { after: afterId });
5558
+ else if (beforeId !== void 0) mark(start, 1, cut, { before: beforeId });
5479
5559
  }
5480
5560
  start = end;
5481
5561
  }
5482
5562
  return out.every((node, index) => node === nodes[index]) ? nodes : out;
5483
5563
  };
5484
5564
  /** {@link withKeptCutsFromChanges} over a paragraph's content. */
5485
- const paragraphKeptCutsFromChanges = (content, writtenOnChange) => asParagraphContent(withKeptCutsFromChanges(content, writtenOnChange));
5565
+ const paragraphKeptCutsFromChanges = (content, writtenOnChange, legacyPiece) => {
5566
+ const cuts = withKeptCutsFromChanges(content, writtenOnChange);
5567
+ return asParagraphContent(legacyPiece === void 0 ? cuts : settleKeptCuts(cuts, { legacyPiece }));
5568
+ };
5486
5569
  /** How many range boundaries a kept marker `node` stands for. */
5487
5570
  const keptBoundaryCount$1 = (node) => node.type === "deletion" ? node.content.reduce((sum, child) => sum + keptBoundaryCount$1(child), 0) : 1;
5488
- const KEPT_CUT_PIECES = {
5571
+ const KEPT_CUT_HOLDER_FIELDS = {
5489
5572
  before: true,
5490
5573
  after: true,
5491
- both: true
5574
+ scope: true
5492
5575
  };
5493
5576
  const KEPT_CUT_FIELDS = {
5494
5577
  keptFrom: true,
5495
- piece: true
5578
+ holders: true
5579
+ };
5580
+ const isRevisionId = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2147483647;
5581
+ /** Whether `holders` names a revision on one side of a marker, or both. */
5582
+ const isKeptCutHolders = (holders) => {
5583
+ if (typeof holders !== "object" || holders === null || Array.isArray(holders)) return false;
5584
+ const keys = Object.keys(holders);
5585
+ return (Object.hasOwn(holders, "before") || Object.hasOwn(holders, "after")) && keys.every((key) => {
5586
+ if (!Object.hasOwn(KEPT_CUT_HOLDER_FIELDS, key)) return false;
5587
+ const value = Reflect.get(holders, key);
5588
+ return key === "scope" ? value === "seam" : isRevisionId(value);
5589
+ });
5496
5590
  };
5497
5591
  /**
5498
5592
  * Whether `cut` is a well-formed kept cut: exactly its fields, kept from a
5499
- * dated revision, naming one side as its piece if any. The contract and the
5500
- * review history reader share it.
5593
+ * dated revision, naming the revisions holding its piece if any. The
5594
+ * contract and the review history reader share it.
5501
5595
  */
5502
- const isKeptCut = (cut) => typeof cut === "object" && cut !== null && !Array.isArray(cut) && Object.keys(cut).every((key) => Object.hasOwn(KEPT_CUT_FIELDS, key)) && "keptFrom" in cut && typeof cut.keptFrom === "string" && (!("piece" in cut) || typeof cut.piece === "string" && Object.hasOwn(KEPT_CUT_PIECES, cut.piece));
5596
+ const isKeptCut = (cut) => typeof cut === "object" && cut !== null && !Array.isArray(cut) && Object.keys(cut).every((key) => Object.hasOwn(KEPT_CUT_FIELDS, key)) && "keptFrom" in cut && typeof cut.keptFrom === "string" && (!("holders" in cut) || isKeptCutHolders(cut.holders));
5503
5597
  const hasValidKeptCuts = (nodes) => nodes.every((node) => {
5504
5598
  if (carriesKeptCut(node) && node.keptCut !== void 0) return isKeptCut(node.keptCut);
5505
5599
  return hasValidKeptCuts(childNodes(node) ?? []);
@@ -5517,29 +5611,29 @@ const hasValidKeptCutsInBlocks = (blocks) => blocks.every((block) => {
5517
5611
  default: return !("keptCut" in block);
5518
5612
  }
5519
5613
  });
5520
- /**
5521
- * `node` with every marker it stands for naming a side as its cut's piece
5522
- * keeping that name only where `facing` says the change that took its seam
5523
- * still stands, keeping what the resolution recorded per marker.
5524
- */
5525
- const withKeptCutPiecesFacing = (node, facing, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5526
- if (!carriesKeptCut(marker) || marker.keptCut?.piece === void 0) return marker;
5527
- if (facing[marker.keptCut.piece]) return marker;
5528
- const { piece: _consumed, ...cut } = marker.keptCut;
5529
- return Object.assign({}, marker, { keptCut: cut });
5530
- }, known));
5531
- /**
5532
- * Whether a pending change stands at `node`'s `edge`: the node itself, or
5533
- * one at that edge of the records it holds, whose resolution can still let
5534
- * the pieces across from it meet.
5535
- */
5536
- const pendingAtEdge = (node, edge) => {
5537
- if (node === void 0) return false;
5538
- if (isTrackedWrapper(node)) return true;
5614
+ /** The id of the pending change at a record edge. */
5615
+ const changeAtEdge = (node, edge) => {
5616
+ if (node === void 0) return void 0;
5617
+ if (isTrackedWrapper(node)) return node.info.id;
5539
5618
  const children = childNodes(node);
5540
- if (children === void 0) return false;
5541
- return pendingAtEdge(edge === "start" ? children.at(0) : children.at(-1), edge);
5542
- };
5619
+ return changeAtEdge(edge === "start" ? children?.at(0) : children?.at(-1), edge);
5620
+ };
5621
+ /** Keep each holder only while that revision is still at the facing edge. */
5622
+ const withFacingHolders = (node, facing, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5623
+ if (!carriesKeptCut(marker)) return marker;
5624
+ const cut = marker.keptCut;
5625
+ const holders = cut?.holders;
5626
+ if (cut === void 0 || holders === void 0) return marker;
5627
+ const keep = (side) => facing[side] === KEPT_CUT_EDGES.UNSETTLED || facing[side] === holders[side];
5628
+ const before = keep("before") ? holders.before : void 0;
5629
+ const after = keep("after") ? holders.after : void 0;
5630
+ if (before === holders.before && after === holders.after) return marker;
5631
+ const facingHolders = withHolderScope(keptCutHolders({
5632
+ before,
5633
+ after
5634
+ }), holders.scope);
5635
+ return Object.assign({}, marker, { keptCut: cutHeldBy(cut, facingHolders) });
5636
+ }, known));
5543
5637
  /** Whether the piece a marker names goes with the records on the sides `gone`. */
5544
5638
  const pieceGoes = (piece, gone) => {
5545
5639
  switch (piece) {
@@ -5557,9 +5651,9 @@ const pieceGoes = (piece, gone) => {
5557
5651
  * leaves them.
5558
5652
  */
5559
5653
  const withKeptCutBesideRemoved = (node, { gone, known }) => changeStandingMarkers(node, keepingRecord((marker) => {
5560
- if (!carriesKeptCut(marker) || marker.keptCut?.piece === void 0) return marker;
5561
- const { piece, ...cut } = marker.keptCut;
5562
- return pieceGoes(piece, gone) ? Object.assign({}, marker, { keptCut: cut }) : marker;
5654
+ if (!carriesKeptCut(marker) || marker.keptCut === void 0) return marker;
5655
+ const piece = pieceOf(marker.keptCut.holders);
5656
+ return piece !== void 0 && pieceGoes(piece, gone) ? Object.assign({}, marker, { keptCut: cutHeldBy(marker.keptCut, void 0) }) : marker;
5563
5657
  }, known));
5564
5658
  /** What meets a list's edge from outside, as kept cuts at that edge read it. */
5565
5659
  const KEPT_CUT_EDGES = Object.freeze({
@@ -5571,33 +5665,12 @@ const KEPT_CUT_EDGES = Object.freeze({
5571
5665
  * seam, so it holds no piece a marker names.
5572
5666
  */
5573
5667
  PENDING_MARK: "pendingMark",
5574
- /** A pending tracked change, which can hold a piece a marker names. */
5575
- PENDING_CHANGE: "pendingChange",
5576
5668
  /**
5577
5669
  * Not known yet: the edge of a nested list, which the paragraph's own
5578
5670
  * settlement reads once the joins stand. Its markers keep what they have.
5579
5671
  */
5580
5672
  UNSETTLED: "unsettled"
5581
5673
  });
5582
- /** Whether a cut at an edge waits there, and whether a piece named there stands. */
5583
- const EDGE_READING = {
5584
- nothing: {
5585
- waits: false,
5586
- holdsPiece: false
5587
- },
5588
- pendingMark: {
5589
- waits: true,
5590
- holdsPiece: false
5591
- },
5592
- pendingChange: {
5593
- waits: true,
5594
- holdsPiece: true
5595
- },
5596
- unsettled: {
5597
- waits: true,
5598
- holdsPiece: true
5599
- }
5600
- };
5601
5674
  /**
5602
5675
  * `nodes` with the kept cuts that wait on nothing cleared, at every depth: a
5603
5676
  * run of kept markers records its cut only while a pending change stands
@@ -5606,12 +5679,12 @@ const EDGE_READING = {
5606
5679
  * holding the run is no such change; resolving it keeps them again.
5607
5680
  * Whichever order resolved the rest, no cut outlives that change.
5608
5681
  */
5609
- const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), rebuilt, outside = {
5682
+ const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), legacyPiece, rebuilt, outside = {
5610
5683
  start: KEPT_CUT_EDGES.NOTHING,
5611
5684
  end: KEPT_CUT_EDGES.NOTHING
5612
5685
  } } = {}) => {
5613
5686
  let out;
5614
- const edgeOf = (node, edge) => pendingAtEdge(node, edge) ? KEPT_CUT_EDGES.PENDING_CHANGE : KEPT_CUT_EDGES.NOTHING;
5687
+ const edgeOf = (node, edge) => changeAtEdge(node, edge) ?? KEPT_CUT_EDGES.NOTHING;
5615
5688
  const pendingBefore = (index) => index === 0 ? outside.start : edgeOf(nodes[index - 1], "end");
5616
5689
  const pendingAfter = (index) => index === nodes.length - 1 ? outside.end : edgeOf(nodes[index + 1], "start");
5617
5690
  let start = 0;
@@ -5622,6 +5695,7 @@ const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), rebuilt,
5622
5695
  const children = childNodes(first);
5623
5696
  const settled = children === void 0 ? children : settleKeptCuts(children, {
5624
5697
  known,
5698
+ ...legacyPiece === void 0 ? {} : { legacyPiece },
5625
5699
  ...rebuilt === void 0 ? {} : { rebuilt },
5626
5700
  outside: {
5627
5701
  start: pendingBefore(start),
@@ -5643,16 +5717,25 @@ const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), rebuilt,
5643
5717
  if (node === void 0 || !isKeptBoundaryCarrier(node)) break;
5644
5718
  }
5645
5719
  const run = nodes.slice(start, end);
5646
- const before = EDGE_READING[pendingBefore(start)];
5647
- const after = EDGE_READING[pendingAfter(end - 1)];
5648
- const waiting = run.some((node) => node.type === "deletion") || before.waits || after.waits;
5649
- const facing = {
5650
- before: before.holdsPiece,
5651
- after: after.holdsPiece,
5652
- both: before.holdsPiece || after.holdsPiece
5653
- };
5720
+ const before = pendingBefore(start);
5721
+ const after = pendingAfter(end - 1);
5722
+ const waiting = run.some((node) => node.type === "deletion") || before !== KEPT_CUT_EDGES.NOTHING || after !== KEPT_CUT_EDGES.NOTHING;
5654
5723
  for (const [offset, node] of run.entries()) {
5655
- const settled = waiting ? withKeptCutPiecesFacing(node, facing, known) : withoutKeptCutsRecorded(node, known);
5724
+ let settled;
5725
+ if (legacyPiece === void 0) settled = waiting ? withFacingHolders(node, {
5726
+ before,
5727
+ after
5728
+ }, known) : withoutKeptCutsRecorded(node, known);
5729
+ else settled = changeStandingMarkers(node, (marker) => {
5730
+ if (!carriesKeptCut(marker) || marker.keptCut === void 0) return marker;
5731
+ const piece = legacyPiece(marker.keptCut);
5732
+ if (piece === void 0) return marker;
5733
+ const holders = keptCutHolders({
5734
+ before: piece !== "after" && typeof before === "number" ? before : void 0,
5735
+ after: piece !== "before" && typeof after === "number" ? after : void 0
5736
+ });
5737
+ return withKeptCut(marker, cutHeldBy(marker.keptCut, withHolderScope(holders, piece === "both" ? "seam" : void 0)));
5738
+ });
5656
5739
  if (settled === node) continue;
5657
5740
  out ??= [...nodes];
5658
5741
  out[start + offset] = settled;
@@ -8665,7 +8748,7 @@ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /*
8665
8748
  kind: "fresh",
8666
8749
  paragraphs: bindDeferredIdentities({
8667
8750
  before: after,
8668
- after: rebindPropertyChangeOwners({
8751
+ after: rebindParagraphMarkReferences({
8669
8752
  source: before,
8670
8753
  draft: after,
8671
8754
  freshened: rebindRetainedIdentities({
@@ -8681,24 +8764,51 @@ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /*
8681
8764
  };
8682
8765
  };
8683
8766
  /**
8684
- * A property change that belongs to a paragraph-mark deletion
8685
- * (`resolvesWith`) follows that deletion to the id freshening gave it.
8767
+ * Review provenance that refers to a paragraph mark follows its freshened
8768
+ * identity when the referring record is copied with it.
8686
8769
  */
8687
- const rebindPropertyChangeOwners = ({ source, draft, freshened, elsewhere }) => {
8770
+ const rebindParagraphMarkReferences = ({ source, draft, freshened, elsewhere }) => {
8688
8771
  const ownerInfo = ({ pPrMark }) => pPrMark?.kind === "del" ? pPrMark.info : pPrMark?.deletion?.info;
8689
8772
  const kept = /* @__PURE__ */ new Set();
8690
8773
  const moved = /* @__PURE__ */ new Map();
8774
+ const movedMarks = /* @__PURE__ */ new Map();
8775
+ const keptMarks = /* @__PURE__ */ new Set();
8691
8776
  for (const [index, paragraph] of draft.entries()) {
8777
+ const fresh = freshened.at(index) ?? panic("Freshening preserves each paragraph.");
8778
+ const oldId = paragraph.pPrMark?.info.id;
8779
+ const freshId = fresh.pPrMark?.info.id;
8780
+ if (oldId !== void 0 && freshId !== void 0) {
8781
+ if (oldId === freshId) keptMarks.add(oldId);
8782
+ else movedMarks.set(oldId, freshId);
8783
+ }
8692
8784
  const old = ownerInfo(paragraph);
8693
- const next = ownerInfo(freshened.at(index) ?? panic("Freshening preserves each paragraph."));
8785
+ const next = ownerInfo(fresh);
8694
8786
  if (old === void 0 || next === void 0) continue;
8695
8787
  if (old.id === next.id) kept.add(old.id);
8696
8788
  else moved.set(old.id, next.id);
8697
8789
  }
8698
- if (moved.size === 0) return freshened;
8790
+ if (moved.size === 0 && movedMarks.size === 0) return freshened;
8699
8791
  const previousOwners = /* @__PURE__ */ new Map();
8700
- for (const paragraph of source) for (const { info, resolvesWith } of paragraph.propertyChanges ?? []) if (resolvesWith !== void 0) previousOwners.set(info.id, resolvesWith);
8701
- return freshened.map((paragraph) => {
8792
+ const previousTakeovers = /* @__PURE__ */ new Map();
8793
+ for (const paragraph of source) {
8794
+ const mark = paragraph.pPrMark;
8795
+ if (mark?.takenOverMark !== void 0) previousTakeovers.set(mark.info.id, mark.takenOverMark);
8796
+ for (const { info, resolvesWith } of paragraph.propertyChanges ?? []) if (resolvesWith !== void 0) previousOwners.set(info.id, resolvesWith);
8797
+ }
8798
+ return freshened.map((fresh) => {
8799
+ const mark = fresh.pPrMark;
8800
+ const target = mark?.takenOverMark;
8801
+ const targetId = target === void 0 ? void 0 : movedMarks.get(target);
8802
+ const paragraph = mark === void 0 || target === void 0 || targetId === void 0 || previousTakeovers.get(mark.info.id) === target && (keptMarks.has(target) || elsewhere.has(slotKey({
8803
+ space: IDENTITY_SPACES.REVISION,
8804
+ id: target
8805
+ }))) ? fresh : {
8806
+ ...fresh,
8807
+ pPrMark: {
8808
+ ...mark,
8809
+ takenOverMark: targetId
8810
+ }
8811
+ };
8702
8812
  if (paragraph.propertyChanges === void 0) return paragraph;
8703
8813
  let changed = false;
8704
8814
  const propertyChanges = paragraph.propertyChanges.map((change) => {
@@ -9219,6 +9329,61 @@ const unchanged$3 = (document) => Result.ok({
9219
9329
  removed: []
9220
9330
  }
9221
9331
  });
9332
+ /**
9333
+ * The container's last paragraph, right after `last`, when its pending
9334
+ * deletion took `last`'s mark, along with the property change that belongs
9335
+ * to that mark's deletion.
9336
+ */
9337
+ const finalDeletionTakenFrom = ({ list, following, followerIndex, last }) => {
9338
+ const mark = last.pPrMark;
9339
+ if (following?.type !== "paragraph" || mark?.kind !== "del" || blockFollower(list, followerIndex).block !== void 0 || paragraphHoldsContentOnceAccepted(following)) return void 0;
9340
+ const change = following.propertyChanges?.find(({ resolvesWith }) => resolvesWith === mark.info.id);
9341
+ return change === void 0 ? void 0 : {
9342
+ final: following,
9343
+ change
9344
+ };
9345
+ };
9346
+ /**
9347
+ * The tracked deletion of `op`'s paragraphs and `final` together, once the
9348
+ * property change `final`'s deletion gave it is rejected. The records the
9349
+ * earlier deletion made on the marks and words stay as they are. A
9350
+ * suggestion takes back no change of another suggestion or an ordinary one,
9351
+ * as it folds into none.
9352
+ */
9353
+ const withFinalDeletionTakenBack = ({ document, op, applyOps, revision, final, change }) => {
9354
+ const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
9355
+ reason,
9356
+ message,
9357
+ opType: op.type
9358
+ }));
9359
+ if (final.paraId === void 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "The last paragraph has no id to delete it by.");
9360
+ if (takesOverOtherSuggestion(change, revision)) return refuse(DOCUMENT_OP_REFUSAL_REASONS.PENDING_PARAGRAPH_PROPERTY_CHANGE, "A suggestion cannot take back another pending paragraph property change.");
9361
+ const takenBack = applyOps(document, [{
9362
+ type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
9363
+ story: op.story,
9364
+ revisionIds: [change.info.id],
9365
+ decision: REVISION_DECISIONS.REJECT
9366
+ }]);
9367
+ if (takenBack.isErr()) return refuse(takenBack.error.reason, takenBack.error.message);
9368
+ const deleted = deleteBlocks({
9369
+ document: takenBack.value.document,
9370
+ op: {
9371
+ ...op,
9372
+ blockIds: [...op.blockIds, final.paraId]
9373
+ },
9374
+ applyOps
9375
+ });
9376
+ if (deleted.isErr()) return deleted;
9377
+ const { touched } = deleted.value;
9378
+ return Result.ok({
9379
+ ...deleted.value,
9380
+ inverse: [...deleted.value.inverse, ...takenBack.value.inverse],
9381
+ touched: {
9382
+ ...touched,
9383
+ modified: [.../* @__PURE__ */ new Set([...touched.modified, ...takenBack.value.touched.modified])]
9384
+ }
9385
+ });
9386
+ };
9222
9387
  const deleteBlocks = ({ document, op, applyOps }) => {
9223
9388
  const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
9224
9389
  reason,
@@ -9285,14 +9450,15 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9285
9450
  }
9286
9451
  });
9287
9452
  }
9288
- const broken = list[first.index - 1];
9289
- const takenOver = owner !== void 0 && terminal && op.move !== true && broken?.type === "paragraph" ? takenOverBreakRecords({
9453
+ const blockBefore = list[first.index - 1];
9454
+ const broken = blockBefore?.type === "paragraph" ? blockBefore : void 0;
9455
+ const takenOver = owner !== void 0 && terminal && op.move !== true && broken !== void 0 ? takenOverBreakRecords({
9290
9456
  broken,
9291
9457
  paragraphs: found.map(({ paragraph }) => paragraph),
9292
9458
  owner,
9293
9459
  held
9294
9460
  }) : void 0;
9295
- if (takenOver !== void 0) {
9461
+ if (takenOver !== void 0 && broken !== void 0) {
9296
9462
  const rejected = applyOps(document, [{
9297
9463
  type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
9298
9464
  story: op.story,
@@ -9301,12 +9467,44 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9301
9467
  }]);
9302
9468
  if (rejected.isErr()) return refuse(rejected.error.reason, rejected.error.message);
9303
9469
  const { document: retracted, inverse, touched } = rejected.value;
9304
- return Result.ok({
9470
+ if ((broken.propertyChanges?.length ?? 0) === 0) return Result.ok({
9305
9471
  document: retracted,
9306
9472
  inverse,
9307
9473
  touched
9308
9474
  });
9475
+ const survivor = storyParagraphs(storyBody$1(retracted, op.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(broken.paraId ?? ""))?.paragraph ?? panic("A taken-back insertion lost the paragraph it broke.");
9476
+ const { pPrMark: _addedMark, ...restyle } = reviewFieldsOf(broken);
9477
+ const kept = applyOps(retracted, [{
9478
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
9479
+ story: op.story,
9480
+ blockId: survivor.paraId ?? "",
9481
+ expected: reviewFieldsOf(survivor),
9482
+ review: survivor.pPrMark === void 0 ? restyle : {
9483
+ ...restyle,
9484
+ pPrMark: survivor.pPrMark
9485
+ }
9486
+ }]);
9487
+ if (kept.isErr()) return refuse(kept.error.reason, kept.error.message);
9488
+ return Result.ok({
9489
+ document: kept.value.document,
9490
+ inverse: [...kept.value.inverse, ...inverse],
9491
+ touched
9492
+ });
9309
9493
  }
9494
+ const takenFinal = finalDeletionTakenFrom({
9495
+ list,
9496
+ following,
9497
+ followerIndex,
9498
+ last: last.paragraph
9499
+ });
9500
+ const retiresBreakBefore = list[breakRetiredBefore(list, first.index)]?.type === "paragraph";
9501
+ if (op.revision !== void 0 && op.move !== true && takenFinal !== void 0 && retiresBreakBefore) return withFinalDeletionTakenBack({
9502
+ document,
9503
+ op,
9504
+ applyOps,
9505
+ revision: op.revision,
9506
+ ...takenFinal
9507
+ });
9310
9508
  const tableBoundary = following?.type === "table" ? paragraphTableRunInBoundary(last.paragraph, following) : void 0;
9311
9509
  const emptiedBeforeBlockedTable = tableBoundary?.type === "blocked" && (tableBoundary.reason === "review" || tableBoundary.reason === "section") && (endsWithParagraph || blockListEndsInParagraph(list));
9312
9510
  const trackedBeforeTable = op.revision !== void 0 && tableBoundary !== void 0 && (markBeforeTableResolves({
@@ -9454,11 +9652,13 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9454
9652
  const retired = retiredIndex === void 0 ? void 0 : list[retiredIndex];
9455
9653
  const trailing = [];
9456
9654
  let endFormatting = survivor.formatting;
9655
+ let propertySource = previous;
9457
9656
  let reviewed = affected;
9458
9657
  if (retiredIndex !== void 0 && retired?.type === "paragraph") {
9459
9658
  const ending = lastBlockPastBoundaries(list);
9460
- if (ending?.type === "paragraph" && givesProperties(list, retiredIndex) && !sameParagraphProperties(retired.formatting, ending.formatting)) {
9659
+ if (ending?.type === "paragraph" && (ending.propertyChanges?.length ?? 0) === 0 && givesProperties(list, retiredIndex) && !sameParagraphProperties(retired.formatting, ending.formatting)) {
9461
9660
  trailing.push(...paragraphsIn$5(list.slice(last.index + 1)));
9661
+ propertySource = retired;
9462
9662
  endFormatting = withMarkFormatting(paragraphPropertiesOf(retired.formatting), ending.formatting);
9463
9663
  }
9464
9664
  reviewed = [
@@ -9471,11 +9671,10 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9471
9671
  const endsContainer = trailing.at(-1) ?? (terminal ? last.paragraph : null);
9472
9672
  const losesMark = (paragraph) => paragraph !== endsContainer && !trailing.includes(paragraph);
9473
9673
  const joinsNext = new Set(reviewed.filter((paragraph) => losesMark(paragraph) && paragraph.sectionProperties === void 0 && (paragraph !== last.paragraph || following?.type === "paragraph") && (paragraph.pPrMark?.kind === "ins" || paragraph.pPrMark?.kind === "moveTo") && isOwnRecord(paragraph.pPrMark.info, revision)));
9474
- const finalTakeover = following?.type === "paragraph" && blockFollower(list, followerIndex).block === void 0 && paragraphHoldsContent(following) && !paragraphHoldsContentOnceAccepted(following) && (following.propertyChanges?.length ?? 0) > 0 && sameParagraphProperties(paragraphPropertiesOf(following.formatting), paragraphPropertiesOf(last.paragraph.formatting));
9475
- const keepsDeletedMark = (paragraph) => (markPendingDeletion(paragraph) || paragraph.pPrMark?.deletion !== void 0) && !(op.move === true && selected.includes(paragraph)) && !(finalTakeover && paragraph === last.paragraph);
9674
+ const keepsDeletedMark = (paragraph) => (markPendingDeletion(paragraph) || paragraph.pPrMark?.deletion !== void 0) && !(op.move === true && selected.includes(paragraph));
9476
9675
  const before = list[first.index - 1];
9477
9676
  const beforeInsertedTable = !(before?.type === "paragraph" && markGoes(before)) && following?.type === "table" && following.rows.length > 0 && following.rows.every((row) => row.structuralChange?.type === "tableRowInsertion");
9478
- const deletesAddedMark = (paragraph) => op.move !== true && losesMark(paragraph) && !joinsNext.has(paragraph) && (paragraph.pPrMark?.kind === "ins" || paragraph.pPrMark?.kind === "moveTo") && paragraph.pPrMark.deletion === void 0 && (!isOwnRecord(paragraph.pPrMark.info, revision) || paragraph.sectionProperties !== void 0 || beforeInsertedTable && paragraph === last.paragraph) && !(finalTakeover && paragraph === last.paragraph);
9677
+ const deletesAddedMark = (paragraph) => op.move !== true && losesMark(paragraph) && !joinsNext.has(paragraph) && (paragraph.pPrMark?.kind === "ins" || paragraph.pPrMark?.kind === "moveTo") && paragraph.pPrMark.deletion === void 0 && (!isOwnRecord(paragraph.pPrMark.info, revision) || paragraph.sectionProperties !== void 0 || beforeInsertedTable && paragraph === last.paragraph);
9479
9678
  const overwrittenMark = reviewed.find((paragraph) => paragraph.pPrMark !== void 0 && !trailing.includes(paragraph) && !joinsNext.has(paragraph) && !keepsDeletedMark(paragraph) && !deletesAddedMark(paragraph))?.pPrMark;
9480
9679
  if (overwrittenMark !== void 0) return refuse(pendingParagraphMarkReason(overwrittenMark), "Deletion would overwrite a paragraph review record.");
9481
9680
  const selectedSet = new Set(selected);
@@ -9517,7 +9716,7 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9517
9716
  review.propertyChanges = [foldedParagraphPropertyChange({
9518
9717
  paragraph,
9519
9718
  formatting: endFormatting,
9520
- stamp: op.revision
9719
+ stamp: revision
9521
9720
  })];
9522
9721
  next = withReviewFields(next, review);
9523
9722
  }
@@ -9536,6 +9735,9 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9536
9735
  case "invalidId": return refuse(DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "Paragraph deletion received an invalid revision id.");
9537
9736
  case "fresh": {
9538
9737
  const next = following?.type === "paragraph" && trailing.length === 0 ? [following] : [];
9738
+ const sourceMark = fresh.paragraphs.find((_, index) => reviewed[index] === propertySource)?.pPrMark;
9739
+ const ownerId = sourceMark?.kind === "del" ? sourceMark.info.id : sourceMark?.deletion?.info.id;
9740
+ const newOwner = ownerId !== void 0 && propertySource !== void 0 && !markGoes(propertySource) ? ownerId : void 0;
9539
9741
  const marked = [...fresh.paragraphs, ...next];
9540
9742
  const original = [...reviewed, ...next];
9541
9743
  const changed = [...tracked, ...next];
@@ -9545,8 +9747,16 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9545
9747
  const modified = /* @__PURE__ */ new Set();
9546
9748
  let carried;
9547
9749
  let joining = [];
9548
- for (const [index, paragraph] of marked.entries()) {
9750
+ for (const [index, markedParagraph] of marked.entries()) {
9549
9751
  const source = original[index];
9752
+ const change = markedParagraph.propertyChanges?.at(0);
9753
+ const paragraph = newOwner !== void 0 && source === endsContainer && !source.propertyChanges?.length && change !== void 0 ? {
9754
+ ...markedParagraph,
9755
+ propertyChanges: [{
9756
+ ...change,
9757
+ resolvesWith: newOwner
9758
+ }]
9759
+ } : markedParagraph;
9550
9760
  if (source === following && standing.length > 0) {
9551
9761
  if (carried === void 0) blocks.push(...standing);
9552
9762
  else carried.push(...standing);
@@ -10160,6 +10370,19 @@ const storyLifecycleTouched = ({ before, after }) => {
10160
10370
  removed: [...oldIds].filter((id) => !newIds.has(id))
10161
10371
  };
10162
10372
  };
10373
+ /**
10374
+ * The operation that turns `before`'s story parts (body, sections, headers,
10375
+ * footers, notes and settings) into `after`'s, for an edit computed on the
10376
+ * whole document; it is stale-checked against `before`.
10377
+ */
10378
+ const storyPartsOpOf = ({ before, after }) => {
10379
+ const prior = changedParts(before, after, true);
10380
+ return {
10381
+ type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
10382
+ expected: cloneModel(prior),
10383
+ parts: cloneModel(captureStoryParts(after, prior))
10384
+ };
10385
+ };
10163
10386
  const storyLifecycleEdit = (before, after, op, semantic = false) => {
10164
10387
  const invalid = contractViolation(after);
10165
10388
  if (invalid) return Result.err(new DocumentOpRefusal({
@@ -10549,6 +10772,71 @@ const setContentControl = (document, op) => {
10549
10772
  }
10550
10773
  });
10551
10774
  };
10775
+ // src/ops/firstSurvivor.ts
10776
+ /**
10777
+ * The fields of a new mark that keeps the paragraph before it, the paragraph
10778
+ * after it taking over `former`, the mark the paragraph had: the tracked
10779
+ * mark at the end of a chain of such takeovers, none when it is no tracked
10780
+ * change.
10781
+ */
10782
+ const firstSurvivorFields = (former) => {
10783
+ const takenOverMark = former?.survivor === "first" ? former.takenOverMark : former?.info.id;
10784
+ return takenOverMark === void 0 ? { survivor: "first" } : {
10785
+ survivor: "first",
10786
+ takenOverMark
10787
+ };
10788
+ };
10789
+ /** The ids of the marks on `paragraphs`. */
10790
+ const markIdsOf = (paragraphs) => new Set(paragraphs.flatMap(({ pPrMark }) => pPrMark ? [pPrMark.info.id] : []));
10791
+ const located = (body, ids) => ids.flatMap((id) => {
10792
+ const at = findStoryParagraph(body, id);
10793
+ return at === void 0 ? [] : [at.paragraph];
10794
+ });
10795
+ /** Removing a break retires the keep-first rule that depended on it. */
10796
+ const storyReleases = ({ before, after, story, touched }) => {
10797
+ const holders = located(before, [...touched.modified, ...touched.removed]);
10798
+ if (holders.every(({ pPrMark }) => pPrMark === void 0)) return [];
10799
+ const kept = markIdsOf(located(after, [...touched.modified, ...touched.inserted]));
10800
+ const retired = /* @__PURE__ */ new Set();
10801
+ for (const holder of holders) {
10802
+ const id = holder.pPrMark?.info.id;
10803
+ if (id === void 0 || kept.has(id)) continue;
10804
+ retired.add(id);
10805
+ }
10806
+ if (retired.size === 0) return [];
10807
+ const releases = [];
10808
+ for (const { paragraph } of storyParagraphs(after)) {
10809
+ const mark = paragraph.pPrMark;
10810
+ const named = mark?.takenOverMark;
10811
+ if (mark === void 0 || named === void 0 || paragraph.paraId === void 0) continue;
10812
+ if (!retired.has(named)) continue;
10813
+ const { survivor: _survivor, takenOverMark: _named, ...rest } = mark;
10814
+ const expected = reviewFieldsOf(paragraph);
10815
+ releases.push({
10816
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
10817
+ story,
10818
+ blockId: paragraph.paraId,
10819
+ expected,
10820
+ review: {
10821
+ ...expected,
10822
+ pPrMark: rest
10823
+ }
10824
+ });
10825
+ }
10826
+ return releases;
10827
+ };
10828
+ /** Retire references to marks removed by an edit in its addressed story. */
10829
+ const takenOverMarkReleases = ({ before, after, touched, story }) => {
10830
+ if (story === void 0 || touched.modified.length === 0 && touched.removed.length === 0) return [];
10831
+ const was = findStoryBody$1(before, story);
10832
+ const is = findStoryBody$1(after, story);
10833
+ return was === void 0 || is === void 0 || was === is ? [] : storyReleases({
10834
+ before: was,
10835
+ after: is,
10836
+ story,
10837
+ touched
10838
+ });
10839
+ };
10552
10840
  // src/ops/paragraphPrimitive.ts
10553
10841
  const refusal$5 = (op, reason, message) => new DocumentOpRefusal({
10554
10842
  message,
@@ -10945,12 +11233,14 @@ const trackedParagraphReplacement = ({ op, revision, source, anchor, takesOverMa
10945
11233
  }));
10946
11234
  if (identityKeysIn(op.blocks).length > 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Tracked insertion of identified review or content-control records is unsupported.");
10947
11235
  const markKind = op.move === true ? "moveTo" : "ins";
11236
+ const former = takesOverMark ? source.pPrMark : void 0;
11237
+ const survivor = firstSurvivorFields(former);
10948
11238
  const marks = takenOverMarks({
10949
- mark: takesOverMark ? source.pPrMark : void 0,
11239
+ mark: former,
10950
11240
  added: {
10951
11241
  kind: markKind,
10952
11242
  info: stampInfo(revision),
10953
- survivor: "first"
11243
+ ...survivor
10954
11244
  }
10955
11245
  });
10956
11246
  if (marks.isErr()) return marks;
@@ -10970,7 +11260,7 @@ const trackedParagraphReplacement = ({ op, revision, source, anchor, takesOverMa
10970
11260
  pPrMark: {
10971
11261
  kind: markKind,
10972
11262
  info: stampInfo(revision),
10973
- ...takesOverMark ? { survivor: "first" } : {}
11263
+ ...takesOverMark ? survivor : {}
10974
11264
  }
10975
11265
  });
10976
11266
  continue;
@@ -11242,7 +11532,8 @@ const insertBlocks = ({ document, op, applyOps, validateBlockReplacement }) => {
11242
11532
  const following = list[location.index + 1];
11243
11533
  const before = op.at.type === "before" || following?.type === "paragraph";
11244
11534
  const anchor = op.at.type === "after" && following?.type === "paragraph" ? following : location.paragraph;
11245
- const takesOverMark = op.revision !== void 0 && !before && (following?.type !== "table" || !insertedMarkResolvesBeforeTable({
11535
+ const opensNextSection = !before && following !== void 0 && location.paragraph.sectionProperties !== void 0;
11536
+ const takesOverMark = op.revision !== void 0 && !before && !opensNextSection && (following?.type !== "table" || !insertedMarkResolvesBeforeTable({
11246
11537
  blocks: list,
11247
11538
  source: location.paragraph,
11248
11539
  index: location.index + 1,
@@ -11259,9 +11550,10 @@ const insertBlocks = ({ document, op, applyOps, validateBlockReplacement }) => {
11259
11550
  });
11260
11551
  const canonicalBlocks = op.blocks.map(canonicalizeInsertedParagraph);
11261
11552
  if (op.revision === void 0 && op.at.type === "after" && following?.type === "paragraph" && location.paragraph.pPrMark?.survivor === "first") return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Insertion after a pending paragraph mark needs its former formatting snapshot and revision ids.");
11553
+ const sectionBoundaries = opensNextSection ? { sectionBoundaries: SECTION_BOUNDARY_POLICIES.REPLACE } : {};
11262
11554
  const draft = {
11263
11555
  ...replacement(canonicalBlocks),
11264
- ...op.revision === void 0 && !before && following !== void 0 && anchor.sectionProperties !== void 0 ? { sectionBoundaries: SECTION_BOUNDARY_POLICIES.REPLACE } : {}
11556
+ ...sectionBoundaries
11265
11557
  };
11266
11558
  const direct = op.revision !== void 0 && op.story === OP_STORIES.MAIN && location.list.length === 0 && anchor.paraId !== void 0 && isParaId(anchor.paraId) && canSpliceMainBodyWithoutSectionRepair(body) && (document.package.footnotes?.length ?? 0) === 0 && (document.package.endnotes?.length ?? 0) === 0 && canonicalBlocks.every(({ pPrMark, propertyChanges, reviewCarrier, content }) => pPrMark === void 0 && propertyChanges === void 0 && reviewCarrier === void 0 && content.every((node) => node.type === "run" && node.content.every((leaf) => leaf.type === "text"))) ? validateBlockReplacement({
11267
11559
  document,
@@ -11298,7 +11590,10 @@ const insertBlocks = ({ document, op, applyOps, validateBlockReplacement }) => {
11298
11590
  usedElsewhere: () => packageIdentityKeyIndex(document.package)
11299
11591
  });
11300
11592
  if (prepared.isErr()) return prepared;
11301
- const tracked = applyOps(document, [prepared.value]);
11593
+ const tracked = applyOps(document, [{
11594
+ ...prepared.value,
11595
+ ...sectionBoundaries
11596
+ }]);
11302
11597
  return tracked.isErr() ? Result.err(new DocumentOpRefusal({
11303
11598
  reason: tracked.error.reason,
11304
11599
  message: tracked.error.message,
@@ -13417,6 +13712,108 @@ const withoutRepeatedMoveRangesIn = (document, contents) => {
13417
13712
  };
13418
13713
  /** {@link withoutRepeatedMoveRangesIn} of one content. */
13419
13714
  const withoutRepeatedMoveRanges = (document, content) => withoutRepeatedMoveRangesIn(document, [content]).at(0) ?? content;
13715
+ // src/ops/contiguousResolutionJoins.ts
13716
+ const plainFields = /* @__PURE__ */ new Set([
13717
+ "type",
13718
+ "paraId",
13719
+ "textId",
13720
+ "content",
13721
+ "pPrMark"
13722
+ ]);
13723
+ const isPlainTextContent = (paragraph) => {
13724
+ if (paragraph.content.length === 0) return true;
13725
+ const run = paragraph.content.at(0);
13726
+ if (paragraph.content.length !== 1 || run?.type !== "run" || Object.keys(run).some((key) => key !== "type" && key !== "content") || run.content.length !== 1) return false;
13727
+ const text = run.content.at(0);
13728
+ return text?.type === "text" && Object.keys(text).every((key) => key === "type" || key === "text");
13729
+ };
13730
+ const isPlainJoinParagraph = (paragraph) => paragraph.paraId !== void 0 && isParaId(paragraph.paraId) && isPlainTextContent(paragraph) && Object.keys(paragraph).every((key) => plainFields.has(key));
13731
+ /**
13732
+ * Each rejected inserted mark joins its paragraph into the already settled
13733
+ * suffix of its contiguous run. In a section-free pair with at most one plain
13734
+ * text payload, only those two paragraphs can affect the ordinary join plan.
13735
+ */
13736
+ const planContiguousResolutionJoins = ({ document, story, paragraphCount, indexOf, paragraphAt, joins, planPair }) => {
13737
+ const firstJoin = joins.at(0);
13738
+ const start = firstJoin === void 0 ? void 0 : indexOf(firstJoin.paraId);
13739
+ if (start === void 0) return {
13740
+ type: "fallback",
13741
+ reason: "joinShape"
13742
+ };
13743
+ const end = start + joins.length + 1;
13744
+ let survivor = paragraphAt(end - 1);
13745
+ if (story !== "main" || end > paragraphCount || survivor === void 0 || survivor.pPrMark !== void 0 || !isPlainJoinParagraph(survivor)) return {
13746
+ type: "fallback",
13747
+ reason: "joinShape"
13748
+ };
13749
+ const effects = [];
13750
+ const receiverEffects = [];
13751
+ for (let i = joins.length - 1; i >= 0; i--) {
13752
+ const first = paragraphAt(start + i);
13753
+ const join = joins[i];
13754
+ if (first === void 0 || !isPlainJoinParagraph(first) || first.content.length > 0 && survivor.content.length > 0 || join === void 0 || join.story !== story || join.op.decision !== REVISION_DECISIONS.REJECT || !join.added || join.depth !== void 0 || join.paraId !== first.paraId || first.pPrMark?.kind !== "ins" || first.pPrMark.info.id !== join.revisionId || first.pPrMark.deletion !== void 0 || first.pPrMark.resolutionJoin !== void 0) return {
13755
+ type: "fallback",
13756
+ reason: "joinShape"
13757
+ };
13758
+ const second = survivor;
13759
+ const planned = planPair({
13760
+ join,
13761
+ first,
13762
+ second
13763
+ });
13764
+ if (planned.isErr()) return {
13765
+ type: "fallback",
13766
+ reason: "joinPlan"
13767
+ };
13768
+ const plan = planned.value;
13769
+ const op = plan.ops.at(0);
13770
+ const receiver = plan.receiverEffects.at(0);
13771
+ if (plan.endsControl !== void 0 || plan.ops.length !== 1 || op?.type !== DOCUMENT_OP_TYPES.REPLACE_BLOCKS || op.story !== story || op.sectionView !== void 0 || op.sectionBoundaries !== void 0 || op.expected.length !== 2 || op.expected[0] !== first || op.expected[1] !== second || op.blocks.length !== 1 || plan.receiverEffects.length !== 1 || receiver?.type !== "paragraph-join" || receiver.receiver !== second) return {
13772
+ type: "fallback",
13773
+ reason: "joinPlan"
13774
+ };
13775
+ const next = op.blocks[0];
13776
+ if (next === void 0 || next.pPrMark !== void 0 || !isPlainJoinParagraph(next) || !structurallyEqual(next.content, first.content.length === 0 ? second.content : first.content) || next.paraId !== first.paraId && next.paraId !== second.paraId) return {
13777
+ type: "fallback",
13778
+ reason: "joinPlan"
13779
+ };
13780
+ if (validateBlockReplacement({
13781
+ document,
13782
+ op,
13783
+ before: op.expected
13784
+ }).isErr()) return {
13785
+ type: "fallback",
13786
+ reason: "joinValidation"
13787
+ };
13788
+ const survivorId = next.paraId;
13789
+ const source = next.paraId === first.paraId ? first : second;
13790
+ if (next !== source) transferParagraphPropertySnapshot({
13791
+ source,
13792
+ target: next
13793
+ });
13794
+ const effect = nonemptyBlockReplacementEffects(op, op.expected);
13795
+ effects.push({
13796
+ inverse: effect.inverse.map(captureDocumentOp),
13797
+ touched: {
13798
+ ...effect.touched,
13799
+ absorbed: effect.touched.removed.map((absorbed) => ({
13800
+ absorbed,
13801
+ survivor: survivorId
13802
+ }))
13803
+ }
13804
+ });
13805
+ receiverEffects.push(receiver);
13806
+ survivor = next;
13807
+ }
13808
+ return {
13809
+ type: "planned",
13810
+ start,
13811
+ end,
13812
+ survivor,
13813
+ effects,
13814
+ receiverEffects
13815
+ };
13816
+ };
13420
13817
  // src/ops/keptJoins.ts
13421
13818
  /**
13422
13819
  * The joins a pending tracked change takes over from a resolved piece that
@@ -13477,6 +13874,138 @@ const withJoinRetired = (node, side, depth) => {
13477
13874
  if (joins[side] <= depth) return node;
13478
13875
  return Object.assign({}, node, { resolutionJoins: Object.assign({}, joins, side === "before" ? { before: depth } : { after: depth }) });
13479
13876
  };
13877
+ /**
13878
+ * `node`, a pending tracked change, with its join on `side` `depth` levels
13879
+ * deep and closed to records there (`plainSides`): it meets no record of the
13880
+ * cut on that side and takes only the kept markers naming its side.
13881
+ */
13882
+ const withJoinClosed = (node, side, depth) => {
13883
+ if (!isTrackedWrapper(node) || node.resolutionJoins === void 0) return panic("A facing insertion is a pending change with joins.");
13884
+ const joins = node.resolutionJoins;
13885
+ const plainSides = joins.plainSides ?? [];
13886
+ return Object.assign({}, node, { resolutionJoins: Object.assign({}, joins, side === "before" ? { before: depth } : { after: depth }, { plainSides: plainSides.includes(side) ? plainSides : [...plainSides, side] }) });
13887
+ };
13888
+ // src/ops/resolutionMaterialization.ts
13889
+ const MAX_INLINE_RESOLUTION_SPAN = 16384;
13890
+ const fallback$1 = (reason) => ({
13891
+ type: "fallback",
13892
+ reason
13893
+ });
13894
+ const isTextRun$1 = (node) => node.type === "run" && node.content.every(({ type }) => type === "text");
13895
+ const isLocalText = (node) => isTextRun$1(node) || (node.type === "insertion" || node.type === "deletion") && node.content.every(isTextRun$1);
13896
+ const hasCanonicalTrailingSection = (body) => {
13897
+ if (body.sections === void 0) return true;
13898
+ if (body.sections?.length !== 1 || body.finalSectionProperties === void 0) return false;
13899
+ const section = body.sections.at(0);
13900
+ return section !== void 0 && section.properties === body.finalSectionProperties && Object.keys(section).length === 2 && Object.hasOwn(section, "properties") && Object.hasOwn(section, "content") && section.content.length === body.content.length && body.content.every((block, index) => block === section.content[index]);
13901
+ };
13902
+ /**
13903
+ * The ordinary primitive validators prepare each paragraph in journal order.
13904
+ * They can read the original package here because each edit only retires IDs.
13905
+ * Section, note, range and other container interactions stay in the ordinary
13906
+ * sequential planner. A failed proof lets that planner determine the refusal.
13907
+ */
13908
+ const tryMaterializeResolution = ({ document, story, locations, inline, join, noteReferences, receiverEffects }) => {
13909
+ if (story !== OP_STORIES.MAIN) return fallback$1("story");
13910
+ const body = document.package.document;
13911
+ if ((document.package.footnotes?.length ?? 0) > 0 || (document.package.endnotes?.length ?? 0) > 0 || (body.comments?.length ?? 0) > 0) return fallback$1("packageDependencies");
13912
+ if (noteReferences.length > 0 || receiverEffects.length > 0) return fallback$1("referenceEffects");
13913
+ const originals = body.content;
13914
+ if (join.type === "plan" && locations.some(({ paragraph }) => paragraph.pPrMark?.takenOverMark !== void 0)) return fallback$1("survivorProvenance");
13915
+ if (!originals.every((block) => block.type === "paragraph") || locations.length !== originals.length) return fallback$1("paragraphList");
13916
+ if (originals.some(({ sectionProperties }) => sectionProperties !== void 0) || !hasCanonicalTrailingSection(body)) return fallback$1("sectionView");
13917
+ if (validateOpsDocument(document).isErr()) return fallback$1("inputContract");
13918
+ const byId = /* @__PURE__ */ new Map();
13919
+ for (const at of locations) {
13920
+ const { paraId } = at.paragraph;
13921
+ if (at.list.length > 0 || originals.at(at.index) !== at.paragraph || paraId === void 0 || !isParaId(paraId)) return fallback$1("paragraphList");
13922
+ byId.set(idKey(paraId), at);
13923
+ }
13924
+ const replacements = /* @__PURE__ */ new Map();
13925
+ const effects = [];
13926
+ let first = originals.length;
13927
+ let end = 0;
13928
+ for (const op of inline) {
13929
+ const at = byId.get(idKey(op.blockId));
13930
+ const paragraph = at === void 0 ? void 0 : replacements.get(at.index) ?? originals.at(at.index);
13931
+ if (op.story !== story || at === void 0 || paragraph === void 0 || !paragraph.content.every(isLocalText)) return fallback$1("primitiveShape");
13932
+ if (op.type === DOCUMENT_OP_TYPES.REPLACE_INLINE) {
13933
+ if (!op.content.every(isTextRun$1)) return fallback$1("primitiveShape");
13934
+ } else if (op.review.propertyChanges !== void 0 || op.review.pPrMark !== void 0) return fallback$1("primitiveShape");
13935
+ const prepared = prepareResolutionParagraphOp({
13936
+ document,
13937
+ op,
13938
+ at: {
13939
+ ...at,
13940
+ paragraph
13941
+ }
13942
+ });
13943
+ if (prepared.isErr()) return fallback$1("primitiveValidation");
13944
+ if (prepared.value.type === "unchanged") continue;
13945
+ const next = prepared.value;
13946
+ if (next.incomingParagraphIds.length > 0 || next.incomingIdentityKeys.length > 0) return fallback$1("identityIntroduction");
13947
+ if (!structurallyEqual(next.paragraph.formatting, paragraph.formatting)) return fallback$1("primitiveShape");
13948
+ transferParagraphPropertySnapshot({
13949
+ source: paragraph,
13950
+ target: next.paragraph
13951
+ });
13952
+ replacements.set(at.index, next.paragraph);
13953
+ first = Math.min(first, at.index);
13954
+ end = Math.max(end, at.index + 1);
13955
+ effects.push({
13956
+ inverse: [captureDocumentOp(next.inverse)],
13957
+ touched: next.touched
13958
+ });
13959
+ }
13960
+ if (effects.length === 0 && join.type === "noJoins") return {
13961
+ type: "materialized",
13962
+ edit: combineEditEffects(document, []),
13963
+ receiverEffects: []
13964
+ };
13965
+ const combinedInline = combineEditEffects(document, effects);
13966
+ const joined = join.type === "plan" ? join.prepare({
13967
+ paragraphCount: originals.length,
13968
+ indexOf: (id) => byId.get(idKey(id))?.index,
13969
+ paragraphAt: (index) => replacements.get(index) ?? originals.at(index)
13970
+ }) : void 0;
13971
+ if (joined?.type === "fallback") return joined;
13972
+ const start = joined === void 0 ? first : Math.min(first, joined.start);
13973
+ const stop = joined === void 0 ? end : Math.max(end, joined.end);
13974
+ const removed = joined === void 0 ? 0 : joined.end - joined.start - 1;
13975
+ if (stop - start - removed > MAX_INLINE_RESOLUTION_SPAN) return fallback$1("wideSpan");
13976
+ let replacement;
13977
+ if (joined === void 0) {
13978
+ replacement = originals.slice(start, stop);
13979
+ for (const [index, paragraph] of replacements) replacement[index - start] = paragraph;
13980
+ } else {
13981
+ replacement = [];
13982
+ for (let index = start; index < stop; index++) if (index === joined.start) {
13983
+ replacement.push(joined.survivor);
13984
+ index = joined.end - 1;
13985
+ } else {
13986
+ const current = replacements.get(index) ?? originals.at(index);
13987
+ if (current === void 0) return fallback$1("paragraphList");
13988
+ replacement.push(current);
13989
+ }
13990
+ }
13991
+ const final = replaceParagraphs({
13992
+ document,
13993
+ story,
13994
+ at: {
13995
+ list: [],
13996
+ index: start
13997
+ },
13998
+ count: stop - start,
13999
+ replacement
14000
+ });
14001
+ if (final.isErr() || hasMultipleParagraphPropertyChanges(final.value) || repeatedParagraphId(final.value) !== void 0) return fallback$1("materialization");
14002
+ meetsContract(final.value);
14003
+ return {
14004
+ type: "materialized",
14005
+ edit: combineEditEffects(final.value, [combinedInline, ...joined?.effects ?? []]),
14006
+ receiverEffects: joined?.receiverEffects ?? []
14007
+ };
14008
+ };
13480
14009
  // src/ops/resolvedEdges.ts
13481
14010
  /**
13482
14011
  * The records at an edge of an inline record, as a resolution reads them
@@ -13724,9 +14253,44 @@ const withMergesHandedOn = (table, rowIndex) => {
13724
14253
  cells
13725
14254
  } : void 0;
13726
14255
  };
13727
- /** The table's rows without row `rowIndex`, the merges it starts handed on. */
14256
+ /**
14257
+ * The row before `rowIndex` once that row is removed, when the removed row
14258
+ * holds the only continuation of a vertical merge the row before starts: the
14259
+ * merge no row continues is no merge, and the cell starting it states none.
14260
+ * `undefined` when the removed row ends no such merge.
14261
+ */
14262
+ const withMergesEnded = (table, rowIndex) => {
14263
+ const grid = tableGrid(table, DOCUMENT_OP_TYPES.DELETE_ROW);
14264
+ if (grid.isErr()) return void 0;
14265
+ const previousRow = table.rows[rowIndex - 1];
14266
+ if (previousRow === void 0) return void 0;
14267
+ const removed = grid.value.rows[rowIndex] ?? [];
14268
+ const following = grid.value.rows[rowIndex + 1] ?? [];
14269
+ const ended = new Set(removed.filter((slot) => slot.ownerRow === rowIndex - 1 && !following.some((entry) => entry.ownerRow === slot.ownerRow && entry.ownerIndex === slot.ownerIndex)).map((slot) => slot.ownerIndex));
14270
+ if (ended.size === 0) return void 0;
14271
+ const cells = previousRow.cells.map((cell, index) => {
14272
+ if (!ended.has(index)) return cell;
14273
+ const { vMerge: _vMerge, sourceXml: _sourceXml, ...formatting } = cell.formatting ?? {};
14274
+ if (Object.keys(formatting).length > 0) return {
14275
+ ...cell,
14276
+ formatting
14277
+ };
14278
+ const { formatting: _formatting, ...plain } = cell;
14279
+ return plain;
14280
+ });
14281
+ return {
14282
+ ...previousRow,
14283
+ cells
14284
+ };
14285
+ };
14286
+ /**
14287
+ * The table's rows without row `rowIndex`: the merges it starts handed on,
14288
+ * and those it alone continues ended.
14289
+ */
13728
14290
  const rowsWithoutRow = (table, rowIndex) => {
13729
14291
  const rows = [...table.rows];
14292
+ const ended = withMergesEnded(table, rowIndex);
14293
+ if (ended !== void 0) rows[rowIndex - 1] = ended;
13730
14294
  const next = withMergesHandedOn(table, rowIndex);
13731
14295
  if (next === void 0) rows.splice(rowIndex, 1);
13732
14296
  else rows.splice(rowIndex, 2, next);
@@ -14206,21 +14770,38 @@ const marksInRemovedStructure = (document, op) => {
14206
14770
  if (op.decision === REVISION_DECISIONS.REJECT) return change.type === "tableRowInsertion" || change.type === "tableCellInsertion";
14207
14771
  return change.type === "tableRowDeletion" || change.type === "tableCellDeletion";
14208
14772
  };
14773
+ const handedOn = (table) => {
14774
+ const grid = tableGrid(table, DOCUMENT_OP_TYPES.SET_TABLE_ROWS);
14775
+ if (grid.isErr()) return /* @__PURE__ */ new Set();
14776
+ const kept = /* @__PURE__ */ new Set();
14777
+ for (const [rowIndex, slots] of grid.value.rows.entries()) {
14778
+ if (removes(table.rows[rowIndex]?.structuralChange)) continue;
14779
+ for (const slot of slots) {
14780
+ if (slot.ownerRow === rowIndex) continue;
14781
+ const owner = table.rows[slot.ownerRow]?.cells[slot.ownerIndex];
14782
+ if (owner !== void 0) kept.add(owner);
14783
+ }
14784
+ }
14785
+ return kept;
14786
+ };
14209
14787
  const settled = /* @__PURE__ */ new Map();
14210
- for (const table of tablesIn(document, op.story)) for (const row of table.rows) for (const cell of row.cells) {
14211
- if (!removes(row.structuralChange) && !removes(cell.structuralChange)) continue;
14212
- for (const { paragraph } of storyParagraphs({ content: cell.content })) {
14213
- const { paraId } = paragraph;
14214
- if (paragraph.pPrMark === void 0 || paraId === void 0 || settled.has(paraId)) continue;
14215
- const review = reviewFieldsOf(paragraph);
14216
- delete review.pPrMark;
14217
- settled.set(paraId, {
14218
- type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
14219
- story: op.story,
14220
- blockId: paraId,
14221
- expected: reviewFieldsOf(paragraph),
14222
- review
14223
- });
14788
+ for (const table of tablesIn(document, op.story)) {
14789
+ const kept = handedOn(table);
14790
+ for (const row of table.rows) for (const cell of row.cells) {
14791
+ if (!(removes(cell.structuralChange) || removes(row.structuralChange) && !kept.has(cell))) continue;
14792
+ for (const { paragraph } of storyParagraphs({ content: cell.content })) {
14793
+ const { paraId } = paragraph;
14794
+ if (paragraph.pPrMark === void 0 || paraId === void 0 || settled.has(paraId)) continue;
14795
+ const review = reviewFieldsOf(paragraph);
14796
+ delete review.pPrMark;
14797
+ settled.set(paraId, {
14798
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
14799
+ story: op.story,
14800
+ blockId: paraId,
14801
+ expected: reviewFieldsOf(paragraph),
14802
+ review
14803
+ });
14804
+ }
14224
14805
  }
14225
14806
  }
14226
14807
  return [...settled.values()];
@@ -14353,6 +14934,35 @@ const reachableOnTable = (table) => /* @__PURE__ */ new Set([
14353
14934
  ...row.cells.flatMap((cell) => [...propertyIds(cell.propertyChanges), ...cellStructuralIds(cell)])
14354
14935
  ])
14355
14936
  ]);
14937
+ /**
14938
+ * The table once every pending record of its grid, its properties, its rows'
14939
+ * properties and its cells is accepted or rejected, as resolving them does;
14940
+ * the rows' own insertions and deletions stay pending. `unsupported` where
14941
+ * resolving them refuses.
14942
+ */
14943
+ const withTableRecordsResolved = (table, reject) => {
14944
+ const rowIds = new Set(table.rows.flatMap(({ structuralChange }) => structuralChange === void 0 ? [] : [structuralChange.info.id]));
14945
+ const ids = new Set([...reachableOnTable(table)].filter((id) => !rowIds.has(id)));
14946
+ if (ids.size === 0) return Result.ok(table);
14947
+ if (removesEveryCell({
14948
+ table,
14949
+ ids,
14950
+ reject
14951
+ })) return Result.err("unsupported");
14952
+ const cells = resolveCellChanges({
14953
+ table,
14954
+ ids,
14955
+ reject,
14956
+ selectedGridChange: table.formatting?.gridChange !== void 0 && ids.has(table.formatting.gridChange.id)
14957
+ });
14958
+ if (cells.isErr()) return Result.err(cells.error);
14959
+ return propertyTable({
14960
+ table: cells.value.table,
14961
+ keepsGrid: cells.value.holdsRemovedColumns,
14962
+ ids,
14963
+ reject
14964
+ });
14965
+ };
14356
14966
  // src/ops/sectionReview.ts
14357
14967
  /**
14358
14968
  * Rejected section properties: the stored old sectPr wholesale, preserving
@@ -14855,7 +15465,13 @@ const restoreRetainedIdentities = ({ nodes, transfers, resolution }) => {
14855
15465
  next = Object.assign({}, node, { resolutionJoins: joins });
14856
15466
  }
14857
15467
  const children = childNodes(next);
14858
- return children === void 0 ? next : rebuildNode(next, children.map(rebase));
15468
+ return children === void 0 ? withKeptCutHoldersRenamed(next, (id) => {
15469
+ const restored = references.get(slotKey({
15470
+ space: IDENTITY_SPACES.REVISION,
15471
+ id
15472
+ }));
15473
+ return restored?.space === IDENTITY_SPACES.REVISION ? restored.id : id;
15474
+ }) : rebuildNode(next, children.map(rebase));
14859
15475
  };
14860
15476
  return {
14861
15477
  nodes: out.map(rebase),
@@ -15056,13 +15672,29 @@ const consumeSeamNames = (out, { blockers }, known) => {
15056
15672
  if (!isTrackedWrapper(node) || !blockers.includes(node.info.id)) continue;
15057
15673
  for (const step of [-1, 1]) {
15058
15674
  const run = [];
15675
+ const toward = step === -1 ? "before" : "after";
15676
+ const ownSide = step === -1 ? "after" : "before";
15677
+ const takesOwn = (node.resolutionJoins?.[toward] ?? 0) > 0;
15678
+ const ownRun = [];
15059
15679
  let beyond;
15060
15680
  for (let at = index + step; at >= 0; at += step) {
15061
15681
  beyond = out[at];
15062
- if (beyond === void 0 || !standsInKeptCut(beyond) || keptCutPiece(beyond) !== "both") break;
15063
- run.push(at);
15682
+ if (beyond === void 0 || !keptCutHeldBy(beyond, {
15683
+ side: ownSide,
15684
+ id: node.info.id
15685
+ })) break;
15686
+ const named = keptCutPiece(beyond);
15687
+ if (named === ownSide && !takesOwn) ownRun.push(at);
15688
+ else if (named !== "both") break;
15689
+ else run.push(at);
15064
15690
  beyond = void 0;
15065
15691
  }
15692
+ for (const at of ownRun) {
15693
+ const marker = out[at];
15694
+ if (marker === void 0) continue;
15695
+ out[at] = withKeptCutPieceConsumed(marker, known);
15696
+ changed = true;
15697
+ }
15066
15698
  if (beyond !== void 0 && isTrackedWrapper(beyond) && waitedOn.has(beyond.info.id)) continue;
15067
15699
  for (const at of run) {
15068
15700
  const marker = out[at];
@@ -15198,6 +15830,41 @@ const settleDeferredRemovals = (nodes, options) => {
15198
15830
  return changed ? out : nodes;
15199
15831
  };
15200
15832
  /**
15833
+ * Kept markers at the edge of an accepted removal away from its seam, naming
15834
+ * its side as their cut's piece: the removal held that piece, and once its
15835
+ * content goes they meet the piece across the seam, which continues the
15836
+ * record the cut split. They go into it at its facing edge, as deep as the
15837
+ * seam, as they do when the removal goes with the change holding it. `out`
15838
+ * is changed in place; whether it changed.
15839
+ */
15840
+ const placeKeptAcrossRemovedPiece = ({ out, index, group, fateOf, known }) => {
15841
+ const holder = out[index];
15842
+ if (holder === void 0 || holder.type !== "deletion" && holder.type !== "moveFrom" || group.edge === void 0) return false;
15843
+ const atEnd = group.edge === "end";
15844
+ const step = atEnd ? -1 : 1;
15845
+ const named = atEnd ? "after" : "before";
15846
+ let records = 0;
15847
+ for (let at = index + step;; at += step) {
15848
+ const node = at < 0 ? void 0 : out[at];
15849
+ if (node === void 0 || !standsInKeptCut(node) || keptCutPiece(node) !== named || !keptCutHeldBy(node, {
15850
+ side: named,
15851
+ id: holder.info.id
15852
+ })) break;
15853
+ records += 1;
15854
+ }
15855
+ if (records === 0) return false;
15856
+ const pieceAt = index - step;
15857
+ const piece = pieceAt < 0 ? void 0 : out[pieceAt];
15858
+ const edgeRecord = atEnd ? holder.content.at(-1) : holder.content.at(0);
15859
+ if (piece === void 0 || edgeRecord === void 0 || isTrackedWrapper(piece) || isStandingBoundary(piece) || emptiedBy(piece, fateOf) || !sameOwnFields(edgeRecord, piece)) return false;
15860
+ const start = atEnd ? index - records : index + 1;
15861
+ const placed = withBoundariesAtEdge(piece, out.slice(start, start + records).map((node) => withKeptCutPieceConsumed(node, known)), group.depth, atEnd ? "start" : "end");
15862
+ if (placed === void 0) return false;
15863
+ out.splice(start, records);
15864
+ out[atEnd ? pieceAt - records : pieceAt] = placed;
15865
+ return true;
15866
+ };
15867
+ /**
15201
15868
  * Kept markers beside a pending removal that holds a piece of the cut they
15202
15869
  * stand in, naming its side as their cut's piece, once the removal is
15203
15870
  * accepted: that piece goes, and they go into the piece across from them at
@@ -15215,10 +15882,19 @@ const placeKeptBesideRemovedPiece = ({ out, index, group, fateOf, known }) => {
15215
15882
  for (let at = index + step;; at += step) {
15216
15883
  const node = at < 0 ? void 0 : out[at];
15217
15884
  const piece = node === void 0 ? void 0 : keptCutPiece(node);
15218
- if (node === void 0 || !standsInKeptCut(node) || piece !== named && piece !== "both") break;
15885
+ if (node === void 0 || !standsInKeptCut(node) || piece !== named && piece !== "both" || !keptCutHeldBy(node, {
15886
+ side: named,
15887
+ id: holder.info.id
15888
+ })) break;
15219
15889
  records += 1;
15220
15890
  }
15221
- if (records === 0) return false;
15891
+ if (records === 0) return placeKeptAcrossRemovedPiece({
15892
+ out,
15893
+ index,
15894
+ group,
15895
+ fateOf,
15896
+ known
15897
+ });
15222
15898
  const pieceAt = index + step * (records + 1);
15223
15899
  const piece = pieceAt < 0 ? void 0 : out[pieceAt];
15224
15900
  const edgeRecord = atEnd ? holder.content.at(-1) : holder.content.at(0);
@@ -15574,6 +16250,7 @@ const withRejoinedBlockers = ({ nodes, retired, resolution }) => {
15574
16250
  next = Object.assign({}, next, { resolutionJoins: joins });
15575
16251
  }
15576
16252
  }
16253
+ if (children === void 0) next = withKeptCutHoldersRenamed(next, successor);
15577
16254
  if (next !== node) carryResolutionState(resolution, node, next);
15578
16255
  return next;
15579
16256
  };
@@ -15836,6 +16513,14 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15836
16513
  ...payload && { payload: true }
15837
16514
  });
15838
16515
  };
16516
+ /** A cut at a paragraph edge can end inside the one insertion it split. */
16517
+ const cutsEdgeOfRemovedInsertion = (node, index) => {
16518
+ const cut = node.resolutionJoins;
16519
+ if (cut?.remove !== 1 || cut.before !== 0 || cut.after !== 0) return false;
16520
+ if (index !== 0 && index !== pending.length - 1) return false;
16521
+ const piece = pending[index === 0 ? 1 : index - 1];
16522
+ return piece !== void 0 && isAddedRevision(piece) && isTrackedWrapper(piece) && resolution.ids.has(piece.info.id) && removesContent(piece, resolution.decision) && (piece.info.date ?? "") < (node.info.date ?? "") && piece.resolutionJoins?.before === 0 && piece.resolutionJoins.after === 0 && piece.resolutionJoins.remove === 0;
16523
+ };
15839
16524
  /**
15840
16525
  * How many levels of the cut `node` recorded for its removal remain once
15841
16526
  * this resolution is done, read against the records either side of it as
@@ -15850,6 +16535,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15850
16535
  const joins = node.resolutionJoins;
15851
16536
  const depth = joins?.remove ?? 0;
15852
16537
  if (depth === 0) return 0;
16538
+ if (cutsEdgeOfRemovedInsertion(node, index)) return 0;
15853
16539
  const reachesPast = resolution.ids.has(node.info.id) && removesContent(node, resolution.decision) && joins?.before === 0 && joins.after === 0;
15854
16540
  const goes = (candidate) => reachesPast && candidate !== void 0 && isTrackedWrapper(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision);
15855
16541
  const removed = resolution.ids.has(node.info.id);
@@ -15868,6 +16554,12 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15868
16554
  const takesCut = (candidate) => candidate !== void 0 && isAddedRevision(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision) && (candidate.info.date ?? "") < (node.info.date ?? "");
15869
16555
  if (before === void 0 || after === void 0) return !removed && (takesCut(before) || takesCut(after)) ? 0 : depth;
15870
16556
  if (takesCut(before) || takesCut(after)) return 0;
16557
+ const laterGoing = (candidate) => removed && candidate !== void 0 && isAddedRevision(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision) && (candidate.info.date ?? "") > (node.info.date ?? "");
16558
+ let takerBefore = beforeIndex;
16559
+ while (takerBefore >= 0 && laterGoing(pending.at(takerBefore))) takerBefore -= 1;
16560
+ let takerAfter = afterIndex;
16561
+ while (takerAfter < pending.length && laterGoing(pending.at(takerAfter))) takerAfter += 1;
16562
+ if (takerBefore >= 0 && takesCut(pending.at(takerBefore)) || takesCut(pending.at(takerAfter))) return 0;
15871
16563
  const joinedToNothing = (candidate) => candidate !== void 0 && isTrackedWrapper(candidate) && isAddedRevision(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision) && candidate.resolutionJoins !== void 0 && candidate.resolutionJoins.before === 0 && candidate.resolutionJoins.after === 0 && candidate.resolutionJoins.remove === 0;
15872
16564
  let pastBefore = beforeIndex;
15873
16565
  while (pastBefore >= 0 && joinedToNothing(pending.at(pastBefore))) pastBefore -= 1;
@@ -15992,12 +16684,13 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15992
16684
  * their seam. A marker already naming a piece keeps it: the first change
15993
16685
  * to take its seam holds it. Whether any marker took the name.
15994
16686
  */
15995
- const nameKeptPiece = (start, end, piece) => {
16687
+ const nameKeptPiece = (start, end, holders) => {
16688
+ if (holders === void 0) return false;
15996
16689
  let named = false;
15997
16690
  for (let index = start; index < end; index += 1) {
15998
16691
  const occurrence = out[index];
15999
16692
  if (occurrence === void 0) continue;
16000
- const next = withKeptCutPieceRecorded(occurrence.node, piece, resolution.relocated.nodes);
16693
+ const next = withKeptCutHoldersRecorded(occurrence.node, holders, resolution.relocated.nodes);
16001
16694
  if (next === occurrence.node) continue;
16002
16695
  out[index] = occurrenceOf(next, occurrence);
16003
16696
  named = true;
@@ -16005,6 +16698,29 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16005
16698
  return named;
16006
16699
  };
16007
16700
  /**
16701
+ * Whether the rejected insertion at `index` meets, on `side`, a join an
16702
+ * earlier change still holds toward it: an insertion made before it, or a
16703
+ * removal, pending or given back by this rejection. The boundaries the
16704
+ * rejection keeps stay at its seam then, naming no piece and going into
16705
+ * none, whichever of them is resolved first: resolving that change hands
16706
+ * its join to the rejected content's place.
16707
+ */
16708
+ const heldAcross = (index, side) => {
16709
+ const node = pending[index];
16710
+ if (node === void 0 || !isTrackedWrapper(node)) return false;
16711
+ const date = node.info.date ?? "";
16712
+ const step = side === "before" ? -1 : 1;
16713
+ let at = index + step;
16714
+ for (let beside = pending[at]; beside !== void 0 && standsInKeptCut(beside); beside = pending[at]) at += step;
16715
+ const across = at < 0 ? void 0 : pending[at];
16716
+ if (across === void 0 || !isTrackedWrapper(across)) return false;
16717
+ const facing = side === "before" ? "after" : "before";
16718
+ if ((across.resolutionJoins?.[facing] ?? 0) === 0) return false;
16719
+ const resolved = resolution.ids.has(across.info.id);
16720
+ if (isAddedRevision(across)) return !resolved && (across.info.date ?? "") < date;
16721
+ return isRemovedRevisionNode(across) && (!resolved || resolution.decision === REVISION_DECISIONS.REJECT);
16722
+ };
16723
+ /**
16008
16724
  * The boundaries a removed one-sided insertion kept, moved into the source
16009
16725
  * piece its join names: the record after it, not yet resolved, or the one
16010
16726
  * `out` holds before them. They stay standing where that record is a
@@ -16012,28 +16728,43 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16012
16728
  * held boundaries only has no edge record to differ from it. Their cuts go
16013
16729
  * with them, naming no piece: settling the list keeps a cut only while a
16014
16730
  * pending change still stands beside them, as placing them by accepting
16015
- * that piece later does.
16731
+ * that piece later does. Whether they moved.
16016
16732
  */
16017
16733
  const placeOneSidedKept = ({ index, piece, depth, kept, inside, edge }) => {
16734
+ if (heldAcross(index, piece === "after" ? "before" : "after")) return false;
16018
16735
  const standsInside = (record) => record !== void 0 && !isTrackedWrapper(record) && childNodes(record) !== void 0 && (edge === void 0 || sameOwnFields(edge, record));
16019
16736
  const first = out.length - kept;
16020
16737
  const boundaries = out.slice(piece === "after" ? out.length - inside : first, piece === "after" ? out.length : first + inside).map(({ node }) => withKeptCutPieceConsumed(node, resolution.relocated.nodes));
16021
16738
  if (piece === "after") {
16022
16739
  const next = pending.at(index + 1);
16023
- if (next === void 0 || !standsInside(next)) return;
16740
+ if (next === void 0 || !standsInside(next)) return false;
16024
16741
  const placed = withBoundariesAtEdge(next, boundaries, depth, "start");
16025
- if (placed === void 0) return;
16742
+ if (placed === void 0) return false;
16026
16743
  pending[index + 1] = placed;
16027
16744
  out.splice(out.length - inside, inside);
16028
- } else {
16029
- const previous = itemBefore(out, first);
16030
- if (previous === void 0 || !standsInside(previous.node)) return;
16031
- const placed = withBoundariesAtEdge(previous.node, boundaries, depth, "end");
16032
- if (placed === void 0) return;
16033
- carryResolutionState(resolution, previous.node, placed);
16034
- out[first - 1] = occurrenceOf(placed, previous);
16035
- out.splice(first, inside);
16745
+ return true;
16036
16746
  }
16747
+ const previous = itemBefore(out, first);
16748
+ if (previous === void 0 || !standsInside(previous.node)) return false;
16749
+ const placed = withBoundariesAtEdge(previous.node, boundaries, depth, "end");
16750
+ if (placed === void 0) return false;
16751
+ carryResolutionState(resolution, previous.node, placed);
16752
+ out[first - 1] = occurrenceOf(placed, previous);
16753
+ out.splice(first, inside);
16754
+ return true;
16755
+ };
16756
+ /**
16757
+ * What pending change, if any, is the one-sided `piece` of the insertion
16758
+ * at `index` this rejection removes, `kept` boundaries kept from it last
16759
+ * in `out`: an insertion, or a removal not resolved with it. A cut the
16760
+ * insertion records across its place leaves no one-sided piece.
16761
+ */
16762
+ const pendingOneSidedPiece = ({ index, piece, joins, kept }) => {
16763
+ if (piece === void 0 || (joins?.remove ?? 0) > 0) return void 0;
16764
+ const record = piece === "after" ? pending[index + 1] : itemBefore(out, out.length - kept)?.node;
16765
+ if (record === void 0 || !isTrackedWrapper(record)) return void 0;
16766
+ if (isAddedRevision(record)) return "insertion";
16767
+ return isRemovedRevisionNode(record) && !resolution.ids.has(record.info.id) ? "removal" : void 0;
16037
16768
  };
16038
16769
  /**
16039
16770
  * Boundaries a rejection kept from new content joined to nothing, standing
@@ -16053,15 +16784,19 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16053
16784
  const handKeptToFacingJoins = ({ index, kept, standing, inEdgeRecords, boundariesOnly, cuts }) => {
16054
16785
  const previousAt = out.length - standing - 1;
16055
16786
  const facing = (node, side) => {
16056
- if (node === void 0 || !isTrackedWrapper(node) || !isAddedRevision(node) || resolution.ids.has(node.info.id)) return void 0;
16787
+ if (node === void 0 || !isTrackedWrapper(node) || !isAddedRevision(node) || resolution.ids.has(node.info.id) && side === "after") return void 0;
16057
16788
  const join = node.resolutionJoins?.[side] ?? 0;
16058
16789
  const date = node.info.date ?? "";
16059
16790
  if (join === 0 || holdsSeamJoin(node, side)) return void 0;
16060
- if (date < kept.from) return cuts ? void 0 : {
16061
- join,
16062
- kept,
16063
- made: "earlier"
16064
- };
16791
+ if (date < kept.from) {
16792
+ const edgeRecord = side === "before" ? node.content.at(0) : node.content.at(-1);
16793
+ if (cuts || edgeRecord !== void 0 && isRemovedRevisionNode(edgeRecord)) return void 0;
16794
+ return {
16795
+ join,
16796
+ kept,
16797
+ made: "earlier"
16798
+ };
16799
+ }
16065
16800
  if (date === kept.from) return void 0;
16066
16801
  const acrossNode = side === "before" ? out[previousAt]?.node : pending[index + 1];
16067
16802
  const facingSide = side === "before" ? "after" : "before";
@@ -16073,6 +16808,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16073
16808
  date: ""
16074
16809
  };
16075
16810
  if (acrossJoin.depth > 0 && acrossJoin.date < kept.from) return void 0;
16811
+ if (heldAcross(index, side)) return void 0;
16076
16812
  const count = acrossJoin.depth > 1 ? 0 : inEdgeRecords[side === "before" ? "last" : "first"];
16077
16813
  if (cuts && count === 0) return void 0;
16078
16814
  return {
@@ -16116,7 +16852,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16116
16852
  side: "before",
16117
16853
  depth: nextFacing.join
16118
16854
  }).takesKept) {
16119
- nameKeptPiece(out.length - recordsFrom(out.length - 1, -1, nextFacing.kept.count), out.length, "after");
16855
+ nameKeptPiece(out.length - recordsFrom(out.length - 1, -1, nextFacing.kept.count), out.length, keptCutHolders({ after: changeAtEdge(next, "start") }));
16120
16856
  if (nextFacing.made === "later") pending[index + 1] = closedToward(next, "before", nextFacing.kept.count);
16121
16857
  }
16122
16858
  if (previous !== void 0 && previousFacing !== void 0 && handJoin({
@@ -16124,7 +16860,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16124
16860
  side: "after",
16125
16861
  depth: previousFacing.join
16126
16862
  }).takesKept) {
16127
- nameKeptPiece(previousAt + 1, previousAt + 1 + recordsFrom(previousAt + 1, 1, previousFacing.kept.count), "before");
16863
+ nameKeptPiece(previousAt + 1, previousAt + 1 + recordsFrom(previousAt + 1, 1, previousFacing.kept.count), keptCutHolders({ before: changeAtEdge(previous.node, "end") }));
16128
16864
  if (previousFacing.made === "later") {
16129
16865
  const closed = closedToward(previous.node, "after", previousFacing.kept.count);
16130
16866
  carryResolutionState(resolution, previous.node, closed);
@@ -16141,12 +16877,41 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16141
16877
  const nameKeptWaitedOn = (groups, kept, index) => {
16142
16878
  const first = out.length - kept;
16143
16879
  const waitedOn = (node, facing) => node !== void 0 && isTrackedWrapper(node) && isAddedRevision(node) && node.resolutionJoins?.[facing] === 0 && groups.some(({ blockers }) => blockers.includes(node.info.id));
16144
- const before = waitedOn(itemBefore(out, first)?.node, "after");
16145
- const after = waitedOn(pending[index + 1], "before");
16146
- if (!before && !after) return;
16147
- let piece = before ? "before" : "after";
16148
- if (before && after) piece = "both";
16149
- nameKeptPiece(first, out.length, piece);
16880
+ const left = itemBefore(out, first)?.node;
16881
+ const right = pending[index + 1];
16882
+ nameKeptPiece(first, out.length, keptCutHolders({
16883
+ before: waitedOn(left, "after") ? changeAtEdge(left, "end") : void 0,
16884
+ after: waitedOn(right, "before") ? changeAtEdge(right, "start") : void 0
16885
+ }));
16886
+ };
16887
+ /** Update markers beside a revision when its edge passes to another. */
16888
+ const handKeptBeside = ({ index, side, from, to }) => {
16889
+ const markerSide = side === "before" ? "after" : "before";
16890
+ const transfer = {
16891
+ side: markerSide,
16892
+ from,
16893
+ to
16894
+ };
16895
+ if (side === "before") {
16896
+ for (let at = out.length - 1; at >= 0; at -= 1) {
16897
+ const occurrence = out[at];
16898
+ if (occurrence === void 0 || !keptCutHeldBy(occurrence.node, {
16899
+ side: markerSide,
16900
+ id: from
16901
+ })) break;
16902
+ const next = withKeptCutHolderHandedOver(occurrence.node, transfer, resolution.relocated.nodes);
16903
+ out[at] = occurrenceOf(next, occurrence);
16904
+ }
16905
+ return;
16906
+ }
16907
+ for (let at = index + 1; at < pending.length; at += 1) {
16908
+ const marker = pending[at];
16909
+ if (marker === void 0 || !keptCutHeldBy(marker, {
16910
+ side: markerSide,
16911
+ id: from
16912
+ })) break;
16913
+ pending[at] = withKeptCutHolderHandedOver(marker, transfer, resolution.relocated.nodes);
16914
+ }
16150
16915
  };
16151
16916
  /**
16152
16917
  * Rejecting an insertion cancels a pending insertion's join facing it:
@@ -16171,15 +16936,196 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16171
16936
  const own = side === "after" ? joins?.before : joins?.after;
16172
16937
  return neighbourDate < date && (own ?? 0) > 0;
16173
16938
  };
16174
- const beyond = (neighbour, side) => made === "later" ? Math.min((neighbour.resolutionJoins?.[side] ?? 0) - 1, joins === void 0 ? 0 : recordJoin(joins, side)) : 0;
16175
- const previous = out.at(-1);
16939
+ const joinedFromBeyond = (side) => {
16940
+ const across = side === "before" ? out.at(-1)?.node : pending[index + 1];
16941
+ const facing = side === "before" ? "after" : "before";
16942
+ return across !== void 0 && isTrackedWrapper(across) && isAddedRevision(across) && !resolution.ids.has(across.info.id) ? recordJoin(across.resolutionJoins ?? {
16943
+ before: 0,
16944
+ after: 0,
16945
+ remove: 0
16946
+ }, facing) : 0;
16947
+ };
16948
+ const fromBeyond = {
16949
+ before: joinedFromBeyond("before"),
16950
+ after: joinedFromBeyond("after")
16951
+ };
16952
+ const beyond = (neighbour, side) => made === "later" ? Math.min((neighbour.resolutionJoins?.[side] ?? 0) - 1, Math.max(joins === void 0 ? 0 : recordJoin(joins, side), fromBeyond[side])) : 0;
16953
+ const handed = {
16954
+ before: false,
16955
+ after: false
16956
+ };
16957
+ const retiredFacing = (neighbour, side) => {
16958
+ const depth = made === "later" && joins !== void 0 && namesSide(index, side) ? Math.min((neighbour.resolutionJoins?.[side] ?? 0) - 1, joins[side]) : 0;
16959
+ if (depth <= 0) return withJoinRetired(neighbour, side, beyond(neighbour, side));
16960
+ handKeptBeside({
16961
+ index,
16962
+ side,
16963
+ from: node.info.id,
16964
+ to: neighbour.info.id
16965
+ });
16966
+ handed[side] = true;
16967
+ return withJoinClosed(neighbour, side, depth);
16968
+ };
16969
+ let before = out.length - 1;
16970
+ let after = index + 1;
16971
+ if (made === "later") {
16972
+ for (let marker = out[before]?.node; marker !== void 0 && keptCutHeldBy(marker, {
16973
+ side: "after",
16974
+ id: node.info.id
16975
+ }); marker = out[before]?.node) before -= 1;
16976
+ for (let marker = pending[after]; marker !== void 0 && keptCutHeldBy(marker, {
16977
+ side: "before",
16978
+ id: node.info.id
16979
+ }); marker = pending[after]) after += 1;
16980
+ }
16981
+ const previous = out[before];
16176
16982
  if (facesNode(previous?.node, "after")) {
16177
- const retired = withJoinRetired(previous.node, "after", beyond(previous.node, "after"));
16983
+ const retired = retiredFacing(previous.node, "after");
16178
16984
  carryResolutionState(resolution, previous.node, retired);
16179
- out[out.length - 1] = occurrenceOf(retired, previous);
16985
+ out[before] = occurrenceOf(retired, previous);
16986
+ }
16987
+ const next = pending[after];
16988
+ if (facesNode(next, "before")) pending[after] = retiredFacing(next, "before");
16989
+ return handed;
16990
+ };
16991
+ /**
16992
+ * Whether the removed insertion at `index` holds, by its join on `side`
16993
+ * closed to records, the piece of the kept markers standing there: they
16994
+ * name its side.
16995
+ */
16996
+ const namesSide = (index, side) => {
16997
+ const node = pending[index];
16998
+ if (node === void 0 || !isTrackedWrapper(node)) return false;
16999
+ const joins = node.resolutionJoins;
17000
+ if (joins === void 0 || joins[side] === 0 || joins.plainSides?.includes(side) !== true) return false;
17001
+ const marker = side === "before" ? out.at(-1)?.node : pending[index + 1];
17002
+ return marker !== void 0 && standsInKeptCut(marker) && keptCutPiece(marker) === (side === "before" ? "after" : "before") && keptCutHeldBy(marker, {
17003
+ side: side === "before" ? "after" : "before",
17004
+ id: node.info.id
17005
+ });
17006
+ };
17007
+ /**
17008
+ * The kept markers whose piece the rejected insertion at `index` holds by
17009
+ * its join on one side, closed to records, moved into the record standing
17010
+ * across it that its join on the other side reaches, as deep as both
17011
+ * joins go: that record holds a piece of their cut too. Rejecting the
17012
+ * insertion before that record's own insertion was accepted hands their
17013
+ * name to it (see {@link retireFacingJoins}), and accepting it then
17014
+ * places them there. The sides whose markers moved.
17015
+ */
17016
+ const placeNamedKeptAcross = (index) => {
17017
+ const placed = {
17018
+ before: false,
17019
+ after: false
17020
+ };
17021
+ const node = pending[index];
17022
+ if (node === void 0 || !isTrackedWrapper(node)) return placed;
17023
+ const joins = node.resolutionJoins;
17024
+ if (joins === void 0) return placed;
17025
+ const names = (marker, piece) => marker !== void 0 && standsInKeptCut(marker) && keptCutPiece(marker) === piece && keptCutHeldBy(marker, {
17026
+ side: piece,
17027
+ id: node.info.id
17028
+ });
17029
+ const holds = (record) => record !== void 0 && !isTrackedWrapper(record) && !isStandingBoundary(record) && childNodes(record) !== void 0;
17030
+ const consumed = (markers) => markers.map((marker) => withKeptCutPieceConsumed(marker, resolution.relocated.nodes));
17031
+ if (namesSide(index, "before") && recordJoin(joins, "after") > 0) {
17032
+ const record = pending[index + 1];
17033
+ let start = out.length;
17034
+ while (names(out[start - 1]?.node, "after")) start -= 1;
17035
+ const into = holds(record) ? withBoundariesAtEdge(record, consumed(out.slice(start).map(({ node: marker }) => marker)), Math.min(joins.before, joins.after), "start") : void 0;
17036
+ if (into !== void 0) {
17037
+ pending[index + 1] = into;
17038
+ out.splice(start);
17039
+ placed.before = true;
17040
+ }
16180
17041
  }
17042
+ const joinedBefore = Math.max(recordJoin(joins, "before"), exactSeams.get(out.length) ?? 0);
17043
+ if (namesSide(index, "after") && joinedBefore > 0) {
17044
+ const previous = out.at(-1);
17045
+ const record = previous?.node;
17046
+ let end = index + 1;
17047
+ while (names(pending[end], "before")) end += 1;
17048
+ const into = holds(record) ? withBoundariesAtEdge(record, consumed(pending.slice(index + 1, end)), Math.min(joinedBefore, joins.after), "end") : void 0;
17049
+ if (previous !== void 0 && into !== void 0) {
17050
+ carryResolutionState(resolution, previous.node, into);
17051
+ out[out.length - 1] = occurrenceOf(into, previous);
17052
+ for (let at = index + 1; at < end; at += 1) placedInside.add(at);
17053
+ placed.after = true;
17054
+ }
17055
+ }
17056
+ return placed;
17057
+ };
17058
+ /**
17059
+ * The pending insertion at `index`, emptied by this resolution of the
17060
+ * changes it held while it stays pending, hands its joins on as accepting
17061
+ * it does: a pending insertion beside it, of the record it was made in,
17062
+ * takes its join toward the other side, a level less deep for its own
17063
+ * wrapper, where something there joins it.
17064
+ */
17065
+ const handEmptiedJoin = (index) => {
17066
+ const node = pending[index];
17067
+ const joins = node !== void 0 && isTrackedWrapper(node) ? node.resolutionJoins : void 0;
17068
+ if (joins === void 0) return;
17069
+ const takes = (beside) => beside !== void 0 && isTrackedWrapper(beside) && isAddedRevision(beside) && beside.resolutionJoins !== void 0 && !resolution.ids.has(beside.info.id);
16181
17070
  const next = pending[index + 1];
16182
- if (facesNode(next, "before")) pending[index + 1] = withJoinRetired(next, "before", beyond(next, "before"));
17071
+ const throughAfter = Math.min(recordJoin(joins, "before"), joins.after - 1);
17072
+ if (takes(next) && throughAfter > 0) pending[index + 1] = handJoin({
17073
+ node: next,
17074
+ side: "before",
17075
+ depth: throughAfter
17076
+ }).node;
17077
+ const previous = out.at(-1);
17078
+ const throughBefore = Math.min(recordJoin(joins, "after"), joins.before - 1);
17079
+ if (previous !== void 0 && takes(previous.node) && throughBefore > 0) {
17080
+ const handed = handJoin({
17081
+ node: previous.node,
17082
+ side: "after",
17083
+ depth: throughBefore
17084
+ }).node;
17085
+ carryResolutionState(resolution, previous.node, handed);
17086
+ out[out.length - 1] = occurrenceOf(handed, previous);
17087
+ }
17088
+ };
17089
+ /**
17090
+ * The sides of the removed deletion at `index` whose kept markers name it
17091
+ * as their cut's piece and face, across its place, a pending insertion
17092
+ * joined toward its content: that insertion holds a piece of the record
17093
+ * the deleted content was, and keeps their name, as it does when the
17094
+ * deletion goes with the insertion holding it.
17095
+ */
17096
+ const namedKeptFacedAcross = (index) => {
17097
+ const faced = {
17098
+ before: false,
17099
+ after: false
17100
+ };
17101
+ const node = pending[index];
17102
+ if (node === void 0 || !isTrackedWrapper(node)) return faced;
17103
+ const joinedToward = (across, side) => across !== void 0 && isTrackedWrapper(across) && isAddedRevision(across) && !resolution.ids.has(across.info.id) && (across.resolutionJoins?.[side] ?? 0) > 0;
17104
+ const names = (marker, side) => marker !== void 0 && keptCutPiece(marker) === side && keptCutHeldBy(marker, {
17105
+ side,
17106
+ id: node.info.id
17107
+ });
17108
+ const before = out.at(-1)?.node;
17109
+ const after = pending[index + 1];
17110
+ if (names(before, "after") && joinedToward(after, "before")) {
17111
+ handKeptBeside({
17112
+ index,
17113
+ side: "before",
17114
+ from: node.info.id,
17115
+ to: after.info.id
17116
+ });
17117
+ faced.before = true;
17118
+ }
17119
+ if (names(after, "before") && joinedToward(before, "after")) {
17120
+ handKeptBeside({
17121
+ index,
17122
+ side: "after",
17123
+ from: node.info.id,
17124
+ to: before.info.id
17125
+ });
17126
+ faced.after = true;
17127
+ }
17128
+ return faced;
16183
17129
  };
16184
17130
  const recordExactSeam = (index, depth) => {
16185
17131
  if (depth > 0) exactSeams.set(index, Math.max(exactSeams.get(index) ?? 0, depth));
@@ -16243,12 +17189,15 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16243
17189
  * name `piece` as the side taking them: the earliest revision they were
16244
17190
  * kept from and how many boundaries they stand for.
16245
17191
  */
16246
- const keptByPiece = (at, from, step, piece) => {
17192
+ const keptByPiece = (at, from, step, { side, id }) => {
16247
17193
  const dates = [];
16248
17194
  let count = 0;
16249
17195
  for (let index = from;; index += step) {
16250
17196
  const node = at(index);
16251
- if (node === void 0 || !standsInKeptCut(node) || keptCutPiece(node) !== piece) break;
17197
+ if (node === void 0 || !standsInKeptCut(node) || keptCutPiece(node) !== side || !keptCutHeldBy(node, {
17198
+ side,
17199
+ id
17200
+ })) break;
16252
17201
  const date = keptCutFrom(node);
16253
17202
  if (date !== void 0) dates.push(date);
16254
17203
  count += keptBoundaryCount([node]);
@@ -16264,9 +17213,12 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16264
17213
  * its side, or both sides, as their cut's piece: those `out` holds before
16265
17214
  * `before` and those after it in `pending`. Its removal consumes the name;
16266
17215
  * the earliest revision they were kept from and how many boundaries they
16267
- * stand for.
17216
+ * stand for. Those on a side whose name content made inside the change
17217
+ * took over (`handed`) keep it.
16268
17218
  */
16269
- const takeKeptBeside = (index, before, takesSeam) => {
17219
+ const takeKeptBeside = ({ index, before, takesSeam, handed }) => {
17220
+ const holder = pending[index];
17221
+ if (holder === void 0 || !isTrackedWrapper(holder)) return void 0;
16270
17222
  const dates = [];
16271
17223
  let count = 0;
16272
17224
  const take = (at, from, step, piece, put) => {
@@ -16274,6 +17226,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16274
17226
  const node = at(position);
16275
17227
  if (node === void 0 || !standsInKeptCut(node)) return;
16276
17228
  const named = keptCutPiece(node);
17229
+ if (!keptCutHeldBy(node, {
17230
+ side: piece,
17231
+ id: holder.info.id
17232
+ })) return;
16277
17233
  if (named !== piece && (named !== "both" || !takesSeam)) return;
16278
17234
  const date = keptCutFrom(node);
16279
17235
  if (date !== void 0) dates.push(date);
@@ -16281,11 +17237,11 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16281
17237
  put(position, withKeptCutPieceConsumed(node, resolution.relocated.nodes));
16282
17238
  }
16283
17239
  };
16284
- take((position) => out[position]?.node, before - 1, -1, "after", (position, node) => {
17240
+ if (!handed.before) take((position) => out[position]?.node, before - 1, -1, "after", (position, node) => {
16285
17241
  const occurrence = out[position];
16286
17242
  if (occurrence !== void 0) out[position] = occurrenceOf(node, occurrence);
16287
17243
  });
16288
- take((position) => pending[position], index + 1, 1, "before", (position, node) => {
17244
+ if (!handed.after) take((position) => pending[position], index + 1, 1, "before", (position, node) => {
16289
17245
  pending[position] = node;
16290
17246
  });
16291
17247
  const earliest = dates.toSorted().at(0);
@@ -16365,19 +17321,24 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16365
17321
  * standing beside it that its join takes inside its own record, on a side
16366
17322
  * that join meets no record on: those naming its side, as deep as the join.
16367
17323
  */
16368
- const withNamedKept = (content, joins, index) => {
17324
+ const withNamedKept = (content, source, index) => {
17325
+ const { info: { id }, resolutionJoins: joins } = source;
16369
17326
  if (joins === void 0) return content;
16370
17327
  const takenInto = (record, markers, side) => {
16371
17328
  const placed = record === void 0 || isTrackedWrapper(record) ? void 0 : withBoundariesAtEdge(record, markers.map((marker) => withKeptCutPieceConsumed(marker, resolution.relocated.nodes)), joins[side], side === "before" ? "start" : "end");
16372
17329
  if (record !== void 0 && placed !== void 0) carryResolutionState(resolution, record, placed);
16373
17330
  return placed;
16374
17331
  };
16375
- const names = (node, piece) => node !== void 0 && standsInKeptCut(node) && keptCutPiece(node) === piece;
17332
+ const names = (node, piece) => node !== void 0 && standsInKeptCut(node) && keptCutPiece(node) === piece && keptCutHeldBy(node, {
17333
+ side: piece,
17334
+ id
17335
+ });
16376
17336
  let taking = [...content];
16377
17337
  if (joins.plainSides?.includes("before") === true) {
16378
17338
  let start = out.length;
16379
17339
  while (names(itemBefore(out, start)?.node, "after")) start -= 1;
16380
- const placed = takenInto(taking.at(0), out.slice(start).map(({ node }) => node), "before");
17340
+ const first = taking.at(0);
17341
+ const placed = takenInto(first, out.slice(start).map(({ node }) => node), "before");
16381
17342
  const seamAmong = [
16382
17343
  ...exactSeams.keys(),
16383
17344
  ...seams,
@@ -16386,16 +17347,27 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16386
17347
  if (placed !== void 0 && !seamAmong) {
16387
17348
  out.splice(start);
16388
17349
  taking = [placed, ...taking.slice(1)];
16389
- }
17350
+ } else if (first !== void 0 && isTrackedWrapper(first)) handKeptBeside({
17351
+ index,
17352
+ side: "before",
17353
+ from: id,
17354
+ to: first.info.id
17355
+ });
16390
17356
  }
16391
17357
  if (joins.plainSides?.includes("after") === true) {
16392
17358
  let end = index + 1;
16393
17359
  while (names(pending[end], "before")) end += 1;
16394
- const placed = takenInto(taking.at(-1), pending.slice(index + 1, end), "after");
17360
+ const last = taking.at(-1);
17361
+ const placed = takenInto(last, pending.slice(index + 1, end), "after");
16395
17362
  if (placed !== void 0) {
16396
17363
  for (let at = index + 1; at < end; at += 1) placedInside.add(at);
16397
17364
  taking = [...taking.slice(0, -1), placed];
16398
- }
17365
+ } else if (last !== void 0 && isTrackedWrapper(last)) handKeptBeside({
17366
+ index,
17367
+ side: "after",
17368
+ from: id,
17369
+ to: last.info.id
17370
+ });
16399
17371
  }
16400
17372
  return taking;
16401
17373
  };
@@ -16505,7 +17477,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16505
17477
  });
16506
17478
  const cut = { keptFrom: node.info.date ?? "" };
16507
17479
  const kept = keptOf(removalContent).map((boundary) => isKeptBoundaryCarrier(boundary) ? withKeptCutsRecorded(boundary, cut, resolution.relocated.nodes) : boundary);
16508
- if (resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) retireFacingJoins(index, node, kept.length === 0 ? "later" : "laterInWrapper");
17480
+ const handedKept = resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) ? retireFacingJoins(index, node, kept.length === 0 ? "later" : "laterInWrapper") : {
17481
+ before: false,
17482
+ after: false
17483
+ };
16509
17484
  const keptStart = out.length;
16510
17485
  appendUnowned(kept);
16511
17486
  const piece = resolution.decision === REVISION_DECISIONS.REJECT && joins !== void 0 && !resolution.deferredOnlyRemovals.has(joins) ? oneSidedKeptPiece(joins) : void 0;
@@ -16524,7 +17499,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16524
17499
  const at = piece === "before" ? out.length - (kept.length - inside) : out.length;
16525
17500
  const enclosingCut = enclosingRecordCut(node, index);
16526
17501
  const closedOn = (side) => node.resolutionJoins?.plainSides?.includes(side) === true;
16527
- const cutGoes = piece === void 0 && enclosingCut === void 0 && madeInNewContent(node, index) && cutLevelsOnceResolved(node, index) === 0;
17502
+ const cutGoes = piece === void 0 && enclosingCut === void 0 && (madeInNewContent(node, index) || cutsEdgeOfRemovedInsertion(node, index)) && cutLevelsOnceResolved(node, index) === 0;
16528
17503
  const depth = Math.max(node.resolutionJoins?.remove ?? 0, enclosingCut?.depth ?? 0, piece === void 0 || joins === void 0 ? 0 : recordJoin(joins, piece));
16529
17504
  if (!cutGoes) floating.set(at, {
16530
17505
  count: inside,
@@ -16538,7 +17513,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16538
17513
  ...joins !== void 0 && resolution.deferredOnlyRemovals.has(joins) && { cut: "deferred" }
16539
17514
  });
16540
17515
  }
16541
- if (inside > 0 && piece !== void 0 && (joins?.remove ?? 0) === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) placeOneSidedKept({
17516
+ const placedOneSided = inside > 0 && piece !== void 0 && (joins?.remove ?? 0) === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) && placeOneSidedKept({
16542
17517
  index,
16543
17518
  piece,
16544
17519
  depth: piece === "after" ? joins?.after ?? 0 : joins?.before ?? 0,
@@ -16546,7 +17521,23 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16546
17521
  inside,
16547
17522
  edge: removalContent[(piece === "after" ? lastRecord : firstRecord) ?? -1]
16548
17523
  });
16549
- if (kept.length > 0 && joins !== void 0 && joins.before === 0 && joins.after === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) handKeptToFacingJoins({
17524
+ const pendingPiece = placedOneSided ? void 0 : pendingOneSidedPiece({
17525
+ index,
17526
+ piece,
17527
+ joins,
17528
+ kept: kept.length
17529
+ });
17530
+ if (inside > 0 && piece !== void 0 && pendingPiece === "removal" && isAddedRevision(node) && (joins?.deferredRemove ?? []).length === 0 && !heldAcross(index, piece === "after" ? "before" : "after")) {
17531
+ const first = out.length - kept.length;
17532
+ if (piece === "before") {
17533
+ const before = changeAtEdge(itemBefore(out, first)?.node, "end");
17534
+ nameKeptPiece(first, first + inside, keptCutHolders({ before }));
17535
+ } else {
17536
+ const after = changeAtEdge(pending[index + 1], "start");
17537
+ nameKeptPiece(out.length - inside, out.length, keptCutHolders({ after }));
17538
+ }
17539
+ }
17540
+ if (kept.length > 0 && joins !== void 0 && !placedOneSided && (joins.before === 0 && joins.after === 0 || pendingPiece === "insertion") && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) handKeptToFacingJoins({
16550
17541
  index,
16551
17542
  kept: {
16552
17543
  from: node.info.date ?? "",
@@ -16570,11 +17561,27 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16570
17561
  spanning: trackedWithin(node.content),
16571
17562
  piece: far
16572
17563
  });
17564
+ const facedAcross = kept.length === 0 && !isAddedRevision(node) ? namedKeptFacedAcross(index) : {
17565
+ before: false,
17566
+ after: false
17567
+ };
16573
17568
  if (node.resolutionJoins === void 0) seams.push(out.length);
16574
17569
  else if ((node.resolutionJoins.plainSides?.length ?? 0) > 0 && !resolution.deferredOnlyRemovals.has(node.resolutionJoins)) {
16575
17570
  plainSeams.add(out.length);
16576
17571
  for (let at = out.length - kept.length; at <= out.length; at += 1) if (floating.has(at)) folds.push(at);
16577
- takeKeptBeside(index, keptStart, false);
17572
+ const placedAcross = kept.length === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) ? placeNamedKeptAcross(index) : {
17573
+ before: false,
17574
+ after: false
17575
+ };
17576
+ takeKeptBeside({
17577
+ index,
17578
+ before: keptStart,
17579
+ takesSeam: false,
17580
+ handed: {
17581
+ before: handedKept.before || placedAcross.before || facedAcross.before,
17582
+ after: handedKept.after || placedAcross.after || facedAcross.after
17583
+ }
17584
+ });
16578
17585
  } else {
16579
17586
  const around = floating.has(out.length) ? enclosingRecordCut(node, index) : void 0;
16580
17587
  const removalCut = Math.max(cutLevelsOnceResolved(node, index), around?.side === void 0 ? around?.depth ?? 0 : 0);
@@ -16591,7 +17598,19 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16591
17598
  after: recordJoin(joins, "after")
16592
17599
  });
16593
17600
  }
16594
- const beside = takeKeptBeside(index, keptStart, removalCut > 0);
17601
+ const faced = removalCut === 0 ? facedAcross : {
17602
+ before: false,
17603
+ after: false
17604
+ };
17605
+ const beside = takeKeptBeside({
17606
+ index,
17607
+ before: keptStart,
17608
+ takesSeam: removalCut > 0,
17609
+ handed: {
17610
+ before: handedKept.before || faced.before,
17611
+ after: handedKept.after || faced.after
17612
+ }
17613
+ });
16595
17614
  if (removalCut > 0 && beside !== void 0) exactKept.set(out.length, beside);
16596
17615
  if (removalCut === 0 && kept.length === 0 && isRemovedRevisionNode(node)) placeBetweenRemovedPieces(node, index);
16597
17616
  }
@@ -16622,8 +17641,12 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16622
17641
  resolution,
16623
17642
  path: [...path, index]
16624
17643
  });
16625
- const content = isAddedRevision(node) && resolution.decision === REVISION_DECISIONS.ACCEPT ? withNamedKept(withPayloadEdgesClosed(acceptCopyOriginAncestor(resolved.nodes), node.resolutionJoins, resolution), node.resolutionJoins, index) : resolved.nodes;
17644
+ const content = isAddedRevision(node) && resolution.decision === REVISION_DECISIONS.ACCEPT ? withNamedKept(withPayloadEdgesClosed(acceptCopyOriginAncestor(resolved.nodes), node.resolutionJoins, resolution), node, index) : resolved.nodes;
16626
17645
  if (content.length === 0 && node.content.length > 0) {
17646
+ if (isAddedRevision(node)) {
17647
+ placeNamedKeptAcross(index);
17648
+ namedKeptFacedAcross(index);
17649
+ }
16627
17650
  folds.push(out.length);
16628
17651
  if ((node.resolutionJoins?.plainSides?.length ?? 0) > 0) plainSeams.add(out.length);
16629
17652
  continue;
@@ -16637,7 +17660,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16637
17660
  recordKeptJoin(out.length, node);
16638
17661
  if (isRemovedRevisionNode(node)) ownContentAfter.add(out.length);
16639
17662
  }
16640
- const keptBefore = joined > 0 ? keptByPiece((at) => out[at]?.node, out.length - 1, -1, "after") : void 0;
17663
+ const keptBefore = joined > 0 ? keptByPiece((at) => out[at]?.node, out.length - 1, -1, {
17664
+ side: "after",
17665
+ id: node.info.id
17666
+ }) : void 0;
16641
17667
  if (keptBefore !== void 0) exactKept.set(out.length, {
16642
17668
  ...keptBefore,
16643
17669
  piece: "after"
@@ -16677,7 +17703,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16677
17703
  recordKeptJoin(out.length, node);
16678
17704
  if (isRemovedRevisionNode(node)) ownContentBefore.add(out.length);
16679
17705
  }
16680
- const keptAfter = joined > 0 ? keptByPiece((at) => pending[at], index + 1, 1, "before") : void 0;
17706
+ const keptAfter = joined > 0 ? keptByPiece((at) => pending[at], index + 1, 1, {
17707
+ side: "before",
17708
+ id: node.info.id
17709
+ }) : void 0;
16681
17710
  if (keptAfter !== void 0) exactKept.set(out.length, {
16682
17711
  ...keptAfter,
16683
17712
  piece: "before"
@@ -16732,6 +17761,11 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16732
17761
  changed = true;
16733
17762
  const keepsEmptiedControl = node.type === "inlineSdt" && children.some((child) => isTrackedWrapper(child) && child.resolutionJoins?.holdsControlText === true);
16734
17763
  if ((isTrackedWrapper(node) || resolution.decision === REVISION_DECISIONS.ACCEPT && !keepsEmptiedControl || children.some((child) => isAddedRevision(child) && child.resolutionJoins?.emptiedHolder === true)) && inner.nodes.length === 0 && children.length > 0) {
17764
+ if (isAddedRevision(node)) {
17765
+ placeNamedKeptAcross(index);
17766
+ if (resolution.decision === REVISION_DECISIONS.ACCEPT) namedKeptFacedAcross(index);
17767
+ handEmptiedJoin(index);
17768
+ }
16735
17769
  folds.push(out.length);
16736
17770
  if (!isTrackedWrapper(node)) closeCutsAtEmptiedPiece({
16737
17771
  first: node,
@@ -17323,7 +18357,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
17323
18357
  if (standingKept > 0 && keptFrom !== void 0 && takesKept && !yieldsKept) {
17324
18358
  const receiverBefore = side === "after";
17325
18359
  const records = keptRecordsFacing(index, receiverBefore ? "before" : "after");
17326
- tookKept = nameKeptPiece(receiverBefore ? first : seam - records, receiverBefore ? first + records : seam, receiverBefore ? "before" : "after");
18360
+ tookKept = nameKeptPiece(receiverBefore ? first : seam - records, receiverBefore ? first + records : seam, keptCutHolders(receiverBefore ? { before: changeAtEdge(node, "end") } : { after: changeAtEdge(node, "start") }));
17327
18361
  }
17328
18362
  if (node === occurrence.node && !tookKept) return;
17329
18363
  out[index] = occurrenceOf(node, occurrence);
@@ -17414,8 +18448,17 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
17414
18448
  const facingAt = blockedBefore ? keptEnd : seam;
17415
18449
  const facingSide = blockedBefore ? "before" : "after";
17416
18450
  const inside = blockedSide !== "both" && facingJoinAt(facingAt, blockedBefore ? "after" : "before") > 0 ? keptRecordsFacing(facingAt, facingSide) : standingKept;
17417
- nameKeptPiece(blockedBefore ? first : seam - inside, blockedBefore ? first + inside : seam, blockedSide);
17418
- nameKeptPiece(first, seam, "both");
18451
+ const insideStart = blockedBefore ? first : seam - inside;
18452
+ const insideEnd = blockedBefore ? first + inside : seam;
18453
+ const holders = keptCutHolders({
18454
+ before: blockedBefore ? changeAtEdge(out[keptEnd]?.node, "end") : void 0,
18455
+ after: blockedAfter ? changeAtEdge(out[seam]?.node, "start") : void 0
18456
+ });
18457
+ nameKeptPiece(insideStart, insideEnd, holders);
18458
+ if (holders !== void 0 && inside < standingKept) nameKeptPiece(first, seam, {
18459
+ ...holders,
18460
+ scope: "seam"
18461
+ });
17419
18462
  continue;
17420
18463
  }
17421
18464
  if (handedOver.size > 0) continue;
@@ -17660,16 +18703,18 @@ const deferSplitSeam = ({ left, right, depth }) => {
17660
18703
  while (keptFrom >= 0 && standingInKeptCut(left.at(keptFrom))) keptFrom -= 1;
17661
18704
  let keptTo = rightStart;
17662
18705
  while (standingInKeptCut(right.at(keptTo))) keptTo += 1;
17663
- const named = (node, piece) => withKeptCutPieceRecorded(node, piece, /* @__PURE__ */ new WeakMap());
18706
+ const known = /* @__PURE__ */ new WeakMap();
18707
+ const leftHolder = keptCutHolders({ after: changeAtEdge(left[leftEnd + 1] ?? (rightStart > 0 ? right.at(0) : void 0), "start") });
18708
+ const rightHolder = keptCutHolders({ before: changeAtEdge(right[rightStart - 1] ?? (leftEnd < left.length - 1 ? left.at(-1) : void 0), "end") });
17664
18709
  const leftRow = left.slice(leftEnd + 1).toReversed();
17665
18710
  const rightRow = right.slice(0, rightStart);
17666
18711
  const atLeft = (node, index) => {
17667
18712
  if (index > leftEnd) return deferred(node, "after", leftRow);
17668
- return index > keptFrom ? named(node, "after") : node;
18713
+ return index > keptFrom && leftHolder !== void 0 ? withKeptCutHoldersRecorded(node, leftHolder, known) : node;
17669
18714
  };
17670
18715
  const atRight = (node, index) => {
17671
18716
  if (index < rightStart) return deferred(node, "before", rightRow);
17672
- return index < keptTo ? named(node, "before") : node;
18717
+ return index < keptTo && rightHolder !== void 0 ? withKeptCutHoldersRecorded(node, rightHolder, known) : node;
17673
18718
  };
17674
18719
  return {
17675
18720
  left: left.map(atLeft),
@@ -18359,6 +19404,7 @@ const removedPieceBoundary = ({ nodes, edge, resolution }) => {
18359
19404
  const settleTwoRecordMarks = (paragraphs, op) => {
18360
19405
  const ids = new Set(op.revisionIds);
18361
19406
  const ops = [];
19407
+ const replacementMarks = /* @__PURE__ */ new Map();
18362
19408
  for (const { paragraph } of paragraphs) {
18363
19409
  const mark = paragraph.pPrMark;
18364
19410
  if (mark?.deletion === void 0) continue;
@@ -18375,6 +19421,7 @@ const settleTwoRecordMarks = (paragraphs, op) => {
18375
19421
  ...mark.info.date === void 0 ? {} : { splitDate: mark.info.date }
18376
19422
  }
18377
19423
  };
19424
+ replacementMarks.set(insertion, deletion);
18378
19425
  ids.delete(insertion);
18379
19426
  } else {
18380
19427
  const { deletion: _deleted, ...added } = mark;
@@ -18389,6 +19436,33 @@ const settleTwoRecordMarks = (paragraphs, op) => {
18389
19436
  review
18390
19437
  });
18391
19438
  }
19439
+ if (replacementMarks.size > 0) {
19440
+ const planned = new Map(ops.map((edit) => [edit.blockId, edit]));
19441
+ for (const { paragraph } of paragraphs) {
19442
+ const blockId = paragraph.paraId ?? "";
19443
+ const existing = planned.get(blockId);
19444
+ const mark = existing === void 0 ? paragraph.pPrMark : existing.review.pPrMark;
19445
+ const target = mark?.takenOverMark;
19446
+ const replacement = target === void 0 ? void 0 : replacementMarks.get(target);
19447
+ if (mark === void 0 || replacement === void 0) continue;
19448
+ const expected = reviewFieldsOf(paragraph);
19449
+ const review = {
19450
+ ...existing?.review ?? expected,
19451
+ pPrMark: {
19452
+ ...mark,
19453
+ takenOverMark: replacement
19454
+ }
19455
+ };
19456
+ if (existing === void 0) ops.push({
19457
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
19458
+ story: op.story,
19459
+ blockId,
19460
+ expected,
19461
+ review
19462
+ });
19463
+ else existing.review = review;
19464
+ }
19465
+ }
18392
19466
  return {
18393
19467
  ops,
18394
19468
  ids: op.revisionIds.filter((id) => ids.has(id))
@@ -18850,6 +19924,8 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
18850
19924
  if (chainCut > depth) depth = Math.min(chainCut, trailing ?? chainCut);
18851
19925
  if (depth !== mark.resolutionJoin) retiredCutDepths.set(idKey(paragraph.paraId ?? ""), depth);
18852
19926
  }
19927
+ const keptBreaks = /* @__PURE__ */ new Set();
19928
+ for (const { paragraph: { pPrMark: mark } } of paragraphs) if (mark !== void 0 && ids.has(mark.info.id) && markWasAdded(mark.kind) === (op.decision === REVISION_DECISIONS.ACCEPT)) keptBreaks.add(mark.info.id);
18853
19929
  for (const location of paragraphs) {
18854
19930
  const { paragraph } = location;
18855
19931
  const paraId = paragraph.paraId ?? "";
@@ -18874,6 +19950,11 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
18874
19950
  });
18875
19951
  }
18876
19952
  let review = resolveParagraphReview(paragraph, resolution, keepsBreak);
19953
+ if (mark?.takenOverMark !== void 0 && keptBreaks.has(mark.takenOverMark) && !keepsBreak) {
19954
+ const { takenOverMark: _takenOverMark, ...positional } = mark;
19955
+ review ??= reviewFieldsOf(paragraph);
19956
+ review.pPrMark = positional;
19957
+ }
18877
19958
  const retiredDepth = retiredCutDepths.get(idKey(paraId));
18878
19959
  if (retiredDepth !== void 0) {
18879
19960
  const remainingMark = review === void 0 ? paragraph.pPrMark : review.pPrMark;
@@ -18890,6 +19971,31 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
18890
19971
  review
18891
19972
  });
18892
19973
  }
19974
+ const materialized = tryMaterializeResolution({
19975
+ document,
19976
+ story: op.story,
19977
+ locations: paragraphs,
19978
+ inline,
19979
+ join: joins.length === 0 ? { type: "noJoins" } : {
19980
+ type: "plan",
19981
+ prepare: (view) => {
19982
+ const ends = new Map(emptiedEnds);
19983
+ return planContiguousResolutionJoins({
19984
+ document,
19985
+ story: op.story,
19986
+ ...view,
19987
+ joins,
19988
+ planPair: ({ join, first, second }) => joinOps({ package: { document: { content: [first, second] } } }, join, ends)
19989
+ });
19990
+ }
19991
+ },
19992
+ noteReferences,
19993
+ receiverEffects
19994
+ });
19995
+ if (materialized.type === "materialized") return Result.ok({
19996
+ edit: materialized.edit,
19997
+ receiverEffects: materialized.receiverEffects
19998
+ });
18893
19999
  const staged = applyOps(document, inline);
18894
20000
  if (staged.isErr()) return Result.err(staged.error);
18895
20001
  const rows = resolveTableRows({
@@ -20387,10 +21493,12 @@ const withSpan = (cell, span) => {
20387
21493
  const formatting = authored({ ...cell.formatting });
20388
21494
  if (span === 1) delete formatting.gridSpan;
20389
21495
  else formatting.gridSpan = span;
20390
- return {
21496
+ if (Object.keys(formatting).length > 0) return {
20391
21497
  ...cell,
20392
21498
  formatting
20393
21499
  };
21500
+ const { formatting: _formatting, ...plain } = cell;
21501
+ return plain;
20394
21502
  };
20395
21503
  const dividedWidth = (width, parts) => {
20396
21504
  if (width === void 0) return void 0;
@@ -20524,6 +21632,58 @@ const restatedCell = (before, after, fields) => {
20524
21632
  fields
20525
21633
  }).map((propertyChanges) => propertyChanges === void 0 ? after : Object.assign({}, after, { propertyChanges }));
20526
21634
  };
21635
+ /**
21636
+ * A new cell a direct edit makes from `source`, taking its properties, with
21637
+ * `source`'s pending property changes restated over them as records of its
21638
+ * own: rejecting them takes the other properties off the new cell as it
21639
+ * does off `source`.
21640
+ */
21641
+ const copiedPropertyChanges = ({ source, cell, ids }) => {
21642
+ const restated = restatedCell(source, cell, CELL_GRID_FIELDS);
21643
+ if (restated.isErr() || restated.value.propertyChanges === void 0) return restated;
21644
+ const propertyChanges = [];
21645
+ for (const change of restated.value.propertyChanges) {
21646
+ const next = ids.next();
21647
+ if (next.done === true) panic("A copied property change has no revision id.");
21648
+ propertyChanges.push({
21649
+ ...change,
21650
+ info: {
21651
+ ...change.info,
21652
+ id: next.value
21653
+ }
21654
+ });
21655
+ }
21656
+ return Result.ok(Object.assign({}, restated.value, { propertyChanges }));
21657
+ };
21658
+ /**
21659
+ * The revision ids a direct edit gives the records it adds beside pending
21660
+ * ones, such as a new cell's copy of its source's property change: the first
21661
+ * `count` ids of `newIds.revision` no record in the package holds.
21662
+ */
21663
+ const directRevisionIds = ({ document, op, count }) => {
21664
+ if (count === 0) return Result.ok([]);
21665
+ const held = packageIdentityKeyIndex(document.package);
21666
+ const ids = [];
21667
+ for (const id of op.newIds?.revision ?? []) {
21668
+ if (ids.length === count) break;
21669
+ if (!Number.isInteger(id) || id < 0 || id > 2147483647) return refuse$3({
21670
+ op,
21671
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
21672
+ message: "Revision ids must be nonnegative 31-bit integers."
21673
+ });
21674
+ if (ids.includes(id) || held.has(slotKey({
21675
+ space: IDENTITY_SPACES.REVISION,
21676
+ id
21677
+ }))) continue;
21678
+ ids.push(id);
21679
+ }
21680
+ if (ids.length < count) return refuse$3({
21681
+ op,
21682
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
21683
+ message: `This table change keeps pending records under ${count} new revision ids.`
21684
+ });
21685
+ return Result.ok(ids);
21686
+ };
20527
21687
  /** `after`, the direct edit of `before`, with `before`'s pending property changes restated. */
20528
21688
  const restatedRow = (before, after) => restateChanges({
20529
21689
  changes: before.propertyChanges,
@@ -20589,15 +21749,13 @@ const rowExtent = (table, grid, row) => {
20589
21749
  * A grid column stands in the earlier grid unless a pending insertion takes
20590
21750
  * it whole.
20591
21751
  */
20592
- const columnReviews = ({ op, table, grid, leavesRow }) => {
21752
+ const columnReviews = ({ op, table, grid }) => {
20593
21753
  const conflict = (message) => refuse$3({
20594
21754
  op,
20595
21755
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
20596
21756
  message
20597
21757
  });
20598
- const columns = reviewColumns(grid);
20599
- if (columns === void 0) return conflict("Resolve the pending cell insertions and deletions that take part of a column before changing its columns.");
20600
- if (table.rows.some((row, rowIndex) => !leavesRow(rowIndex) && (!statesOwnGrid(row.propertyChanges, row.formatting, ROW_GRID_FIELDS) || row.cells.some((cell) => !statesOwnGrid(cell.propertyChanges, cell.formatting, CELL_SPAN_FIELDS))))) return conflict("Resolve the pending span changes of the rows the column crosses before changing its columns.");
21758
+ const columns = reviewColumns(grid) ?? panic("A column edit across partial records reads both decisions.");
20601
21759
  const gridChange = table.formatting?.gridChange;
20602
21760
  if (gridChange === void 0) return Result.ok(void 0);
20603
21761
  if (gridChange.columnWidths.length !== grid.width - columns.inserted.size) return conflict("Resolve the pending grid change before changing the table's columns.");
@@ -20612,6 +21770,365 @@ const columnReviews = ({ op, table, grid, leavesRow }) => {
20612
21770
  columnWidths
20613
21771
  });
20614
21772
  };
21773
+ /**
21774
+ * Whether a pending record places a column differently once it is accepted
21775
+ * than once it is rejected: a cell insertion or deletion that takes only part
21776
+ * of a column, or a row or cell property change recording other spans or
21777
+ * omissions.
21778
+ */
21779
+ const recordsPlaceColumnsApart = (table, grid) => reviewColumns(grid) === void 0 || table.rows.some((row) => !statesOwnGrid(row.propertyChanges, row.formatting, ROW_GRID_FIELDS) || row.cells.some((cell) => !statesOwnGrid(cell.propertyChanges, cell.formatting, CELL_SPAN_FIELDS)));
21780
+ /** A cell's first paragraph id, which names it in every decision's table. */
21781
+ const cellKey = (cell) => storyParagraphs({ content: cell.content }).at(0)?.paragraph.paraId;
21782
+ /** The rows of the table every cell and property record of which is decided. */
21783
+ const decidedRows = (table, reject, op) => {
21784
+ const decided = withTableRecordsResolved(table, reject);
21785
+ if (decided.isErr() || decided.value.rows.length !== table.rows.length) return void 0;
21786
+ const grid = tableGrid(decided.value, op.type);
21787
+ if (grid.isErr()) return void 0;
21788
+ const rows = [];
21789
+ for (const [index, row] of decided.value.rows.entries()) {
21790
+ const { before, end } = rowExtent(decided.value, grid.value, index);
21791
+ const cells = [];
21792
+ for (const { cell, start, end: cellEnd } of grid.value.rows[index] ?? []) {
21793
+ const key = cellKey(cell);
21794
+ if (key === void 0) return void 0;
21795
+ cells.push({
21796
+ key,
21797
+ start,
21798
+ end: cellEnd
21799
+ });
21800
+ }
21801
+ rows.push({
21802
+ before,
21803
+ end,
21804
+ after: row.formatting?.gridAfter ?? 0,
21805
+ cells
21806
+ });
21807
+ }
21808
+ return rows;
21809
+ };
21810
+ const columnPlace = (row, op) => {
21811
+ const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
21812
+ const column = op.column;
21813
+ if (column < row.before) return { type: "before" };
21814
+ if (insert ? column > row.end + row.after : column >= row.end + row.after) return { type: "leaves" };
21815
+ if (insert ? column > row.end : column >= row.end) return { type: "after" };
21816
+ const spanning = row.cells.find(({ start, end }) => insert ? start < column && column < end : start <= column && column < end);
21817
+ if (spanning !== void 0) return {
21818
+ type: "within",
21819
+ cell: spanning.key,
21820
+ span: spanning.end - spanning.start
21821
+ };
21822
+ return {
21823
+ type: "between",
21824
+ after: row.cells.find(({ end }) => end === column)?.key
21825
+ };
21826
+ };
21827
+ /**
21828
+ * One row's part of a direct column edit, so that accepting every record
21829
+ * gives the edit of the accepted row, and rejecting them that of the
21830
+ * rejected row. `undefined` where no one change of the row does both.
21831
+ */
21832
+ const rowColumnPlan = ({ entries, accepted, rejected, op }) => {
21833
+ const inAccepted = accepted.cells.map(({ key }) => key);
21834
+ const inRejected = rejected.cells.map(({ key }) => key);
21835
+ const placeA = columnPlace(accepted, op);
21836
+ const placeR = columnPlace(rejected, op);
21837
+ if (placeA.type === "leaves" && placeR.type === "leaves") return { type: "unchanged" };
21838
+ if (placeA.type === "before" || placeA.type === "after") {
21839
+ if (placeR.type !== placeA.type) return void 0;
21840
+ return {
21841
+ type: "omission",
21842
+ side: placeA.type === "before" ? "gridBefore" : "gridAfter"
21843
+ };
21844
+ }
21845
+ if (placeR.type === "before" || placeR.type === "after") return void 0;
21846
+ const keys = entries.map(({ cell }) => cellKey(cell));
21847
+ const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
21848
+ const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
21849
+ const spans = /* @__PURE__ */ new Map();
21850
+ const removed = /* @__PURE__ */ new Set();
21851
+ const occupant = insert ? void 0 : entries.findIndex(({ start, end }) => start <= op.column && op.column < end);
21852
+ for (const [index, key] of keys.entries()) {
21853
+ if (key === void 0) return void 0;
21854
+ const presentA = inAccepted.includes(key);
21855
+ const presentR = inRejected.includes(key);
21856
+ const hitA = placeA.type === "within" && placeA.cell === key;
21857
+ const hitR = placeR.type === "within" && placeR.cell === key;
21858
+ if (!insert) {
21859
+ const goesA = hitA && placeA.span === 1;
21860
+ const goesR = hitR && placeR.span === 1;
21861
+ if (presentA && presentR && goesA !== goesR) return void 0;
21862
+ if (goesA || goesR) {
21863
+ removed.add(index);
21864
+ continue;
21865
+ }
21866
+ }
21867
+ const delta = insert ? count : -1;
21868
+ const current = hitA && (insert ? placeR.type !== "between" : occupant === void 0 || occupant === index) ? delta : 0;
21869
+ const earlier = hitR ? delta : 0;
21870
+ if (current === 0 && earlier === 0) continue;
21871
+ const recorded = ((entries[index]?.cell)?.propertyChanges?.length ?? 0) > 0;
21872
+ if (!recorded && presentA && presentR && current !== earlier) return void 0;
21873
+ spans.set(index, recorded ? {
21874
+ current,
21875
+ earlier
21876
+ } : {
21877
+ current: presentA ? current : earlier,
21878
+ earlier: 0
21879
+ });
21880
+ }
21881
+ if (!insert) return {
21882
+ type: "cells",
21883
+ added: void 0,
21884
+ spans,
21885
+ removed
21886
+ };
21887
+ const range = (place, present) => {
21888
+ if (place.type !== "between") return void 0;
21889
+ const lower = place.after === void 0 ? 0 : keys.indexOf(place.after) + 1;
21890
+ const next = keys.findIndex((key, index) => index >= lower && key !== void 0 && present.includes(key));
21891
+ return {
21892
+ lower,
21893
+ upper: next === -1 ? keys.length : next
21894
+ };
21895
+ };
21896
+ const rangeA = range(placeA, inAccepted);
21897
+ const rangeR = range(placeR, inRejected);
21898
+ const ranges = [rangeA, rangeR].filter((each) => each !== void 0);
21899
+ if (ranges.length === 0) return {
21900
+ type: "cells",
21901
+ added: void 0,
21902
+ spans,
21903
+ removed
21904
+ };
21905
+ const at = maxOf(ranges.map(({ lower }) => lower), 0);
21906
+ if (ranges.some(({ lower, upper }) => lower < 0 || at > upper)) return void 0;
21907
+ let kept = "both";
21908
+ if (rangeA === void 0) kept = "reject";
21909
+ else if (rangeR === void 0) kept = "accept";
21910
+ return {
21911
+ type: "cells",
21912
+ added: {
21913
+ at,
21914
+ kept
21915
+ },
21916
+ spans,
21917
+ removed
21918
+ };
21919
+ };
21920
+ /** Every row's part of a direct column edit across records that place it apart. */
21921
+ const columnPlanAcrossRecords = ({ table, grid, op }) => {
21922
+ if (table.formatting?.gridChange !== void 0) return void 0;
21923
+ const accepted = decidedRows(table, false, op);
21924
+ const rejected = decidedRows(table, true, op);
21925
+ if (accepted === void 0 || rejected === void 0) return void 0;
21926
+ const plans = [];
21927
+ for (const index of table.rows.keys()) {
21928
+ const acceptedRow = accepted[index];
21929
+ const rejectedRow = rejected[index];
21930
+ const entries = grid.rows[index];
21931
+ if (acceptedRow === void 0 || rejectedRow === void 0 || entries === void 0) return void 0;
21932
+ const plan = rowColumnPlan({
21933
+ entries,
21934
+ accepted: acceptedRow,
21935
+ rejected: rejectedRow,
21936
+ op
21937
+ });
21938
+ if (plan === void 0) return void 0;
21939
+ plans.push(plan);
21940
+ }
21941
+ return plans;
21942
+ };
21943
+ /** The span field of cell formatting, moved by `delta` columns. */
21944
+ const respanned = (formatting, delta) => {
21945
+ if (delta === 0) return formatting;
21946
+ const next = authored({ ...formatting });
21947
+ const span = (formatting?.gridSpan ?? 1) + delta;
21948
+ if (span === 1) delete next.gridSpan;
21949
+ else next.gridSpan = span;
21950
+ return next;
21951
+ };
21952
+ /** The omission field of row formatting, moved by `delta` columns. */
21953
+ const reomitted = (formatting, side, delta) => {
21954
+ const next = authored({ ...formatting });
21955
+ const value = (formatting?.[side] ?? 0) + delta;
21956
+ if (side === "gridBefore") {
21957
+ if (value === 0) delete next.gridBefore;
21958
+ else next.gridBefore = value;
21959
+ } else if (value === 0) delete next.gridAfter;
21960
+ else next.gridAfter = value;
21961
+ return next;
21962
+ };
21963
+ /**
21964
+ * A direct column edit beside records that place the column apart once
21965
+ * accepted and once rejected. Each row takes the edit as both decisions read
21966
+ * it: a new cell only one of them keeps is recorded as that decision's cell
21967
+ * insertion or deletion, under the author of the row's record, and a span
21968
+ * only one of them changes is changed in the properties that decision gives
21969
+ * the cell. Accepting every record gives the edit of the accepted table, and
21970
+ * rejecting them that of the rejected one; where no table does both, the
21971
+ * edit refuses.
21972
+ */
21973
+ const columnEditAcrossRecords = ({ document, op, table, grid, conflict }) => {
21974
+ const refused = () => conflict("Resolve the pending cell insertions, deletions and span changes that place the column apart before changing its columns.");
21975
+ const plans = columnPlanAcrossRecords({
21976
+ table,
21977
+ grid,
21978
+ op
21979
+ });
21980
+ if (plans === void 0) return refused();
21981
+ const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
21982
+ const addedRows = plans.filter((plan) => plan.type === "cells" && plan.added !== void 0);
21983
+ const fresh = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? freshCells({
21984
+ document,
21985
+ op,
21986
+ ids: op.newBlockIds,
21987
+ count: addedRows.length * count
21988
+ }) : Result.ok([]);
21989
+ if (fresh.isErr()) return Result.err(fresh.error);
21990
+ const recorded = addedRows.filter((plan) => plan.type === "cells" && plan.added?.kept !== "both").length;
21991
+ const ids = directRevisionIds({
21992
+ document,
21993
+ op,
21994
+ count: recorded * count
21995
+ });
21996
+ if (ids.isErr()) return Result.err(ids.error);
21997
+ const freshIds = ids.value.values();
21998
+ const freshCellsLeft = fresh.value.values();
21999
+ const removedCells = [];
22000
+ const rows = [];
22001
+ for (const [rowIndex, row] of table.rows.entries()) {
22002
+ const plan = plans[rowIndex] ?? panic("A row has no plan.");
22003
+ const entries = grid.rows[rowIndex] ?? panic("A row has no grid.");
22004
+ const delta = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? count : -1;
22005
+ switch (plan.type) {
22006
+ case "unchanged":
22007
+ rows.push(row);
22008
+ continue;
22009
+ case "omission": {
22010
+ const next = {
22011
+ ...row,
22012
+ formatting: reomitted(row.formatting, plan.side, delta)
22013
+ };
22014
+ if (row.propertyChanges !== void 0) next.propertyChanges = row.propertyChanges.map((change) => ({
22015
+ ...change,
22016
+ previousFormatting: reomitted(change.previousFormatting, plan.side, delta)
22017
+ }));
22018
+ rows.push(next);
22019
+ continue;
22020
+ }
22021
+ case "cells": break;
22022
+ default: return plan;
22023
+ }
22024
+ const source = row.cells.find((cell) => cell.structuralChange !== void 0)?.structuralChange?.info ?? row.cells.find((cell) => cell.propertyChanges !== void 0)?.propertyChanges?.at(0)?.info ?? row.propertyChanges?.at(0)?.info;
22025
+ const recordInfo = (id) => {
22026
+ if (source === void 0) return panic("A new cell has no record.");
22027
+ const { author, date, initials, suggestionId } = source;
22028
+ return {
22029
+ id,
22030
+ author,
22031
+ ...date === void 0 ? {} : { date },
22032
+ ...initials === void 0 ? {} : { initials },
22033
+ ...suggestionId === void 0 ? {} : { suggestionId }
22034
+ };
22035
+ };
22036
+ const cells = [];
22037
+ const added = () => {
22038
+ const out = [];
22039
+ for (let column = 0; column < count; column += 1) {
22040
+ const next = freshCellsLeft.next();
22041
+ if (next.done === true) panic("A new cell has no paragraph id.");
22042
+ const kept = plan.added?.kept;
22043
+ if (kept === void 0 || kept === "both") {
22044
+ out.push(next.value);
22045
+ continue;
22046
+ }
22047
+ const id = freshIds.next();
22048
+ if (id.done === true) panic("A new cell has no revision id.");
22049
+ out.push({
22050
+ ...next.value,
22051
+ structuralChange: {
22052
+ type: kept === "accept" ? "tableCellInsertion" : "tableCellDeletion",
22053
+ info: recordInfo(id.value)
22054
+ }
22055
+ });
22056
+ }
22057
+ return out;
22058
+ };
22059
+ for (const [index, { cell }] of entries.entries()) {
22060
+ if (plan.added?.at === index) cells.push(...added());
22061
+ if (plan.removed.has(index)) {
22062
+ removedCells.push(cell);
22063
+ continue;
22064
+ }
22065
+ const span = plan.spans.get(index);
22066
+ if (span === void 0) {
22067
+ cells.push(cell);
22068
+ continue;
22069
+ }
22070
+ const next = { ...cell };
22071
+ const formatting = respanned(cell.formatting, span.current);
22072
+ if (formatting === void 0) delete next.formatting;
22073
+ else next.formatting = formatting;
22074
+ const [first, ...rest] = cell.propertyChanges ?? [];
22075
+ const earlier = respanned(first?.previousFormatting ?? {}, span.earlier);
22076
+ if (first !== void 0 && span.earlier !== 0) next.propertyChanges = [{
22077
+ ...first,
22078
+ ...earlier === void 0 ? {} : { previousFormatting: earlier }
22079
+ }, ...rest];
22080
+ cells.push(next);
22081
+ }
22082
+ if (plan.added !== void 0 && plan.added.at >= entries.length) cells.push(...added());
22083
+ if (editRemovesRow({
22084
+ before: row.cells,
22085
+ after: cells
22086
+ })) continue;
22087
+ rows.push({
22088
+ ...row,
22089
+ cells
22090
+ });
22091
+ }
22092
+ if (removedCells.some(reachesPastRemovedCell) || strandsABookmark(removedCells)) return refuse$3({
22093
+ op,
22094
+ reason: DOCUMENT_OP_REFUSAL_REASONS.DEPENDENT_RECORDS,
22095
+ message: "Resolve comments, moves and bookmarks reaching past the column before removing it."
22096
+ });
22097
+ const columnWidths = table.columnWidths === void 0 ? void 0 : [...table.columnWidths];
22098
+ if (columnWidths !== void 0) {
22099
+ if (op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN) columnWidths.splice(op.column, 0, ...Array.from({ length: count }, () => op.width));
22100
+ else columnWidths.splice(op.column, 1);
22101
+ }
22102
+ const edited = {
22103
+ ...table,
22104
+ rows
22105
+ };
22106
+ if (columnWidths !== void 0) edited.columnWidths = columnWidths;
22107
+ const newIds = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.newBlockIds : [];
22108
+ const unnamed = (value) => {
22109
+ let text = JSON.stringify(value);
22110
+ for (const id of newIds) text = text.replaceAll(`"${id}"`, `"new"`);
22111
+ return JSON.parse(text);
22112
+ };
22113
+ for (const reject of [false, true]) {
22114
+ const decided = withTableRecordsResolved(table, reject);
22115
+ const editedDecided = withTableRecordsResolved(edited, reject);
22116
+ if (decided.isErr() || editedDecided.isErr()) return refused();
22117
+ const decidedGrid = statedGrid(decided.value, op);
22118
+ if (decidedGrid.isErr()) return refused();
22119
+ const want = columnEdit({
22120
+ document,
22121
+ op: op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? {
22122
+ ...op,
22123
+ newBlockIds: newIds.slice(0, plans.filter((plan) => plan.type === "cells" && plan.added !== void 0 && plan.added.kept !== (reject ? "accept" : "reject")).length * count)
22124
+ } : op,
22125
+ table: decided.value,
22126
+ grid: decidedGrid.value
22127
+ });
22128
+ if (want.isErr() || !structurallyEqual(unnamed(editedDecided.value), unnamed(want.value))) return refused();
22129
+ }
22130
+ return Result.ok(edited);
22131
+ };
20615
22132
  const columnEdit = ({ document, op, table, grid }) => {
20616
22133
  const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
20617
22134
  const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
@@ -20635,6 +22152,17 @@ const columnEdit = ({ document, op, table, grid }) => {
20635
22152
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
20636
22153
  message: "Resolve table reviews before changing its columns."
20637
22154
  });
22155
+ if (op.revision === void 0 && recordsPlaceColumnsApart(table, grid)) return columnEditAcrossRecords({
22156
+ document,
22157
+ op,
22158
+ table,
22159
+ grid,
22160
+ conflict: (message) => refuse$3({
22161
+ op,
22162
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
22163
+ message
22164
+ })
22165
+ });
20638
22166
  const removedCells = insert ? [] : grid.rows.flatMap((entries) => entries.filter((entry) => entry.start <= op.column && op.column < entry.end && entry.end - entry.start === 1).map((entry) => entry.cell));
20639
22167
  if (removedCells.some(reachesPastRemovedCell) || strandsABookmark(removedCells)) return refuse$3({
20640
22168
  op,
@@ -20663,8 +22191,7 @@ const columnEdit = ({ document, op, table, grid }) => {
20663
22191
  const earlierGrid = op.revision === void 0 ? columnReviews({
20664
22192
  op,
20665
22193
  table,
20666
- grid,
20667
- leavesRow
22194
+ grid
20668
22195
  }) : Result.ok(void 0);
20669
22196
  if (earlierGrid.isErr()) return Result.err(earlierGrid.error);
20670
22197
  const stampedRows = /* @__PURE__ */ new Map();
@@ -20881,6 +22408,35 @@ const closingRows = ({ before, after }) => new Set(after.flatMap((row, index) =>
20881
22408
  after: row.cells
20882
22409
  }) ? [index] : []));
20883
22410
  /**
22411
+ * The table without the rows a merge closes, each taken out as removing a
22412
+ * row does: a merge none of the rows left continues is no merge.
22413
+ */
22414
+ const withoutRows = (table, closing) => {
22415
+ let rows = table.rows;
22416
+ for (const index of [...closing].toSorted((left, right) => right - left)) rows = rowsWithoutRow({
22417
+ ...table,
22418
+ rows
22419
+ }, index);
22420
+ return {
22421
+ ...table,
22422
+ rows
22423
+ };
22424
+ };
22425
+ /**
22426
+ * A direct merge's rows that close go into its first row, which then holds
22427
+ * their words. Under a pending insertion or deletion of its own, the first
22428
+ * row would take them with it when that change removes it.
22429
+ */
22430
+ const closesOtherRows = ({ op, table, closing }) => {
22431
+ const first = table.rows[op.top]?.structuralChange;
22432
+ if (first === void 0 || [...closing].every((index) => structurallyEqual(table.rows[index]?.structuralChange, first))) return Result.ok(void 0);
22433
+ return refuse$3({
22434
+ op,
22435
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
22436
+ message: "Resolve the pending insertion or deletion of the merge's first row before merging rows it would take whole."
22437
+ });
22438
+ };
22439
+ /**
20884
22440
  * A suggested merge's rows, with the deletion of each row it closes
20885
22441
  * recorded beside its cell's merge record: accepting removes the row, as the
20886
22442
  * direct merge does, and rejecting keeps it as it was.
@@ -20916,25 +22472,240 @@ const trackedClosingRows = ({ document, op, table, merged, closing, used }) => {
20916
22472
  return Result.ok(rows);
20917
22473
  };
20918
22474
  /**
20919
- * Whether a direct merge keeps the table's pending records. The merged rows
20920
- * stand or go together: one pending insertion or deletion takes them all, or
20921
- * none does. A merged cell is under no pending insertion, deletion or merge of
20922
- * its own, and a cell the merge takes in records no other span, merge or
20923
- * width than it has.
22475
+ * Whether a direct merge keeps the table's pending records. A merged cell is
22476
+ * under no pending insertion, deletion or merge of its own, and a cell the
22477
+ * merge takes in records no other span, merge or width than it has. The
22478
+ * merged rows' own insertions and deletions stay on their words
22479
+ * (`reviewedMergeContent`).
20924
22480
  */
20925
- const mergeReviews = ({ op, table, selected, verticalOnly }) => {
22481
+ const mergeReviews = ({ op, selected, verticalOnly }) => {
20926
22482
  const conflict = (message) => refuse$3({
20927
22483
  op,
20928
22484
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
20929
22485
  message
20930
22486
  });
20931
- const rows = table.rows.slice(op.top, op.bottom);
20932
- if (rows.some((row) => !structurallyEqual(row.structuralChange, rows.at(0)?.structuralChange))) return conflict("Resolve the pending row insertions and deletions the merge crosses before merging.");
20933
22487
  const cells = selected.flat();
20934
22488
  if (cells.some(({ cell }) => cell.structuralChange !== void 0)) return conflict("Resolve the pending insertions, deletions and merges of the merged cells before merging.");
20935
22489
  if ((verticalOnly ? [] : cells.slice(1)).some(({ cell }) => !statesOwnGrid(cell.propertyChanges, cell.formatting, CELL_GRID_FIELDS))) return conflict("Resolve the pending span and width changes of the merged cells before merging.");
20936
22490
  return Result.ok(void 0);
20937
22491
  };
22492
+ /** The row change each kind of record goes with. */
22493
+ const ROW_CHANGE_TYPES = {
22494
+ [WRAP_KINDS.INSERTION]: "tableRowInsertion",
22495
+ [WRAP_KINDS.DELETION]: "tableRowDeletion"
22496
+ };
22497
+ const MARK_KINDS = {
22498
+ [WRAP_KINDS.INSERTION]: "ins",
22499
+ [WRAP_KINDS.DELETION]: "del"
22500
+ };
22501
+ /**
22502
+ * The paragraph's content recorded as the kind of change: words a pending
22503
+ * insertion already holds stay as they are, as a deletion keeps the words a
22504
+ * pending deletion holds.
22505
+ */
22506
+ const recordedContent = (paragraph, removal) => {
22507
+ const wrap = (items) => {
22508
+ if (items.length === 0) return Result.ok([]);
22509
+ const wrapped = wrapTracked({
22510
+ items,
22511
+ from: {
22512
+ offset: 0,
22513
+ zeroWidthBefore: 0
22514
+ },
22515
+ to: {
22516
+ offset: paragraphLength({
22517
+ type: "paragraph",
22518
+ content: [...items]
22519
+ }),
22520
+ zeroWidthBefore: Number.MAX_SAFE_INTEGER
22521
+ },
22522
+ kind: removal.kind,
22523
+ stamp: removal.stamp,
22524
+ ...removal.kind === WRAP_KINDS.DELETION ? { commentAnchors: "stand" } : {}
22525
+ });
22526
+ switch (wrapped.kind) {
22527
+ case "refused": return Result.err(wrapped.reason);
22528
+ case "unchanged": return Result.ok([...items]);
22529
+ case "wrapped": return Result.ok(wrapped.content);
22530
+ default: return wrapped;
22531
+ }
22532
+ };
22533
+ if (removal.kind === WRAP_KINDS.DELETION) return wrap(paragraph.content);
22534
+ const content = [];
22535
+ let stretch = [];
22536
+ for (const item of [...paragraph.content, void 0]) {
22537
+ if (item !== void 0 && item.type !== "insertion") {
22538
+ stretch.push(item);
22539
+ continue;
22540
+ }
22541
+ const wrapped = wrap(stretch);
22542
+ if (wrapped.isErr()) return wrapped;
22543
+ content.push(...wrapped.value);
22544
+ stretch = [];
22545
+ if (item !== void 0) content.push(item);
22546
+ }
22547
+ return Result.ok(content);
22548
+ };
22549
+ /**
22550
+ * A direct merge's cell content, across rows with different pending
22551
+ * insertions and deletions. The words of a row pending insertion keep that
22552
+ * insertion as records of their own, and those of a row pending deletion
22553
+ * that deletion, under its author, date and suggestion: rejecting the rows'
22554
+ * changes removes the inserted rows' words and keeps the deleted rows' in
22555
+ * place, and accepting them does the reverse. A paragraph mark between such
22556
+ * words and the next ones records the change too, so the words go with their
22557
+ * paragraphs. When the merged cell ends with words one decision removes,
22558
+ * the last paragraph that stays takes the cell's final mark as a paragraph
22559
+ * insertion or deletion at a container's end does.
22560
+ */
22561
+ const reviewedMergeContent = ({ document, op, changes, words }) => {
22562
+ if (changes.every((change) => structurallyEqual(change, changes.at(0)))) return Result.ok(words.flatMap(({ blocks }) => blocks));
22563
+ const conflict = (message) => refuse$3({
22564
+ op,
22565
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
22566
+ message
22567
+ });
22568
+ const merged = [];
22569
+ for (const { blocks: held, change } of words) for (const block of held) {
22570
+ if (change === void 0 && block.type === "paragraph") {
22571
+ merged.push({
22572
+ paragraph: block,
22573
+ removal: void 0
22574
+ });
22575
+ continue;
22576
+ }
22577
+ if (block.type !== "paragraph" || change?.type !== "tableRowInsertion" && change?.type !== "tableRowDeletion") return conflict("Resolve the pending row changes the merge crosses before merging cells that hold tables or content controls.");
22578
+ const { id, author, date, initials, suggestionId } = change.info;
22579
+ if (date === void 0) return conflict("Resolve the undated pending row changes the merge crosses before merging.");
22580
+ const stamp = {
22581
+ id,
22582
+ author,
22583
+ date,
22584
+ ...initials === void 0 ? {} : { initials },
22585
+ ...suggestionId === void 0 ? {} : { suggestionId }
22586
+ };
22587
+ merged.push({
22588
+ paragraph: block,
22589
+ removal: change.type === "tableRowInsertion" ? {
22590
+ kind: WRAP_KINDS.INSERTION,
22591
+ stamp
22592
+ } : {
22593
+ kind: WRAP_KINDS.DELETION,
22594
+ stamp
22595
+ }
22596
+ });
22597
+ }
22598
+ const lastStanding = (kind) => merged.findLastIndex(({ removal }) => removal?.kind !== kind);
22599
+ const rowStands = (kind) => changes.some((change) => change?.type !== ROW_CHANGE_TYPES[kind]);
22600
+ if ([WRAP_KINDS.INSERTION, WRAP_KINDS.DELETION].some((kind) => rowStands(kind) && lastStanding(kind) === -1)) return conflict("Resolve the pending row changes the merge crosses before merging cells whose words would all go with them.");
22601
+ const final = merged.length - 1;
22602
+ const after = [];
22603
+ for (const [index, { paragraph, removal }] of merged.entries()) {
22604
+ if (removal === void 0) {
22605
+ after.push(paragraph);
22606
+ continue;
22607
+ }
22608
+ const recorded = recordedContent(paragraph, removal);
22609
+ if (recorded.isErr()) return refuse$3({
22610
+ op,
22611
+ reason: recorded.error,
22612
+ message: "The merged rows' words cannot record their pending change."
22613
+ });
22614
+ const mark = MARK_KINDS[removal.kind];
22615
+ const existing = paragraph.pPrMark;
22616
+ if (existing !== void 0 && (existing.kind !== mark || existing.deletion !== void 0)) return conflict("Resolve the pending paragraph mark changes of the merged rows before merging.");
22617
+ const next = {
22618
+ ...paragraph,
22619
+ content: recorded.value
22620
+ };
22621
+ if (index === final) delete next.pPrMark;
22622
+ else if (existing === void 0) next.pPrMark = {
22623
+ kind: mark,
22624
+ info: stampInfo(removal.stamp)
22625
+ };
22626
+ after.push(next);
22627
+ }
22628
+ const ending = merged.at(final)?.removal;
22629
+ const standing = ending === void 0 ? -1 : lastStanding(ending.kind);
22630
+ if (ending !== void 0 && standing !== -1) {
22631
+ const survivor = after[standing] ?? panic("A merged paragraph is missing.");
22632
+ const last = after[final] ?? panic("A merged paragraph is missing.");
22633
+ if (survivor.pPrMark !== void 0 || survivor.propertyChanges !== void 0 || last.propertyChanges !== void 0) return conflict("Resolve the pending paragraph changes at the end of the merged cell before merging.");
22634
+ const info = stampInfo(ending.stamp);
22635
+ if (ending.kind === WRAP_KINDS.INSERTION) {
22636
+ after[standing] = {
22637
+ ...survivor,
22638
+ pPrMark: {
22639
+ kind: "ins",
22640
+ info,
22641
+ survivor: "first"
22642
+ }
22643
+ };
22644
+ for (let index = standing + 1; index < final; index += 1) {
22645
+ const paragraph = after[index] ?? panic("A merged paragraph is missing.");
22646
+ if (paragraph.pPrMark?.kind === "ins") after[index] = {
22647
+ ...paragraph,
22648
+ pPrMark: {
22649
+ ...paragraph.pPrMark,
22650
+ survivor: "first"
22651
+ }
22652
+ };
22653
+ }
22654
+ if (!structurallyEqual(finalizeParagraphFormatting(survivor.formatting) ?? {}, finalizeParagraphFormatting(last.formatting) ?? {})) after[final] = {
22655
+ ...last,
22656
+ propertyChanges: [{
22657
+ type: "paragraphPropertyChange",
22658
+ info,
22659
+ ...survivor.formatting === void 0 ? {} : { previousFormatting: survivor.formatting }
22660
+ }]
22661
+ };
22662
+ } else {
22663
+ after[standing] = {
22664
+ ...survivor,
22665
+ pPrMark: {
22666
+ kind: "del",
22667
+ info
22668
+ }
22669
+ };
22670
+ const formatting = finalizeParagraphFormatting(survivor.formatting);
22671
+ if (!structurallyEqual(formatting ?? {}, finalizeParagraphFormatting(last.formatting) ?? {})) {
22672
+ const review = reviewFieldsOf(last);
22673
+ delete review.formatting;
22674
+ if (formatting !== void 0) review.formatting = formatting;
22675
+ review.propertyChanges = [foldedParagraphPropertyChange({
22676
+ paragraph: last,
22677
+ formatting,
22678
+ stamp: ending.stamp
22679
+ })];
22680
+ after[final] = withReviewFields(last, review);
22681
+ }
22682
+ }
22683
+ }
22684
+ const before = merged.map(({ paragraph }) => paragraph);
22685
+ const held = packageIdentityKeyIndex(document.package);
22686
+ const own = /* @__PURE__ */ new Map();
22687
+ for (const key of identityKeysOf(before)) own.set(key, (own.get(key) ?? 0) + 1);
22688
+ const fresh = freshenIdentities({
22689
+ before,
22690
+ after,
22691
+ newIds: op.newIds ?? {},
22692
+ usedElsewhere: () => ({ has: (key) => held.count(key) > (own.get(key) ?? 0) })
22693
+ });
22694
+ switch (fresh.kind) {
22695
+ case "needsIds": return refuse$3({
22696
+ op,
22697
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
22698
+ message: `The merged rows' words need ${fresh.missing} more revision ids.`
22699
+ });
22700
+ case "invalidId": return refuse$3({
22701
+ op,
22702
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
22703
+ message: `${fresh.id} cannot be a new revision id.`
22704
+ });
22705
+ case "fresh": return Result.ok(fresh.paragraphs);
22706
+ default: return fresh;
22707
+ }
22708
+ };
20938
22709
  const merge = ({ document, op, table, grid }) => {
20939
22710
  if (hasStructuralMarkup(table)) return refuse$3({
20940
22711
  op,
@@ -20960,7 +22731,6 @@ const merge = ({ document, op, table, grid }) => {
20960
22731
  if (op.revision === void 0) {
20961
22732
  const kept = mergeReviews({
20962
22733
  op,
20963
- table,
20964
22734
  selected,
20965
22735
  verticalOnly
20966
22736
  });
@@ -21025,10 +22795,14 @@ const merge = ({ document, op, table, grid }) => {
21025
22795
  ...table,
21026
22796
  rows
21027
22797
  });
21028
- if (op.revision === void 0) return Result.ok({
22798
+ if (op.revision === void 0) return closesOtherRows({
22799
+ op,
22800
+ table,
22801
+ closing
22802
+ }).map(() => withoutRows({
21029
22803
  ...table,
21030
- rows: rows.filter((_row, index) => !closing.has(index))
21031
- });
22804
+ rows
22805
+ }, closing));
21032
22806
  return trackedClosingRows({
21033
22807
  document,
21034
22808
  op,
@@ -21052,8 +22826,20 @@ const merge = ({ document, op, table, grid }) => {
21052
22826
  if (fresh.isErr()) return Result.err(fresh.error);
21053
22827
  const first = selected.at(0)?.at(0);
21054
22828
  if (first === void 0) return mismatch(op, "No cells are selected.");
21055
- const holding = selected.flatMap((row) => row.map(({ cell }) => cell)).filter((cell) => !isEmptyCell(cell));
21056
- const content = (holding.length === 0 ? [first.cell] : holding).flatMap((cell) => cell.content);
22829
+ const changes = table.rows.slice(op.top, op.bottom).map(({ structuralChange }) => structuralChange);
22830
+ const holds = selected.some((row) => row.some(({ cell }) => !isEmptyCell(cell)));
22831
+ const words = selected.flatMap((row, offset) => row.filter(({ cell }) => holds ? !isEmptyCell(cell) : cell === first.cell).map(({ cell }) => ({
22832
+ blocks: cell.content,
22833
+ change: changes[offset]
22834
+ })));
22835
+ const reviewed = reviewedMergeContent({
22836
+ document,
22837
+ op,
22838
+ changes,
22839
+ words
22840
+ });
22841
+ if (reviewed.isErr()) return Result.err(reviewed.error);
22842
+ const content = reviewed.value;
21057
22843
  const mergedCellWidth = mergedWidth(selected.at(0)?.map(({ cell }) => cell) ?? []);
21058
22844
  if (mergedCellWidth.isErr()) return mismatch(op, "Selected cell widths must be nonnegative safe integer units.");
21059
22845
  const width = mergedCellWidth.value;
@@ -21096,10 +22882,14 @@ const merge = ({ document, op, table, grid }) => {
21096
22882
  before: table.rows,
21097
22883
  after: rows
21098
22884
  });
21099
- return Result.ok({
22885
+ return closesOtherRows({
22886
+ op,
22887
+ table,
22888
+ closing
22889
+ }).map(() => withoutRows({
21100
22890
  ...table,
21101
- rows: rows.filter((_row, index) => !closing.has(index))
21102
- });
22891
+ rows
22892
+ }, closing));
21103
22893
  };
21104
22894
  const split = ({ document, op, table, grid, location }) => {
21105
22895
  const target = grid.rows[location.rowIndex]?.find((entry) => entry.index === location.cellIndex);
@@ -21127,11 +22917,13 @@ const split = ({ document, op, table, grid, location }) => {
21127
22917
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
21128
22918
  message: "Resolve the pending insertions, deletions and merges of the split cell before splitting it."
21129
22919
  });
21130
- if (op.revision === void 0 && span > 1 && group.some(({ cell }) => cell.propertyChanges !== void 0)) return refuse$3({
22920
+ const copiedChanges = op.revision === void 0 ? directRevisionIds({
22921
+ document,
21131
22922
  op,
21132
- reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
21133
- message: "Resolve the pending property changes of the split cell before splitting its columns."
21134
- });
22923
+ count: group.reduce((sum, { cell }) => sum + (cell.propertyChanges?.length ?? 0) * (span - 1), 0)
22924
+ }) : Result.ok([]);
22925
+ if (copiedChanges.isErr()) return Result.err(copiedChanges.error);
22926
+ const copiedIds = copiedChanges.value.values();
21135
22927
  if (group.some(({ cell }) => {
21136
22928
  const width = cell.formatting?.width;
21137
22929
  return width !== void 0 && (width.type === "dxa" || width.type === "pct") && (!Number.isSafeInteger(width.value) || width.value < 0);
@@ -21203,7 +22995,17 @@ const split = ({ document, op, table, grid, location }) => {
21203
22995
  type: "tableCellInsertion",
21204
22996
  info: stampInfo(cellStamp)
21205
22997
  };
21206
- replacement.push(next);
22998
+ const copied = copiedPropertyChanges({
22999
+ source: entry.cell,
23000
+ cell: next,
23001
+ ids: copiedIds
23002
+ });
23003
+ if (copied.isErr()) return refuse$3({
23004
+ op,
23005
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
23006
+ message: "A pending change records another span than the split changes."
23007
+ });
23008
+ replacement.push(copied.value);
21207
23009
  }
21208
23010
  }
21209
23011
  cells.splice(entry.index, 1, ...replacement);
@@ -21234,11 +23036,22 @@ const tableEditParagraphDemand = (location, op) => {
21234
23036
  const grid = statedGrid(table, op);
21235
23037
  if (grid.isErr()) return Result.err(grid.error);
21236
23038
  switch (op.type) {
21237
- case DOCUMENT_OP_TYPES.INSERT_COLUMN: return Result.ok(grid.value.rows.filter((cells, row) => {
21238
- const before = table.rows[row]?.formatting?.gridBefore ?? 0;
21239
- const { end } = rowExtent(table, grid.value, row);
21240
- return op.column >= before && op.column <= end && !cells.some((cell) => cell.start < op.column && op.column < cell.end);
21241
- }).length * (op.count ?? 1));
23039
+ case DOCUMENT_OP_TYPES.INSERT_COLUMN: {
23040
+ const plans = recordsPlaceColumnsApart(table, grid.value) ? columnPlanAcrossRecords({
23041
+ table,
23042
+ grid: grid.value,
23043
+ op: {
23044
+ ...op,
23045
+ newBlockIds: []
23046
+ }
23047
+ }) : void 0;
23048
+ if (plans !== void 0) return Result.ok(plans.filter((plan) => plan.type === "cells" && plan.added !== void 0).length * (op.count ?? 1));
23049
+ return Result.ok(grid.value.rows.filter((cells, row) => {
23050
+ const before = table.rows[row]?.formatting?.gridBefore ?? 0;
23051
+ const { end } = rowExtent(table, grid.value, row);
23052
+ return op.column >= before && op.column <= end && !cells.some((cell) => cell.start < op.column && op.column < cell.end);
23053
+ }).length * (op.count ?? 1));
23054
+ }
21242
23055
  case DOCUMENT_OP_TYPES.MERGE_CELLS: {
21243
23056
  const selection = mergeSelection({
21244
23057
  table,
@@ -21461,7 +23274,8 @@ const applyTableEdit = (document, op) => {
21461
23274
  });
21462
23275
  break;
21463
23276
  case DOCUMENT_OP_TYPES.SET_TABLE_GRID: {
21464
- if (op.columnWidths.length !== grid.value.width || op.columnWidths.some((width) => !Number.isSafeInteger(width) || width <= 0)) return mismatch(op, "Column widths must match the grid and be positive twip counts.");
23277
+ const unmeasured = op.columnWidths.length === 0;
23278
+ if (!unmeasured && op.columnWidths.length !== grid.value.width || op.columnWidths.some((width) => !Number.isSafeInteger(width) || width <= 0)) return mismatch(op, "Column widths must match the grid and be positive twip counts, or be none.");
21465
23279
  if (table.formatting?.gridChange !== void 0) return refuse$3({
21466
23280
  op,
21467
23281
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
@@ -21479,8 +23293,9 @@ const applyTableEdit = (document, op) => {
21479
23293
  });
21480
23294
  const stamps = stampsFor(op, 2);
21481
23295
  if (stamps.isErr()) return Result.err(stamps.error);
21482
- const next = {
21483
- ...table,
23296
+ const { columnWidths: _previous, ...rest } = table;
23297
+ const next = unmeasured ? rest : {
23298
+ ...rest,
21484
23299
  columnWidths: [...op.columnWidths]
21485
23300
  };
21486
23301
  const gridStamp = stamps.value.at(0);
@@ -22686,7 +24501,7 @@ const trackSplit = ({ op, stamp, paragraph, first, made, madeSecond, resolutionJ
22686
24501
  kind: "ins",
22687
24502
  info: stampInfo(stamp),
22688
24503
  resolutionJoin,
22689
- ...madeSecond ? { survivor: "first" } : {}
24504
+ ...madeSecond ? firstSurvivorFields(paragraph.pPrMark) : {}
22690
24505
  };
22691
24506
  if (!sameParagraphProperties(made.formatting, paragraph.formatting)) {
22692
24507
  const conflict = madeSecond ? paragraphPropertyFoldConflict(paragraph, stamp) : void 0;
@@ -23641,7 +25456,7 @@ const applyAddressedOp = ({ document, op, purpose, boxes }) => {
23641
25456
  purpose
23642
25457
  });
23643
25458
  if (applied.isErr()) return Result.err(applied.error);
23644
- const edit = applied.value;
25459
+ let edit = applied.value;
23645
25460
  const beforeSections = document.package.document.sections;
23646
25461
  const afterSections = edit.document.package.document.sections;
23647
25462
  const structural = op.type === DOCUMENT_OP_TYPES.SPLIT_BLOCK || op.type === DOCUMENT_OP_TYPES.JOIN_BLOCKS || op.type === DOCUMENT_OP_TYPES.REPLACE_BLOCKS;
@@ -23695,6 +25510,21 @@ const applyAddressedOp = ({ document, op, purpose, boxes }) => {
23695
25510
  }]
23696
25511
  };
23697
25512
  }
25513
+ const releases = op.type === DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW || op.type === DOCUMENT_OP_TYPES.RESOLVE_REVISION || edit.touched.removed.length === 0 ? [] : takenOverMarkReleases({
25514
+ before: document,
25515
+ after: edit.document,
25516
+ touched: edit.touched,
25517
+ story: addressedStory(op)
25518
+ });
25519
+ if (releases.length > 0) {
25520
+ const released = applyDocumentOpsForPurpose({
25521
+ document: edit.document,
25522
+ ops: releases,
25523
+ purpose
25524
+ });
25525
+ if (released.isErr()) return released;
25526
+ edit = combineEditEffects(released.value.document, [edit, released.value]);
25527
+ }
23698
25528
  return Result.ok({
23699
25529
  ...edit,
23700
25530
  inverse: edit.inverse.map(captureDocumentOp),
@@ -24552,6 +26382,13 @@ const filterNewIds = (op, keep) => {
24552
26382
  if (control !== void 0) newIds.control = control.filter((id) => keep(IDENTITY_SPACES.CONTROL, id));
24553
26383
  return withNewIds(op, newIds);
24554
26384
  };
26385
+ /** The table edits that may keep pending records on new rows and cells. */
26386
+ const DIRECT_TABLE_EDITS = /* @__PURE__ */ new Set([
26387
+ DOCUMENT_OP_TYPES.INSERT_COLUMN,
26388
+ DOCUMENT_OP_TYPES.DELETE_COLUMN,
26389
+ DOCUMENT_OP_TYPES.MERGE_CELLS,
26390
+ DOCUMENT_OP_TYPES.SPLIT_CELL
26391
+ ]);
24555
26392
  /** Keep only supplied ids that the successful operation put in changed paragraphs. */
24556
26393
  const trimAppliedNewIds = ({ before, op, applied, story }) => {
24557
26394
  if (!("newIds" in op) || op.newIds === void 0) return op;
@@ -24561,9 +26398,9 @@ const trimAppliedNewIds = ({ before, op, applied, story }) => {
24561
26398
  const location = findStoryParagraph(body, key);
24562
26399
  return location === void 0 ? [] : [location.paragraph];
24563
26400
  });
24564
- const identities = new Set(identityKeysIn(paragraphs));
24565
- const revisions = new Set(applied.revisions);
24566
26401
  const known = packageIdentityKeyIndex(before.package);
26402
+ const identities = new Set(DIRECT_TABLE_EDITS.has(op.type) && stampOf(op) === void 0 ? known.introducedIn(applied.document.package) : identityKeysIn(paragraphs));
26403
+ const revisions = new Set(applied.revisions);
24567
26404
  return filterNewIds(op, (space, id) => {
24568
26405
  const key = `${space}:${id}`;
24569
26406
  return !known.has(key) && (identities.has(key) || space === IDENTITY_SPACES.REVISION && revisions.has(id));
@@ -24714,8 +26551,10 @@ const leafPlan = ({ node, ancestors }, owner) => {
24714
26551
  const laterGap = (left, right) => compareGaps(left, right) >= 0 ? left : right;
24715
26552
  const earlierGap = (left, right) => compareGaps(left, right) <= 0 ? left : right;
24716
26553
  const replacementDeletionSegments = ({ spans, from, to, mode }) => {
24717
- const keepsLoneEmptyContainers = mode.type === "editing" && mode.keepsLoneEmptyContainers === true;
26554
+ const keepsLoneEmptyContainers = mode.type === "suggesting" || mode.keepsLoneEmptyContainers === true;
24718
26555
  const out = [];
26556
+ const recordingRegions = /* @__PURE__ */ new Set();
26557
+ let region = 0;
24719
26558
  let open;
24720
26559
  for (const span of spans) {
24721
26560
  const start = laterGap(span.before, from);
@@ -24723,6 +26562,7 @@ const replacementDeletionSegments = ({ spans, from, to, mode }) => {
24723
26562
  if (compareGaps(start, end) >= 0) continue;
24724
26563
  if (isParagraphContent(span.node) && isRangeBoundary(span.node)) {
24725
26564
  open = void 0;
26565
+ region += 1;
24726
26566
  continue;
24727
26567
  }
24728
26568
  let plan = isCommentAnchor(span.node) ? "anchor" : "direct";
@@ -24730,24 +26570,35 @@ const replacementDeletionSegments = ({ spans, from, to, mode }) => {
24730
26570
  else if (span.ancestors.some(isRemovedRevisionNode)) plan = "untouched";
24731
26571
  if (plan === "anchor") {
24732
26572
  open = void 0;
26573
+ region += 1;
24733
26574
  continue;
24734
26575
  }
24735
26576
  const segmentPlan = plan === "untouched" ? "tracked" : plan;
24736
- const records = plan !== "untouched" && !((mode.type === "suggesting" || keepsLoneEmptyContainers) && isEmptyContainer(span.node));
26577
+ const empty = plan !== "untouched" && keepsLoneEmptyContainers && isEmptyContainer(span.node);
26578
+ const records = plan !== "untouched" && !empty;
26579
+ if (records) recordingRegions.add(region);
24737
26580
  if (open !== void 0 && open.plan === segmentPlan && compareGaps(open.to, start) === 0) {
24738
26581
  open.to = end;
24739
26582
  open.records ||= records;
26583
+ open.empties ||= empty;
24740
26584
  continue;
24741
26585
  }
24742
26586
  open = {
24743
26587
  plan: segmentPlan,
24744
26588
  from: start,
24745
26589
  to: end,
24746
- records
26590
+ records,
26591
+ region,
26592
+ empties: empty
24747
26593
  };
24748
26594
  out.push(open);
24749
26595
  }
24750
- return out.filter(({ records }) => records);
26596
+ return out.flatMap((stretch) => stretch.records || mode.type === "editing" && stretch.empties && recordingRegions.has(stretch.region) ? [{
26597
+ plan: stretch.plan,
26598
+ from: stretch.from,
26599
+ to: stretch.to,
26600
+ records: true
26601
+ }] : []);
24751
26602
  };
24752
26603
  /**
24753
26604
  * The leaves of a range that its direct deletion leaves standing, in
@@ -25753,6 +27604,212 @@ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileI
25753
27604
  selection: intent.to
25754
27605
  });
25755
27606
  };
27607
+ // src/ops/pasteAnchors.ts
27608
+ const PLACEHOLDER_STEM = "_folioPasteAnchor";
27609
+ /** Where placeholder ids start; an id a bookmark already holds is skipped. */
27610
+ const PLACEHOLDER_FIRST_ID = 2130706432;
27611
+ /**
27612
+ * A placeholder name prefix no bookmark the destination or the paste holds
27613
+ * begins with, so that only this paste's placeholders carry it.
27614
+ */
27615
+ const freePrefix = (names) => {
27616
+ let serial = 0;
27617
+ for (;;) {
27618
+ const prefix = `${PLACEHOLDER_STEM}${String(serial)}_`;
27619
+ if (![...names].some((name) => name.startsWith(prefix))) return prefix;
27620
+ serial += 1;
27621
+ }
27622
+ };
27623
+ const PLACEHOLDER_INDEX = /^(?:0|[1-9]\d*)$/u;
27624
+ const placeholderIndex = (prefix, name) => {
27625
+ if (!name.startsWith(prefix)) return void 0;
27626
+ const suffix = name.slice(prefix.length);
27627
+ return PLACEHOLDER_INDEX.test(suffix) ? Number(suffix) : void 0;
27628
+ };
27629
+ /** `value` with every placeholder bookmark in it removed. */
27630
+ const withoutPasteAnchors = (value, ids) => {
27631
+ const isPlaceholder = (item) => {
27632
+ if (typeof item !== "object" || item === null) return false;
27633
+ const type = Reflect.get(item, "type");
27634
+ const id = Reflect.get(item, "id");
27635
+ return (type === "bookmarkStart" || type === "bookmarkEnd") && typeof id === "number" && ids.has(id);
27636
+ };
27637
+ const strip = (node) => {
27638
+ if (Array.isArray(node)) {
27639
+ for (let index = node.length - 1; index >= 0; index -= 1) if (isPlaceholder(node[index])) node.splice(index, 1);
27640
+ for (const item of node) strip(item);
27641
+ return;
27642
+ }
27643
+ if (typeof node !== "object" || node === null) return;
27644
+ for (const field of Object.values(node)) strip(field);
27645
+ };
27646
+ const copy = cloneModel(value);
27647
+ strip(copy);
27648
+ return copy;
27649
+ };
27650
+ /**
27651
+ * The blocks with each note reference and comment marker a placeholder, named
27652
+ * and numbered apart from every bookmark in `destination` and in the blocks.
27653
+ */
27654
+ const withPasteAnchors = (blocks, destination = {
27655
+ names: /* @__PURE__ */ new Set(),
27656
+ ids: /* @__PURE__ */ new Set()
27657
+ }) => {
27658
+ const pasted = bookmarksIn(blocks);
27659
+ const prefix = freePrefix(/* @__PURE__ */ new Set([...destination.names, ...pasted.names]));
27660
+ const taken = /* @__PURE__ */ new Set([...destination.ids, ...pasted.ids]);
27661
+ const ids = /* @__PURE__ */ new Set();
27662
+ let nextId = PLACEHOLDER_FIRST_ID;
27663
+ const anchors = [];
27664
+ const placeholder = (anchor) => {
27665
+ const index = anchors.length;
27666
+ anchors.push(anchor);
27667
+ while (taken.has(nextId)) nextId += 1;
27668
+ const id = nextId;
27669
+ nextId += 1;
27670
+ ids.add(id);
27671
+ return [{
27672
+ type: "bookmarkStart",
27673
+ id,
27674
+ name: `${prefix}${String(index)}`
27675
+ }, {
27676
+ type: "bookmarkEnd",
27677
+ id
27678
+ }];
27679
+ };
27680
+ const inline = (content) => {
27681
+ const out = [];
27682
+ for (const item of content) {
27683
+ if (item.type === "commentRangeStart" || item.type === "commentRangeEnd" || item.type === "commentReference") {
27684
+ out.push(...placeholder({
27685
+ kind: item.type,
27686
+ id: item.id
27687
+ }));
27688
+ continue;
27689
+ }
27690
+ if (item.type === "run") {
27691
+ if (!item.content.some((piece) => piece.type === "footnoteRef" || piece.type === "endnoteRef")) {
27692
+ out.push(item);
27693
+ continue;
27694
+ }
27695
+ let pending = [];
27696
+ const flush = () => {
27697
+ if (pending.length > 0) out.push({
27698
+ ...item,
27699
+ content: pending
27700
+ });
27701
+ pending = [];
27702
+ };
27703
+ for (const piece of item.content) {
27704
+ if (piece.type !== "footnoteRef" && piece.type !== "endnoteRef") {
27705
+ pending.push(piece);
27706
+ continue;
27707
+ }
27708
+ flush();
27709
+ out.push(...placeholder({
27710
+ kind: "note",
27711
+ note: piece.type === "footnoteRef" ? "footnote" : "endnote",
27712
+ id: piece.id
27713
+ }));
27714
+ }
27715
+ flush();
27716
+ continue;
27717
+ }
27718
+ out.push(isInlineContainer(item) ? withChildren(item, inline(childrenOf(item))) : item);
27719
+ }
27720
+ return out;
27721
+ };
27722
+ const block = (each) => each.type === "paragraph" ? {
27723
+ ...each,
27724
+ content: inline(each.content)
27725
+ } : {
27726
+ ...each,
27727
+ rows: each.rows.map((row) => ({
27728
+ ...row,
27729
+ cells: row.cells.map((cell) => ({
27730
+ ...cell,
27731
+ content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? block(inner) : inner)
27732
+ }))
27733
+ }))
27734
+ };
27735
+ const anchoredBlocks = blocks.map(block);
27736
+ return {
27737
+ prefix,
27738
+ ids,
27739
+ blocks: anchoredBlocks,
27740
+ plain: withoutPasteAnchors(anchoredBlocks, ids),
27741
+ anchors
27742
+ };
27743
+ };
27744
+ /** The names and ids of every bookmark `value` holds, at any depth. */
27745
+ const bookmarksIn = (value) => {
27746
+ const names = /* @__PURE__ */ new Set();
27747
+ const ids = /* @__PURE__ */ new Set();
27748
+ const visit = (node) => {
27749
+ if (Array.isArray(node)) {
27750
+ for (const item of node) visit(item);
27751
+ return;
27752
+ }
27753
+ if (node instanceof Map) {
27754
+ for (const item of node.values()) visit(item);
27755
+ return;
27756
+ }
27757
+ if (typeof node !== "object" || node === null) return;
27758
+ const type = Reflect.get(node, "type");
27759
+ const name = Reflect.get(node, "name");
27760
+ const id = Reflect.get(node, "id");
27761
+ if (type === "bookmarkStart" && typeof name === "string") names.add(name);
27762
+ if ((type === "bookmarkStart" || type === "bookmarkEnd") && typeof id === "number") ids.add(id);
27763
+ for (const field of Object.values(node)) visit(field);
27764
+ };
27765
+ visit(value);
27766
+ return {
27767
+ names,
27768
+ ids
27769
+ };
27770
+ };
27771
+ /** Whether `paragraph` holds this paste's placeholders and nothing else. */
27772
+ const holdsOnlyPasteAnchors = (paragraph, ids) => paragraph.content.length > 0 && paragraph.content.every((item) => (item.type === "bookmarkStart" || item.type === "bookmarkEnd") && ids.has(item.id));
27773
+ /**
27774
+ * Each of this paste's placeholders' place among `paragraphs`, by anchor
27775
+ * index; undefined when one is missing or found twice, since then no place
27776
+ * is the placeholder's own.
27777
+ */
27778
+ const placedPasteAnchors = ({ paragraphs, prefix, count }) => {
27779
+ const placed = /* @__PURE__ */ new Map();
27780
+ const seen = [];
27781
+ const visit = (items, at) => {
27782
+ let offset = at.start;
27783
+ for (const item of items) {
27784
+ if (item.type === "bookmarkStart") {
27785
+ const index = placeholderIndex(prefix, item.name);
27786
+ if (index !== void 0 && index < count) {
27787
+ seen.push(index);
27788
+ placed.set(index, {
27789
+ blockId: at.blockId,
27790
+ offset,
27791
+ order: at.order
27792
+ });
27793
+ }
27794
+ }
27795
+ if (isInlineContainer(item)) visit(childrenOf(item), {
27796
+ ...at,
27797
+ start: offset
27798
+ });
27799
+ offset += contentWidth([item]);
27800
+ }
27801
+ };
27802
+ for (const [order, paragraph] of paragraphs.entries()) {
27803
+ const blockId = paragraph.paraId;
27804
+ if (blockId === void 0) continue;
27805
+ visit(paragraph.content, {
27806
+ blockId,
27807
+ order,
27808
+ start: 0
27809
+ });
27810
+ }
27811
+ return seen.length !== count || placed.size !== count ? void 0 : placed;
27812
+ };
25756
27813
  // src/ops/rangeReplacement.ts
25757
27814
  /** Tracked replacement fragments share deletion's validation and physical-id pool. */
25758
27815
  const rangeParagraph = (body, blockId) => blockId === "" ? storyParagraphs(body).find(({ paragraph }) => (paragraph.paraId ?? "") === "") : findStoryParagraph(body, blockId);
@@ -26281,6 +28338,7 @@ const intentEndpoints = (intent) => {
26281
28338
  case "removeHyperlink":
26282
28339
  case "insertHyperlink":
26283
28340
  case "replaceFragment":
28341
+ case "pasteBlocks":
26284
28342
  case "moveFragment":
26285
28343
  case "replaceText":
26286
28344
  case "insertAtom":
@@ -26412,6 +28470,30 @@ const createEditorIntentIdAllocator = ({ reservedBlockIds } = {}) => {
26412
28470
  for (const span of leafSpans(paragraph.content)) demand += 4 * (1 + span.ancestors.length);
26413
28471
  }
26414
28472
  if (incoming.length > 0) demand += 8;
28473
+ if (intent.type === "pasteBlocks") {
28474
+ demand += 11;
28475
+ for (const block of intent.blocks) {
28476
+ const paragraphs = block.type === "table" ? storyParagraphs({ content: [block] }).map(({ paragraph }) => paragraph) : [block];
28477
+ if (block.type === "table") demand += 2 + block.rows.length;
28478
+ for (const paragraph of paragraphs) {
28479
+ demand += PARAGRAPH_REVISION_DEMAND;
28480
+ for (const span of leafSpans(paragraph.content)) demand += leafRevisionDemand(span.ancestors.length);
28481
+ }
28482
+ }
28483
+ for (const anchor of withPasteAnchors(intent.blocks).anchors) {
28484
+ if (anchor.kind !== "note") {
28485
+ demand += 4;
28486
+ continue;
28487
+ }
28488
+ const note = intent.annotations?.notes.find(({ type, id }) => type === anchor.note && id === anchor.id);
28489
+ demand += 4;
28490
+ for (const block of note?.content ?? []) {
28491
+ if (block.type !== "paragraph") continue;
28492
+ demand += PARAGRAPH_REVISION_DEMAND;
28493
+ for (const span of leafSpans(block.content)) demand += leafRevisionDemand(span.ancestors.length);
28494
+ }
28495
+ }
28496
+ }
26415
28497
  if (intent.type === "setHyperlink" || intent.type === "removeHyperlink" || intent.type === "insertHyperlink") demand = 2 * demand + 8;
26416
28498
  if (intent.type === "generateTOC") demand += 8 + (intent.headings.length + 1) * (PARAGRAPH_REVISION_DEMAND + 4 * leafRevisionDemand(3));
26417
28499
  if (intent.type === "moveFragment") {
@@ -26495,8 +28577,8 @@ const createEditorIntentIdAllocator = ({ reservedBlockIds } = {}) => {
26495
28577
  break;
26496
28578
  }
26497
28579
  case DOCUMENT_OP_TYPES.MERGE_CELLS:
26498
- demand = (op.bottom - op.top + 1) * 2;
26499
- for (const row of located.value.table.rows.slice(op.top + 1, op.bottom)) {
28580
+ demand = (op.bottom - op.top + 1) * 2 + 2;
28581
+ for (const row of located.value.table.rows.slice(op.top, op.bottom)) {
26500
28582
  demand += 1;
26501
28583
  for (const { paragraph } of storyParagraphs({ content: [{
26502
28584
  type: "table",
@@ -26679,6 +28761,543 @@ const adjacentJoinRefusal = (document, join) => {
26679
28761
  });
26680
28762
  };
26681
28763
  const paragraphAt = (document, at) => findStoryParagraph(storyBody$1(document, at.story), at.blockId)?.paragraph;
28764
+ /**
28765
+ * Whether `paragraph` holds content in `[from, to)` once its changes are
28766
+ * accepted, by the one paragraph-content rule: range markers, comment
28767
+ * references and what accepting takes away hold none. A paste keeps a
28768
+ * paragraph for the text beside it only when this holds, in either mode, so
28769
+ * accepting a suggested paste leaves the paragraphs the direct paste does.
28770
+ */
28771
+ const holdsContentWithin = ({ paragraph, from, to }) => {
28772
+ const clip = (items, start) => {
28773
+ const content = [];
28774
+ let offset = start;
28775
+ for (const item of items) {
28776
+ const end = offset + contentWidth([item]);
28777
+ if (end > from && offset < to) content.push(isInlineContainer(item) ? withChildren(item, clip(childrenOf(item), offset)) : item);
28778
+ offset = end;
28779
+ }
28780
+ return content;
28781
+ };
28782
+ return paragraphHoldsContentOnceAccepted({
28783
+ ...paragraph,
28784
+ content: clip(paragraph.content, 0)
28785
+ });
28786
+ };
28787
+ /** Bookmark ids the content's starts and ends carry, containers included. */
28788
+ const bookmarkIdsIn = (items) => items.flatMap((item) => {
28789
+ if (item.type === "bookmarkStart" || item.type === "bookmarkEnd") return [item.id];
28790
+ return isInlineContainer(item) ? bookmarkIdsIn(childrenOf(item)) : [];
28791
+ });
28792
+ /** Whether a pasted table, or one nested in it, holds bookmarks or records of its own. */
28793
+ const holdsTableLevelIdentities = (block) => {
28794
+ if (block.type !== "table") return false;
28795
+ if ((block.bookmarks?.length ?? 0) > 0 || (block.propertyChanges?.length ?? 0) > 0 || (block.carrierStack?.length ?? 0) > 0) return true;
28796
+ 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))));
28797
+ };
28798
+ /** A pasted block's paragraphs in document order, a table's cells' among them. */
28799
+ 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) : [])));
28800
+ /**
28801
+ * Clipboard blocks placed: once with their placeholders, to find where each
28802
+ * lands, and once without, for the operations and the document they leave.
28803
+ * Placeholders are zero width and hold no content, so both place the blocks
28804
+ * alike; a found place the plain document does not hold refuses. An open
28805
+ * fragment holding only placeholders places nothing: the range is cleared and
28806
+ * every placeholder lands at the caret. A closed paragraph is placed as one.
28807
+ */
28808
+ const placeAnchoredBlocks = (document, { intent, plain, prefix, ids, count, mode, firstBlockId }) => {
28809
+ const story = intent.from.story;
28810
+ const paragraphsOf = (from) => storyParagraphs(storyBody$1(from, story)).map(({ paragraph }) => paragraph);
28811
+ const only = intent.blocks.length === 1 ? intent.blocks[0] : void 0;
28812
+ if (only?.type === "paragraph" && intent.openStart === 1 && intent.openEnd === 1 && holdsOnlyPasteAnchors(only, ids)) {
28813
+ const cleared = idKey(intent.from.blockId) === idKey(intent.to.blockId) && intent.from.offset === intent.to.offset && (intent.from.zeroWidthBefore ?? 0) === (intent.to.zeroWidthBefore ?? 0) ? Result.ok({
28814
+ ops: [],
28815
+ selection: intent.from
28816
+ }) : compileEditorIntent(document, {
28817
+ intent: {
28818
+ type: "replaceText",
28819
+ from: intent.from,
28820
+ to: intent.to,
28821
+ text: ""
28822
+ },
28823
+ mode,
28824
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
28825
+ });
28826
+ if (cleared.isErr()) return Result.err(cleared.error);
28827
+ const applied = applyDocumentOps(document, cleared.value.ops);
28828
+ if (applied.isErr()) return Result.err(applied.error);
28829
+ const caret = cleared.value.selection;
28830
+ const order = paragraphsOf(applied.value.document).findIndex(({ paraId }) => paraId === caret.blockId);
28831
+ const at = {
28832
+ blockId: caret.blockId,
28833
+ offset: caret.offset,
28834
+ order
28835
+ };
28836
+ return Result.ok({
28837
+ ops: [...cleared.value.ops],
28838
+ document: applied.value.document,
28839
+ caret,
28840
+ places: () => at
28841
+ });
28842
+ }
28843
+ const placed = compileBlockPlacement(document, {
28844
+ intent,
28845
+ mode,
28846
+ firstBlockId
28847
+ });
28848
+ if (placed.isErr()) return Result.err(placed.error);
28849
+ const marked = placed.value.applied === void 0 ? applyDocumentOps(document, placed.value.ops) : Result.ok(placed.value.applied);
28850
+ if (marked.isErr()) return Result.err(marked.error);
28851
+ const lost = () => Result.err(new DocumentOpRefusal({
28852
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
28853
+ message: "A pasted note or comment lost its place in the paste.",
28854
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
28855
+ }));
28856
+ const found = placedPasteAnchors({
28857
+ paragraphs: paragraphsOf(marked.value.document),
28858
+ prefix,
28859
+ count
28860
+ });
28861
+ if (found === void 0) return lost();
28862
+ const unmarkedPlacement = compileBlockPlacement(document, {
28863
+ intent: {
28864
+ ...intent,
28865
+ blocks: plain
28866
+ },
28867
+ mode,
28868
+ firstBlockId
28869
+ });
28870
+ if (unmarkedPlacement.isErr()) return Result.err(unmarkedPlacement.error);
28871
+ const unmarked = unmarkedPlacement.value.applied === void 0 ? applyDocumentOps(document, unmarkedPlacement.value.ops) : Result.ok(unmarkedPlacement.value.applied);
28872
+ if (unmarked.isErr()) return Result.err(unmarked.error);
28873
+ const lengths = new Map(paragraphsOf(unmarked.value.document).map((paragraph) => [paragraph.paraId, paragraphLength(paragraph)]));
28874
+ for (const { blockId, offset } of found.values()) {
28875
+ const length = lengths.get(blockId);
28876
+ if (length === void 0 || offset > length) return lost();
28877
+ }
28878
+ return Result.ok({
28879
+ ops: [...unmarkedPlacement.value.ops],
28880
+ document: unmarked.value.document,
28881
+ caret: unmarkedPlacement.value.selection,
28882
+ places: (index) => found.get(index)
28883
+ });
28884
+ };
28885
+ /**
28886
+ * Clipboard blocks whose note references and comment markers name notes and
28887
+ * comments: the blocks are placed with a placeholder for each, then each note
28888
+ * and comment is copied under a fresh id where its placeholder landed, the
28889
+ * latest place first so that no copy moves the place of another. A comment
28890
+ * whose range the clipboard holds only part of is copied as a point.
28891
+ */
28892
+ const compileBlockPaste = (document, { intent, mode, firstBlockId }) => {
28893
+ const { annotations, ...placement } = intent;
28894
+ const anchored = withPasteAnchors(intent.blocks, bookmarksIn(document.package));
28895
+ if (anchored.anchors.length === 0) return compileBlockPlacement(document, {
28896
+ intent: placement,
28897
+ mode,
28898
+ firstBlockId
28899
+ });
28900
+ const refuse = (message) => Result.err(new DocumentOpRefusal({
28901
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION,
28902
+ message,
28903
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
28904
+ }));
28905
+ const story = intent.from.story;
28906
+ const notes = [];
28907
+ for (const anchor of anchored.anchors) {
28908
+ if (anchor.kind !== "note") {
28909
+ if (!annotations?.comments.some(({ id }) => id === anchor.id)) return refuse("A pasted comment marker names no copied comment.");
28910
+ notes.push(void 0);
28911
+ continue;
28912
+ }
28913
+ const note = annotations?.notes.find(({ type, id }) => type === anchor.note && id === anchor.id);
28914
+ if (note === void 0) return refuse("A pasted note reference names no copied note.");
28915
+ if (story !== OP_STORIES.MAIN) return refuse("Notes are pasted only into the document body.");
28916
+ if (note.content.some((block) => block.type !== "paragraph")) return refuse("A pasted note holds only paragraphs.");
28917
+ notes.push(note);
28918
+ }
28919
+ const placed = placeAnchoredBlocks(document, {
28920
+ intent: {
28921
+ ...placement,
28922
+ blocks: anchored.blocks
28923
+ },
28924
+ plain: anchored.plain,
28925
+ prefix: anchored.prefix,
28926
+ ids: anchored.ids,
28927
+ count: anchored.anchors.length,
28928
+ mode,
28929
+ firstBlockId
28930
+ });
28931
+ if (placed.isErr()) return placed;
28932
+ const { ops, places, caret } = placed.value;
28933
+ let current = placed.value.document;
28934
+ const copies = [];
28935
+ const ranges = /* @__PURE__ */ new Map();
28936
+ for (const [index, anchor] of anchored.anchors.entries()) {
28937
+ const at = places(index);
28938
+ if (at === void 0) continue;
28939
+ const note = notes[index];
28940
+ if (anchor.kind === "note") {
28941
+ if (note !== void 0) copies.push({
28942
+ kind: "note",
28943
+ at,
28944
+ note,
28945
+ rank: index
28946
+ });
28947
+ continue;
28948
+ }
28949
+ const range = ranges.get(anchor.id) ?? {};
28950
+ const ranked = {
28951
+ at,
28952
+ rank: index
28953
+ };
28954
+ if (anchor.kind === "commentRangeStart") range.start = ranked;
28955
+ else if (anchor.kind === "commentRangeEnd") range.end = ranked;
28956
+ else range.reference = ranked;
28957
+ ranges.set(anchor.id, range);
28958
+ }
28959
+ for (const [id, { start, end, reference }] of ranges) {
28960
+ const comment = annotations?.comments.find((each) => each.id === id) ?? panic("A pasted comment was checked against the copied comments.");
28961
+ const ranged = start !== void 0 && end !== void 0;
28962
+ const last = ranged ? end : reference ?? end ?? start;
28963
+ if (last === void 0) continue;
28964
+ copies.push({
28965
+ kind: "comment",
28966
+ from: ranged ? start.at : void 0,
28967
+ at: last.at,
28968
+ comment,
28969
+ rank: last.rank
28970
+ });
28971
+ }
28972
+ copies.sort((left, right) => right.at.order - left.at.order || right.at.offset - left.at.offset || right.rank - left.rank);
28973
+ const position = ({ blockId, offset }) => ({
28974
+ story,
28975
+ blockId,
28976
+ offset
28977
+ });
28978
+ const nextId = (ids) => maxOf((ids ?? []).map(({ id }) => id), 0) + 1;
28979
+ const freshContent = ({ content, opType, reserved }) => {
28980
+ const identified = identifyClipboardParagraphs({
28981
+ document: current,
28982
+ paragraphs: content,
28983
+ mode: {
28984
+ ...mode,
28985
+ newIds: {
28986
+ ...mode.newIds,
28987
+ revision: [...mode.newIds?.revision ?? [], ...reserved]
28988
+ }
28989
+ },
28990
+ firstBlockId: void 0
28991
+ });
28992
+ if (identified.isErr()) return Result.err(identified.error);
28993
+ const fresh = freshParagraphIds({
28994
+ document: current,
28995
+ reserved: mode.reservedBlockIds,
28996
+ lease: mode.idLease,
28997
+ count: content.length,
28998
+ opType
28999
+ });
29000
+ if (fresh.isErr()) return Result.err(fresh.error);
29001
+ for (const [index, paragraph] of identified.value.entries()) paragraph.paraId = fresh.value[index] ?? panic("A fresh paragraph id is missing.");
29002
+ return Result.ok(identified.value);
29003
+ };
29004
+ const freeRevisionIds = () => {
29005
+ const occupied = packageIdOccupancy(current.package).revisions;
29006
+ const commented = new Set((current.package.document.comments ?? []).map(({ id }) => id));
29007
+ return [...mode.type === "suggesting" ? [mode.revision.id] : [], ...mode.newIds?.revision ?? []].filter((candidate) => !occupied.has(candidate) && !commented.has(candidate));
29008
+ };
29009
+ const out = [...ops];
29010
+ for (const copy of copies) {
29011
+ let op;
29012
+ if (copy.kind === "note") {
29013
+ const content = freshContent({
29014
+ content: copy.note.content.filter((block) => block.type === "paragraph"),
29015
+ opType: DOCUMENT_OP_TYPES.ADD_NOTE,
29016
+ reserved: []
29017
+ });
29018
+ if (content.isErr()) return Result.err(content.error);
29019
+ const note = copy.note.type === "footnote" ? {
29020
+ ...cloneModel(copy.note),
29021
+ id: nextId(current.package.footnotes),
29022
+ content: content.value
29023
+ } : {
29024
+ ...cloneModel(copy.note),
29025
+ id: nextId(current.package.endnotes),
29026
+ content: content.value
29027
+ };
29028
+ let stamp = {};
29029
+ if (mode.type === "suggesting") {
29030
+ const [id, ...rest] = freeRevisionIds();
29031
+ if (id === void 0) return Result.err(new DocumentOpRefusal({
29032
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
29033
+ message: "The pasted notes need more revision ids.",
29034
+ opType: DOCUMENT_OP_TYPES.ADD_NOTE
29035
+ }));
29036
+ stamp = {
29037
+ revision: {
29038
+ ...mode.revision,
29039
+ id
29040
+ },
29041
+ newIds: {
29042
+ revision: rest,
29043
+ control: mode.newIds.control ?? []
29044
+ }
29045
+ };
29046
+ }
29047
+ op = {
29048
+ type: DOCUMENT_OP_TYPES.ADD_NOTE,
29049
+ at: position(copy.at),
29050
+ note,
29051
+ ...stamp
29052
+ };
29053
+ } else {
29054
+ const fresh = freshCommentId(current, mode.idLease);
29055
+ if (fresh.isErr()) return Result.err(fresh.error);
29056
+ const commentId = fresh.value;
29057
+ const content = freshContent({
29058
+ content: copy.comment.content,
29059
+ opType: DOCUMENT_OP_TYPES.CREATE_COMMENT,
29060
+ reserved: [commentId]
29061
+ });
29062
+ if (content.isErr()) return Result.err(content.error);
29063
+ const { parentId: _parent, suggestionId: _suggestion, ...source } = cloneModel(copy.comment);
29064
+ const proposed = mode.type === "suggesting" ? mode.revision.suggestionId : void 0;
29065
+ op = {
29066
+ type: DOCUMENT_OP_TYPES.CREATE_COMMENT,
29067
+ newIds: {
29068
+ revision: freeRevisionIds().filter((id) => id !== commentId),
29069
+ control: mode.newIds?.control ?? []
29070
+ },
29071
+ comment: {
29072
+ ...source,
29073
+ id: commentId,
29074
+ content: content.value,
29075
+ anchorKind: copy.from === void 0 ? "point" : "range",
29076
+ ...proposed === void 0 ? {} : { suggestionId: proposed }
29077
+ },
29078
+ anchor: copy.from === void 0 ? {
29079
+ kind: "point",
29080
+ at: position(copy.at)
29081
+ } : {
29082
+ kind: "range",
29083
+ from: position(copy.from),
29084
+ to: position(copy.at)
29085
+ }
29086
+ };
29087
+ }
29088
+ const applied = applyDocumentOp(current, op);
29089
+ if (applied.isErr()) return Result.err(applied.error);
29090
+ out.push(trimAppliedNewIds({
29091
+ before: current,
29092
+ op,
29093
+ applied: applied.value,
29094
+ story
29095
+ }));
29096
+ current = applied.value.document;
29097
+ }
29098
+ const passed = copies.filter(({ at }) => at.blockId === caret.blockId && at.offset <= caret.offset).length;
29099
+ return Result.ok({
29100
+ ops: out,
29101
+ selection: {
29102
+ ...caret,
29103
+ offset: caret.offset + passed
29104
+ }
29105
+ });
29106
+ };
29107
+ /**
29108
+ * Clipboard blocks with tables: one step after another, each compiled against
29109
+ * the document the last left and, suggesting, taking the revision ids the
29110
+ * steps before it left unused.
29111
+ */
29112
+ const compileBlockPlacement = (document, { intent, mode, firstBlockId }) => {
29113
+ const { from, to, openStart, openEnd } = intent;
29114
+ const paragraphs = intent.blocks.filter((block) => block.type === "paragraph");
29115
+ if (paragraphs.length === intent.blocks.length) return compileEditorIntent(document, {
29116
+ intent: {
29117
+ type: "replaceFragment",
29118
+ from,
29119
+ to,
29120
+ paragraphs,
29121
+ openStart,
29122
+ openEnd
29123
+ },
29124
+ mode,
29125
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
29126
+ });
29127
+ const identified = identifyClipboardParagraphs({
29128
+ document,
29129
+ paragraphs: intent.blocks.flatMap(blockParagraphs),
29130
+ mode,
29131
+ firstBlockId
29132
+ });
29133
+ if (identified.isErr()) return Result.err(identified.error);
29134
+ let next = 0;
29135
+ const take = () => identified.value[next++] ?? panic("An identified clipboard paragraph is missing.");
29136
+ const rebuilt = (block) => block.type === "paragraph" ? take() : {
29137
+ ...block,
29138
+ rows: block.rows.map((row) => ({
29139
+ ...row,
29140
+ cells: row.cells.map((cell) => ({
29141
+ ...cell,
29142
+ content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? rebuilt(inner) : inner)
29143
+ }))
29144
+ }))
29145
+ };
29146
+ const blocks = intent.blocks.map(rebuilt);
29147
+ const refuseIdentities = (message) => Result.err(new DocumentOpRefusal({
29148
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION,
29149
+ message,
29150
+ opType: DOCUMENT_OP_TYPES.INSERT_TABLE
29151
+ }));
29152
+ if (blocks.some(holdsTableLevelIdentities)) return refuseIdentities("A pasted table's own bookmarks and tracked records need fresh identities.");
29153
+ const joinedBlocks = /* @__PURE__ */ new Set();
29154
+ if (openStart === 1 && blocks.at(0)?.type === "paragraph") joinedBlocks.add(0);
29155
+ if (openEnd === 1 && blocks.at(-1)?.type === "paragraph") joinedBlocks.add(blocks.length - 1);
29156
+ const bookmarkBlocks = /* @__PURE__ */ new Map();
29157
+ for (const [index, block] of blocks.entries()) for (const paragraph of blockParagraphs(block)) for (const id of bookmarkIdsIn(paragraph.content)) {
29158
+ const holders = bookmarkBlocks.get(id) ?? /* @__PURE__ */ new Set();
29159
+ holders.add(index);
29160
+ bookmarkBlocks.set(id, holders);
29161
+ }
29162
+ for (const holders of bookmarkBlocks.values()) if (holders.size > 1 && [...holders].some((index) => joinedBlocks.has(index))) return refuseIdentities("A pasted bookmark spanning a joined paragraph and a table needs one identity.");
29163
+ const ops = [];
29164
+ let current = document;
29165
+ let pool = mode.type === "suggesting" ? [mode.revision.id, ...mode.newIds.revision ?? []] : [];
29166
+ const step = (stepIntent) => {
29167
+ let stepMode = mode;
29168
+ if (mode.type === "suggesting") {
29169
+ const [id, ...rest] = pool;
29170
+ if (id === void 0) return Result.err(new DocumentOpRefusal({
29171
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
29172
+ message: "The pasted blocks need more revision ids.",
29173
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
29174
+ }));
29175
+ stepMode = {
29176
+ ...mode,
29177
+ revision: {
29178
+ ...mode.revision,
29179
+ id
29180
+ },
29181
+ newIds: {
29182
+ ...mode.newIds,
29183
+ revision: rest
29184
+ }
29185
+ };
29186
+ }
29187
+ const compiled = compileEditorIntent(current, {
29188
+ intent: stepIntent,
29189
+ mode: stepMode,
29190
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
29191
+ });
29192
+ if (compiled.isErr()) return Result.err(compiled.error);
29193
+ const applied = compiled.value.applied === void 0 ? applyDocumentOps(current, compiled.value.ops) : Result.ok(compiled.value.applied);
29194
+ if (applied.isErr()) return Result.err(applied.error);
29195
+ ops.push(...compiled.value.ops);
29196
+ current = applied.value.document;
29197
+ const occupied = packageIdOccupancy(current.package).revisions;
29198
+ pool = pool.filter((candidate) => !occupied.has(candidate));
29199
+ return Result.ok(compiled.value.selection);
29200
+ };
29201
+ let caret = from;
29202
+ if (from.blockId !== to.blockId || from.offset !== to.offset) {
29203
+ const cleared = step({
29204
+ type: "replaceText",
29205
+ from,
29206
+ to,
29207
+ text: ""
29208
+ });
29209
+ if (cleared.isErr()) return Result.err(cleared.error);
29210
+ caret = cleared.value;
29211
+ }
29212
+ const head = blocks.at(0);
29213
+ if (openStart === 1 && head?.type === "paragraph") {
29214
+ blocks.shift();
29215
+ const joined = step({
29216
+ type: "replaceFragment",
29217
+ from: caret,
29218
+ to: caret,
29219
+ paragraphs: [head],
29220
+ openStart: 1,
29221
+ openEnd: 1
29222
+ });
29223
+ if (joined.isErr()) return Result.err(joined.error);
29224
+ caret = joined.value;
29225
+ }
29226
+ const last = blocks.at(-1);
29227
+ const tail = openEnd === 1 && last?.type === "paragraph" ? last : void 0;
29228
+ if (tail !== void 0) blocks.pop();
29229
+ const destination = paragraphAt(current, caret);
29230
+ if (destination === void 0) return Result.err(new DocumentOpRefusal({
29231
+ reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
29232
+ message: "The clipboard destination paragraph does not exist.",
29233
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
29234
+ }));
29235
+ if (holdsContentWithin({
29236
+ paragraph: destination,
29237
+ from: 0,
29238
+ to: caret.offset
29239
+ })) {
29240
+ const fresh = freshParagraphIds({
29241
+ document: current,
29242
+ reserved: mode.reservedBlockIds,
29243
+ lease: mode.idLease,
29244
+ count: 1,
29245
+ opType: DOCUMENT_OP_TYPES.SPLIT_BLOCK
29246
+ });
29247
+ if (fresh.isErr()) return Result.err(fresh.error);
29248
+ const newBlockId = fresh.value[0] ?? panic("A fresh paragraph id is missing.");
29249
+ const split = step({
29250
+ type: "splitParagraph",
29251
+ at: caret,
29252
+ newBlockId
29253
+ });
29254
+ if (split.isErr()) return Result.err(split.error);
29255
+ }
29256
+ const anchor = caret.blockId;
29257
+ for (const block of blocks) {
29258
+ const placed = step(block.type === "paragraph" ? {
29259
+ type: "insertParagraphs",
29260
+ story: caret.story,
29261
+ at: {
29262
+ type: "before",
29263
+ blockId: anchor
29264
+ },
29265
+ paragraphs: [block]
29266
+ } : {
29267
+ type: "tableBlock",
29268
+ operation: {
29269
+ type: DOCUMENT_OP_TYPES.INSERT_TABLE,
29270
+ story: caret.story,
29271
+ blockId: anchor,
29272
+ table: block,
29273
+ side: "before",
29274
+ paragraphAfter: "none"
29275
+ }
29276
+ });
29277
+ if (placed.isErr()) return Result.err(placed.error);
29278
+ }
29279
+ let selection = {
29280
+ story: caret.story,
29281
+ blockId: anchor,
29282
+ offset: 0
29283
+ };
29284
+ if (tail !== void 0) {
29285
+ const joined = step({
29286
+ type: "replaceFragment",
29287
+ from: selection,
29288
+ to: selection,
29289
+ paragraphs: [tail],
29290
+ openStart: 1,
29291
+ openEnd: 1
29292
+ });
29293
+ if (joined.isErr()) return Result.err(joined.error);
29294
+ selection = joined.value;
29295
+ }
29296
+ return Result.ok({
29297
+ ops,
29298
+ selection
29299
+ });
29300
+ };
26682
29301
  /** The first paragraph of the cell a merge made, which keeps its place. */
26683
29302
  const mergedCellParagraph = ({ document, op, located }) => {
26684
29303
  const leading = tableGrid(located.table, op.type).map(({ rows }) => rows[op.top]?.find(({ start }) => start === op.left)).unwrapOr(void 0);
@@ -26986,7 +29605,9 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
26986
29605
  return id;
26987
29606
  };
26988
29607
  const remintedControls = /* @__PURE__ */ new WeakSet();
29608
+ const keptMarkers = [];
26989
29609
  visit(copy, (value) => {
29610
+ if ("keptCut" in value) keptMarkers.push(value);
26990
29611
  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") {
26991
29612
  value.properties.id = freshId(IDENTITY_SPACES.CONTROL, value.properties.id);
26992
29613
  remintedControls.add(value.properties);
@@ -26999,6 +29620,14 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
26999
29620
  else if (isCopiedRangeMarker(value)) value.id = freshId("bookmark", value.id);
27000
29621
  }
27001
29622
  });
29623
+ for (const marker of keptMarkers) {
29624
+ const cut = marker.keptCut;
29625
+ if (!isKeptCut(cut)) continue;
29626
+ marker.keptCut = remapKeptCutHolders(cut, (id) => remapped.get(slotKey({
29627
+ space: IDENTITY_SPACES.REVISION,
29628
+ id
29629
+ })));
29630
+ }
27002
29631
  if (leaseExhausted) return Result.err(new DocumentOpRefusal({
27003
29632
  reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
27004
29633
  message: "The pasted content needs more ids than the lease holds.",
@@ -27357,6 +29986,11 @@ const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting
27357
29986
  ...firstBlockId === void 0 ? {} : { firstBlockId }
27358
29987
  })
27359
29988
  });
29989
+ case "pasteBlocks": return compileBlockPaste(document, {
29990
+ intent,
29991
+ mode,
29992
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
29993
+ });
27360
29994
  case "replaceFragment": {
27361
29995
  if (intent.paragraphs.length === 0) return compileEditorIntent(document, {
27362
29996
  intent: {
@@ -27401,8 +30035,13 @@ const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting
27401
30035
  const endpoint = paragraphAt(document, intent.to);
27402
30036
  const destinationFormatting = splitParagraphFields$1(document, intent.from).formatting;
27403
30037
  const endpointFormatting = splitParagraphFields$1(document, intent.to).formatting;
27404
- const prefixBoundary = intent.openStart === 0 && intent.from.offset > 0;
27405
- const suffixBoundary = intent.openEnd === 0 && endpoint !== void 0 && intent.to.offset < paragraphLength(endpoint);
30038
+ const keeps = (paragraph, from, to) => paragraph !== void 0 && holdsContentWithin({
30039
+ paragraph,
30040
+ from,
30041
+ to
30042
+ });
30043
+ const prefixBoundary = intent.openStart === 0 && keeps(destination, 0, intent.from.offset);
30044
+ const suffixBoundary = intent.openEnd === 0 && endpoint !== void 0 && keeps(endpoint, intent.to.offset, paragraphLength(endpoint));
27406
30045
  const normalized = [
27407
30046
  ...prefixBoundary ? [{
27408
30047
  type: "paragraph",
@@ -29584,6 +32223,7 @@ const paragraphMarkChange = object({
29584
32223
  info: trackedChangeInfo,
29585
32224
  resolutionJoin: optional(natural),
29586
32225
  survivor: optional(literal("first")),
32226
+ takenOverMark: optional(natural),
29587
32227
  splitDate: optional(string),
29588
32228
  deletion: optional(object({ info: trackedChangeInfo }))
29589
32229
  });
@@ -32317,6 +34957,32 @@ const fragmentedDeletionOverlap = (op, over) => {
32317
34957
  const direct = op.revision === void 0 ? op : over;
32318
34958
  return tracked.revision !== void 0 && direct.revision === void 0 && (tracked.newIds?.revision?.length ?? 0) > 0 && sameParagraph(tracked.from, tracked.to) && sameParagraph(tracked.from, direct.from) && sameParagraph(tracked.from, direct.to) && Math.max(tracked.from.offset, direct.from.offset) < Math.min(tracked.to.offset, direct.to.offset);
32319
34959
  };
34960
+ /**
34961
+ * The positions an operation is rebased by, where its transform maps them
34962
+ * by paragraph and offset.
34963
+ */
34964
+ const mappedPositions = (op) => {
34965
+ switch (op.type) {
34966
+ case DOCUMENT_OP_TYPES.INSERT_TEXT:
34967
+ case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return [op.at];
34968
+ case DOCUMENT_OP_TYPES.DELETE_RANGE:
34969
+ case DOCUMENT_OP_TYPES.SET_RUN_PROPS: return [op.from, op.to];
34970
+ default: return [];
34971
+ }
34972
+ };
34973
+ /**
34974
+ * Whether `op` has a position at an offset `over`'s range spans, where
34975
+ * `over` is a deletion whose ends name zero-width leaves. Such a deletion
34976
+ * changes the zero-width gaps only at those offsets: a direct one removes
34977
+ * the leaves strictly inside it but keeps some range boundaries there, and
34978
+ * a tracked one wraps leaves a position among them would fall inside. A
34979
+ * position elsewhere moves by its offset alone. The transform refuses the
34980
+ * pair, so it is outside the tracked-order policy too.
34981
+ */
34982
+ const zeroWidthSpanOverlap = (op, over) => {
34983
+ if (over.type !== DOCUMENT_OP_TYPES.DELETE_RANGE || (over.from.zeroWidthBefore ?? 0) === 0 && (over.to.zeroWidthBefore ?? 0) === 0) return false;
34984
+ return mappedPositions(op).some((position) => sameParagraph(position, over.from) && over.from.offset <= position.offset && position.offset <= over.to.offset);
34985
+ };
32320
34986
  // src/ops/sequencing/transform.ts
32321
34987
  const operationStory = (op) => {
32322
34988
  switch (op.type) {
@@ -32584,7 +35250,7 @@ const transformRestoredOp = ({ op, over, effect, order }) => {
32584
35250
  if (op.type === DOCUMENT_OP_TYPES.INSERT_TEXT && over.type === DOCUMENT_OP_TYPES.SET_RUN_PROPS && op.runProps !== "inherit" && op.at.offset >= over.from.offset && op.at.offset <= over.to.offset) return refusal(op, over, "Explicit inserted formatting needs a range partition.");
32585
35251
  if (over.type === DOCUMENT_OP_TYPES.DELETE_RANGE && over.revision && op.type === DOCUMENT_OP_TYPES.INSERT_TEXT && op.at.offset > over.from.offset && op.at.offset < over.to.offset) return refusal(op, over, "Insertion inside tracked-deleted content requires wrapper affinity.");
32586
35252
  if (op.type === DOCUMENT_OP_TYPES.DELETE_RANGE && op.revision && over.type === DOCUMENT_OP_TYPES.INSERT_TEXT && over.at.offset > op.from.offset && over.at.offset < op.to.offset) return refusal(op, over, "Tracking a concurrent insertion requires a revision partition.");
32587
- if (over.type === DOCUMENT_OP_TYPES.DELETE_RANGE && ((over.from.zeroWidthBefore ?? 0) !== 0 || (over.to.zeroWidthBefore ?? 0) !== 0)) return refusal(op, over, "Tracked deletion and zero-width boundaries require an unchanged range.");
35253
+ if (zeroWidthSpanOverlap(op, over)) return refusal(op, over, "Tracked deletion and zero-width boundaries require an unchanged range.");
32588
35254
  const mapping = {
32589
35255
  over,
32590
35256
  effect,
@@ -34249,4 +36915,4 @@ const resolvedDocumentView = (document, decision) => {
34249
36915
  const storyBody = storyBody$1;
34250
36916
  const findStoryBody = findStoryBody$1;
34251
36917
  const sameStory = sameStory$2;
34252
- 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, isTextOnlyRun, joinPropertyChangeLink, leasedIdCensus, locateParagraphInBlockList, locateParagraphThroughTextBoxes, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteDeletionOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, orphanRootCommentIds, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, 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, suggestedCommentIds, suggestionRevisionInfos, survivingComments, textBoxContentsIn, toOpEnvelope, transferParagraphPropertySnapshot, transformBatch, transformPosition, trimIdLease, tryTrackedInsertionGroup, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withParagraphCopies, withParagraphRenderings, withTextBoxesClosed, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };
36918
+ 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, suggestionRevisionInfos, survivingComments, textBoxContentsIn, toOpEnvelope, transferParagraphPropertySnapshot, transformBatch, transformPosition, trimIdLease, tryTrackedInsertionGroup, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withParagraphCopies, withParagraphRenderings, withTextBoxesClosed, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };