plitejs 54.0.0-beta.7 → 54.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/authored/index.d.ts +44 -41
  2. package/dist/authored/index.js +16489 -16181
  3. package/dist/{authored-veto-CferDljr.js → authored-veto-DLmBMIcy.js} +1 -1
  4. package/dist/{clipboard-format-key-CLFcThXH.js → clipboard-format-key-SzffxWqa.js} +1 -1
  5. package/dist/{comparison-plan-7iIABSWG.js → comparison-plan-BqFJWjO4.js} +36 -14
  6. package/dist/{create-editor-acDgsovY.js → create-editor-kU8fg-PF.js} +6 -30
  7. package/dist/diff/index.d.ts +2 -32
  8. package/dist/diff/index.js +7 -378
  9. package/dist/dom/index.d.ts +2 -2
  10. package/dist/dom/index.js +2 -2
  11. package/dist/{dom-B5bAma7X.js → dom-SUWlnfT9.js} +562 -145
  12. package/dist/history/index.d.ts +5 -5
  13. package/dist/history/index.js +2041 -1833
  14. package/dist/history-skip-CcEhIzak.js +35 -0
  15. package/dist/hyperscript/index.d.ts +1 -1
  16. package/dist/hyperscript/index.js +1 -1
  17. package/dist/{hyperscript-BXUV6sdO.js → hyperscript-DdeGYoSc.js} +3 -2
  18. package/dist/{index-CTTjpWgb.d.ts → index-4PpawhYe.d.ts} +1 -1
  19. package/dist/{index-DJvrmSRP.d.ts → index-BsOySJwr.d.ts} +9 -9
  20. package/dist/{index-D8DQ1YFB.d.ts → index-CHEKdrHP.d.ts} +12 -4
  21. package/dist/{comparison-types-CsmDG5r2.d.ts → index-DM-b6jEe.d.ts} +21 -57
  22. package/dist/{index-LhVJuuEf.d.ts → index-DqmhcD_0.d.ts} +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +5 -4
  25. package/dist/internal/index.d.ts +2 -2
  26. package/dist/internal/index.js +66 -5
  27. package/dist/law-check-Bvnz2EKh.js +19271 -0
  28. package/dist/pagination/index.d.ts +1 -1
  29. package/dist/pagination/index.js +1 -1
  30. package/dist/pagination/react.d.ts +2 -2
  31. package/dist/pagination/react.js +92 -46
  32. package/dist/{pagination-CwjmxPoX.js → pagination-XEnxZ1DX.js} +2 -1
  33. package/dist/{plugin-BZCGtqMI.js → plugin-B8uCi-Hr.js} +8758 -19452
  34. package/dist/{range-geometry-CZari453.d.ts → range-geometry-B2f67yLv.d.ts} +1 -1
  35. package/dist/{range-geometry-CqWrwkjH.js → range-geometry-BGKYQHqO.js} +3 -2
  36. package/dist/react/index.d.ts +3 -3
  37. package/dist/react/index.js +7 -6
  38. package/dist/react/virtualized.d.ts +2 -2
  39. package/dist/react/virtualized.js +59 -38
  40. package/dist/{react-DO9IETEQ.js → react-B6B-5z7t.js} +24 -55
  41. package/dist/{retraction-RHEKiF3h.js → retraction-BMzQ2on5.js} +1 -1
  42. package/dist/scroll-root-DudA40xj.js +25 -0
  43. package/dist/{src-fLbHzUjC.js → src--BZ7fZY4.js} +60 -26
  44. package/dist/testing/index.d.ts +2 -2
  45. package/dist/testing/index.js +4 -3
  46. package/dist/{tx-only-1FM45FSj.d.ts → tx-only-D8lpB-sT.d.ts} +338 -147
  47. package/dist/{update-policy-C32RjjGt.js → update-policy-J-4sHmrg.js} +2 -1
  48. package/dist/{use-editor-dom-scope-CUBnNAZV.js → use-editor-dom-scope-BFWvutxn.js} +2837 -2093
  49. package/dist/yjs/index.d.ts +1 -1
  50. package/dist/yjs/index.js +1 -1
  51. package/dist/yjs/react/index.d.ts +3 -3
  52. package/dist/yjs/react/index.js +3 -3
  53. package/dist/{yjs-BMguSAX_.js → yjs-DPngKQWQ.js} +114 -39
  54. package/package.json +2 -3
@@ -1,4 +1,6 @@
1
- import { $d as invertCarriedRun, $l as mapAnchorHistoryRecovery, $r as registerEditorHistoryRuntime, Aa as recordedDeleteGroupingInput, Bd as UNKNOWN_FACTS, Bo as rootChildrenOf, Cf as isInternalTextOnlyDocumentChange, Cl as getDocumentChangeRelocations, Cu as getCompiledEditorSchema, Df as valueRoot, Dm as countCoreWork, Ef as transformInternalDocumentChange, Er as getUpdateView, Eu as getPluginRegistry, Ff as addSection, Gd as flipFacts, Gf as markReadBack, Hf as mapRootChangePositionBackward, Id as classifyDocumentChange, Io as resolveBookmark, Jd as recordedFacts, Jf as alike, Jp as decodeEditorEffect, Kf as joinsOf, Lf as applyPropertyModifications, Lr as isBuildingTransactionSpec, Mf as withoutRetainedRecordSets, Mm as jsonEqual, Mn as emitAnyEditorEffect, Ms as txLocate, Mu as areEditorSchemaIdentitiesEqual, Nf as RootChange, Nn as enterEditorRead, Np as getValueRecords, Ns as txOnly, Od as getEditorRuntime, Of as valueRootIndex, Om as readCoreWork, Op as getRecordEntries, Pl as getAuthoredUpdateView, Pm as getDefined, Pp as hasRecord, Qd as exactRunOn, Qf as DocumentIndex, Qr as recordEditorHistoryReplayReceipt, Rd as NO_FACTS, Rf as applyPropertyModificationsToSlice, Sf as isInternalDocumentChangeNoop, Si as setTypedMarks, Sl as snapshotIndexOf, So as changedBookmarks, Tc as withLandedMarks, Tf as mapInternalDocumentChangePosition, To as getBookmark, Ud as factsFromJSON, Vd as composeFacts, Vo as sameCarets, Wa as setActiveHistoryReplayOrigin, Wd as factsToJSON, Xd as carriedLetterPairs, Xf as tokenAlike, Xp as encodeEditorEffect, Yl as consumeAnchorHistoryCapture, Yu as readEditorSchemaIdentity, Zd as carriesRun, Zn as getCurrentSelectionRoot, _f as getInternalDocumentChangeRecords, _l as getEditorCommitUnsettle, _p as textToken, _u as reportEditorLifecycleError, ap as normalizeSetValues, cl as getEditorCommitAdmission, cm as mapEffect, df as documentChangeWritesOnlyElementProperties, dl as getEditorCommitFacts, dp as getDocumentSliceNodeKeys, ef as landCarriedRuns, eu as mergeAnchorHistoryRecovery, fp as isElementNode, gc as encodeEditorSelection, gf as getInternalDocumentChangeRanges, gl as getEditorCommitStartedAt, hc as decodeEditorSelection, hf as getInternalDocumentChangeEntries, hl as getEditorCommitSnapshot, ho as gridRolesOf, hp as openToken, id as EditorSchemaValidationError, if as alignedDocumentChange, im as createEditorEffect, jd as getEditorSchema, jf as withInternalDocumentRootChange, jn as documentReplacement, jp as getRecordText, ka as nativeGroupingInput, kc as constructCanonicalDocumentChange, kd as getEditorRuntimeOwner, l as definePlugin, ll as getEditorCommitCarriedRuns, lp as closeToken, lr as getEditorUpdateRoot, lt as getSelection, mc as assertSelectionSupported, mf as getInternalDocumentChangeClassificationEntries, mm as MAIN_ROOT_KEY, mp as nodeProps, mu as HISTORY_BOUNDARY_TAG, nf as widenRun, of as collapseDocumentElementPropertyWrites, om as defineUpdateAnnotation, pl as getEditorCommitRest, pp as isTextNode, qf as liftOf, qu as propertyTargetsReadParents, rd as EditorNoncanonicalChangeError, rf as DocumentChange, ru as stageAnchorHistoryRecovery, sf as createInternalDocumentChange, sm as invertEffect, sp as PreparedTokenSlice, su as toPublicRoot, tf as mapCarriedRunThrough, ti as registerEditorTransactionGuard, tp as decodeNodes, tr as getEditorDocumentValue, uf as documentChangePropertyOnlyWrites, ul as getEditorCommitCompletedTextDeletion, um as RangeApi, vd as SelectionApi, vf as getInternalDocumentChangeRootKeys, vl as getEditorCommitValue, vp as tokenLength, wo as consumeCommitCarets, xc as mapSelectionThroughChange, xm as copyRoot, xn as applyDocumentChange, yd as ElementApi, yf as getInternalDocumentRootChange, yl as historyReplayClaim, ym as isObject, yp as tokensEqual, zd as NO_ROOT_FACTS, zf as getDocumentPropertyContext, zi as withEditorUpdateRootScope, zo as restoreHistoryCarets, zr as isInTransaction } from "../plugin-BZCGtqMI.js";
1
+ import { $ as withInternalDocumentRootChange, $r as mapEffect, $t as hasInternalDocumentChangeStepFirstAt, A as getInternalDocumentRootChange, Ai as countCoreWork, An as openToken, B as isInternalRecordsOnlyChange, Ci as copyRoot, Cr as recordOpsToJson, D as getInternalDocumentChangeRanges, Dn as isElementNode, Dt as keptRunsOf$1, E as getInternalDocumentChangeEntries, F as hasV4StepsSource, G as mapInternalDocumentChangePosition, Gt as liftOf, J as transformInternalDocumentChange, Kt as alike, Li as jsonEqual, Lr as decodeEditorEffect, M as getV4Steps, Mn as textToken, O as getInternalDocumentChangeRecords, On as isTextNode, Ot as mapRootChangePositionBackward, P as hasV4RegisterSteps, Pn as tokensEqual, Qr as invertEffect, R as isExternalRootChangeOrigin, T as getInternalDocumentChangeClassificationEntries, V as isInternalTextOnlyDocumentChange, Vt as markReadBack, X as valueRootIndex, Y as valueRoot, Yr as createEditorEffect, Yt as tokenAlike, Zr as defineUpdateAnnotation, ai as MAIN_ROOT_KEY, at as extractV4Between, b as filterDocumentChangeRegisterKeys, bn as closeToken, bt as applyPropertyModifications, c as attachV4Steps, ct as applyV4Steps, d as collapseDocumentElementPropertyWrites, et as withoutRetainedRecordSets, f as copyV4StepsMetadata, fr as getRecordText, ft as toV4TextStream, g as createV4DocumentChange, gi as isObject, gt as RootChange, hr as hasRecord, in as decodeNodes, j as getV4RegisterSteps, ji as readCoreWork, k as getInternalDocumentChangeRootKeys, ki as visitRootNames, kn as nodeProps, lr as getRecordEntries, lt as elementStreamLength, mr as getValueRecords, n as DocumentChange, nt as getValueIdLookup, o as attachLazyV4Compute, p as createInternalDocumentChange, ti as RangeApi, tt as rebaseV4Changes, u as bindV4DocumentChange, ut as isTextBearingElement, v as documentChangePropertyOnlyWrites, vn as PreparedTokenSlice, vt as addSection, y as documentChangeWritesOnlyElementProperties, z as isInternalDocumentChangeNoop, zr as encodeEditorEffect } from "../law-check-Bvnz2EKh.js";
2
+ import { $d as factsToJSON, $l as consumeAnchorHistoryCapture, $r as registerEditorHistoryRuntime, $u as readEditorSchemaIdentity, Aa as nativeGroupingInput, Ao as getBookmark, Au as getPluginRegistry, Bi as withEditorUpdateRootScope, Ci as setTypedMarks, Dd as ElementApi, Do as changedBookmarks, Du as getCompiledEditorSchema, Ed as SelectionApi, Er as getUpdateView, Gd as classifyDocumentChange, Go as rootChildrenOf, Id as getEditorRuntime, Ko as sameCarets, Ld as getEditorRuntimeOwner, Lr as isBuildingTransactionSpec, Ls as txLocate, Lu as areEditorSchemaIdentitiesEqual, Mn as emitAnyEditorEffect, Nn as enterEditorRead, Nu as isStateFieldEffect, Oc as withLandedMarks, Qd as factsFromJSON, Qr as recordEditorHistoryReplayReceipt, Rl as getAuthoredUpdateView, Rs as txOnly, Sl as historyReplayClaim, Tl as snapshotIndexOf, Ua as setActiveHistoryReplayOrigin, Vo as resolveBookmark, Wo as restoreHistoryCarets, Xd as composeFacts, Yd as UNKNOWN_FACTS, Zi as isBoundToSharedRoom, Zn as getCurrentSelectionRoot, _c as assertSelectionSupported, af as exactRunOn, bl as getEditorCommitUnsettle, bo as gridRolesOf, cd as parseScopedElementId, cf as widenRun, dl as getEditorCommitAdmission, du as toPublicRoot, ef as flipFacts, fl as getEditorCommitCarriedRuns, gl as getEditorCommitRest, if as carriesRun, iu as mergeAnchorHistoryRecovery, ja as recordedDeleteGroupingInput, jd as TextApi, jn as documentReplacement, ko as consumeCommitCarets, l as definePlugin, ld as EditorNoncanonicalChangeError, lr as getEditorUpdateRoot, lt as getSelection, ml as getEditorCommitFacts, nd as schemaSetValuedResolver, of as invertCarriedRun, pl as getEditorCommitCompletedTextDeletion, qd as NO_FACTS, ru as mapAnchorHistoryRecovery, sf as landCarriedRuns, su as stageAnchorHistoryRecovery, ti as registerEditorTransactionGuard, tr as getEditorDocumentValue, ud as EditorSchemaValidationError, vc as decodeEditorSelection, vl as getEditorCommitSnapshot, vu as HISTORY_BOUNDARY_TAG, wc as mapSelectionThroughChange, xl as getEditorCommitValue, xn as applyDocumentChange, xu as reportEditorLifecycleError, yc as encodeEditorSelection, yl as getEditorCommitStartedAt, zc as constructCanonicalDocumentChange, zd as getEditorSchema, zr as isInTransaction } from "../plugin-B8uCi-Hr.js";
3
+ import { t as shouldSkipHistoryForOnlyProperties } from "../history-skip-CcEhIzak.js";
2
4
  //#region src/core/change/window.ts
3
5
  const rootOf = (root) => root ?? "main";
4
6
  const blockAt = (index, position) => {
@@ -25,7 +27,7 @@ const spansOf = (change, before, after) => {
25
27
  before: blocksOf(valueRootIndex(before, root), fromA, toA)
26
28
  });
27
29
  spans.set(root, list);
28
- });
30
+ }, { base: before });
29
31
  return spans;
30
32
  };
31
33
  const windowsOf = (entry) => [...spansOf(entry.change, entry.before, entry.after)].map(([root, spans]) => ({
@@ -267,810 +269,6 @@ const stepBranchTracks$1 = (value, commit, otherWriter, mapKept) => {
267
269
  return stepBranchTracksInner(value, entry, otherWriter, /* @__PURE__ */ new Map(), mapKept);
268
270
  };
269
271
  //#endregion
270
- //#region src/core/change/cross.ts
271
- const fail = (why) => {
272
- throw new Error(`crossRecord: ${why}.`);
273
- };
274
- const writtenRoot = (change) => {
275
- let written = null;
276
- for (const [root, rootChange] of getInternalDocumentChangeEntries(change)) {
277
- if (rootChange.sections.every((value, index) => index % 2 === 0 || value === -1)) continue;
278
- if (written) fail("a change writes more than one root");
279
- written = {
280
- change: rootChange,
281
- root
282
- };
283
- }
284
- return written;
285
- };
286
- const rootFactsOf = (facts, root) => facts.kind === "recorded" ? facts.roots.get(root) ?? NO_ROOT_FACTS : fail("a change has unknown facts");
287
- const indexAt = (spans, key, at) => {
288
- let low = 0;
289
- let high = spans.length;
290
- while (low < high) {
291
- countCoreWork("crossingPieces");
292
- const middle = low + high >> 1;
293
- const span = spans[middle];
294
- if (key(span) + span.length <= at) low = middle + 1;
295
- else if (key(span) > at) high = middle;
296
- else return middle;
297
- }
298
- return -1;
299
- };
300
- const joinRanges = (ranges) => {
301
- const tokens = [];
302
- const nodeKeys = /* @__PURE__ */ new Map();
303
- let text = "";
304
- let position = 0;
305
- for (const { from, slice, to } of ranges) {
306
- if (from === to) continue;
307
- const { offsets, tokens: source } = slice;
308
- const sourceKeys = getDocumentSliceNodeKeys(slice);
309
- let index = 0;
310
- for (let high = source.length; index < high;) {
311
- const middle = index + high >> 1;
312
- if (offsets[middle] + tokenLength(source[middle]) <= from) index = middle + 1;
313
- else high = middle;
314
- }
315
- for (; index < source.length && offsets[index] < to; index += 1) {
316
- const token = source[index];
317
- if (token.kind === "text") text += token.text.slice(Math.max(from - offsets[index], 0), to - offsets[index]);
318
- else {
319
- const nodeKey = sourceKeys.get(offsets[index]);
320
- if (nodeKey) nodeKeys.set(position + offsets[index] - from, nodeKey);
321
- if (text) tokens.push(textToken(text));
322
- text = "";
323
- tokens.push(token);
324
- }
325
- }
326
- position += to - from;
327
- }
328
- if (text) tokens.push(textToken(text));
329
- if (tokens.length === 0) return PreparedTokenSlice.empty;
330
- const joined = PreparedTokenSlice.fromTokens(tokens);
331
- return nodeKeys.size === 0 ? joined : joined.withNodeKeys(nodeKeys);
332
- };
333
- const readSkipped = (base, change, facts) => {
334
- const kept = [];
335
- const carried = [];
336
- const fresh = [];
337
- const written = [];
338
- const { carries } = facts;
339
- let drop = null;
340
- let copyGap = -1;
341
- let input = 0;
342
- let output = 0;
343
- let carry = 0;
344
- for (let index = 0; index < change.sections.length; index += 2) {
345
- const length = change.sections[index];
346
- const inserted = change.sections[index + 1];
347
- if (inserted === -1) {
348
- if (length > 0) {
349
- const span = {
350
- input,
351
- length,
352
- output
353
- };
354
- kept.push(span);
355
- written.push(span);
356
- }
357
- input += length;
358
- output += length;
359
- continue;
360
- }
361
- countCoreWork("crossingPieces");
362
- if (inserted === -2) fail("the skipped change sets a property");
363
- if (length > 0) {
364
- if (inserted > 0) fail("a skipped piece both drops and writes");
365
- if (drop && drop.to !== input) fail("the skipped change drops two runs");
366
- drop = {
367
- from: drop?.from ?? input,
368
- to: input + length
369
- };
370
- }
371
- const slice = change.data[index >> 1];
372
- const end = output + Math.max(inserted, 0);
373
- let at = output;
374
- let sourceGapAfterCarry = null;
375
- while (at < end) {
376
- while (carry < carries.length && carries[carry][0] + carries[carry][2] <= at) {
377
- countCoreWork("crossingPieces");
378
- carry += 1;
379
- }
380
- const next = carries[carry];
381
- const inCarry = next !== void 0 && next[0] <= at;
382
- const to = Math.min(inCarry ? next[0] + next[2] : next?.[0] ?? end, end);
383
- if (inCarry) {
384
- const span = {
385
- input: next[1] + at - next[0],
386
- length: to - at,
387
- output: at
388
- };
389
- carried.push(span);
390
- written.push(span);
391
- sourceGapAfterCarry = next[1] + to - next[0];
392
- copyGap = input;
393
- } else {
394
- const run = {
395
- baseGap: sourceGapAfterCarry ?? input,
396
- length: to - at,
397
- offset: at - output,
398
- output: at,
399
- slice
400
- };
401
- fresh.push(run);
402
- written.push(run);
403
- }
404
- at = to;
405
- }
406
- input += length;
407
- output += Math.max(inserted, 0);
408
- }
409
- const carriedLength = carried.reduce((sum, span) => sum + span.length, 0);
410
- if (carriedLength !== carries.reduce((sum, each) => sum + each[2], 0)) fail("a carry of the skipped change sits outside what it writes");
411
- if (drop && carriedLength !== drop.to - drop.from) fail("the skipped change drops a run its carries do not copy");
412
- const neither = (position) => fail(`input position ${position} is neither kept nor carried`);
413
- const inDrop = (position) => drop !== null && drop.from <= position && position < drop.to;
414
- const outputOf = (position) => {
415
- const spans = inDrop(position) ? carried : kept;
416
- const index = indexAt(spans, (each) => each.input, position);
417
- return index === -1 ? neither(position) : spans[index].output + position - spans[index].input;
418
- };
419
- const outputRuns = (from, to) => {
420
- const runs = [];
421
- for (let position = from; position < to;) {
422
- const spans = inDrop(position) ? carried : kept;
423
- let index = indexAt(spans, (each) => each.input, position);
424
- if (index === -1) neither(position);
425
- for (; position < to && index < spans.length && spans[index].input <= position; index += 1) {
426
- countCoreWork("crossingPieces");
427
- const span = spans[index];
428
- const end = Math.min(to, span.input + span.length);
429
- const out = span.output + position - span.input;
430
- const last = runs.at(-1);
431
- if (last?.to === out) last.to += end - position;
432
- else runs.push({
433
- from: out,
434
- to: out + end - position
435
- });
436
- position = end;
437
- }
438
- }
439
- return runs;
440
- };
441
- const pastFresh = (at) => {
442
- let position = at;
443
- for (let index = indexAt(written, (each) => each.output, at); index !== -1 && index < written.length && "slice" in written[index]; index += 1) {
444
- countCoreWork("crossingPieces");
445
- position = written[index].output + written[index].length;
446
- }
447
- return position;
448
- };
449
- const outputSlice = (from, to) => {
450
- const ranges = [];
451
- const baseRuns = [];
452
- let index = indexAt(written, (each) => each.output, from);
453
- for (let at = from; at < to; index += 1) {
454
- countCoreWork("crossingPieces");
455
- const span = index === -1 || index >= written.length ? fail(`output position ${at} is written by no span`) : written[index];
456
- const end = Math.min(to, span.output + span.length);
457
- if ("slice" in span) ranges.push({
458
- from: span.offset + at - span.output,
459
- slice: span.slice,
460
- to: span.offset + end - span.output
461
- });
462
- else {
463
- const inputAt = span.input + at - span.output;
464
- let run = baseRuns.at(-1);
465
- if (run?.to !== inputAt) {
466
- run = {
467
- from: inputAt,
468
- ranges: [],
469
- to: inputAt
470
- };
471
- baseRuns.push(run);
472
- }
473
- run.to = inputAt + end - at;
474
- const range = {
475
- from: inputAt - run.from,
476
- slice: PreparedTokenSlice.empty,
477
- to: run.to - run.from
478
- };
479
- run.ranges.push(range);
480
- ranges.push(range);
481
- }
482
- at = end;
483
- }
484
- for (const run of baseRuns) {
485
- const slice = base.slice(run.from, run.to);
486
- for (const range of run.ranges) range.slice = slice;
487
- }
488
- return joinRanges(ranges);
489
- };
490
- return {
491
- copyGap,
492
- drop,
493
- fresh,
494
- outputOf,
495
- outputRuns,
496
- outputSlice,
497
- pastFresh
498
- };
499
- };
500
- const changeFrom = (length, edits) => {
501
- const sections = [];
502
- const data = [];
503
- const starts = [];
504
- let input = 0;
505
- let output = 0;
506
- for (const edit of edits) {
507
- if (edit.from < input) fail("two edits of a derived change overlap");
508
- addSection(sections, data, edit.from - input, -1, null);
509
- output += edit.from - input;
510
- starts.push(output);
511
- if (edit.modifications) {
512
- addSection(sections, data, 1, -2, edit.modifications);
513
- output += 1;
514
- } else {
515
- const insert = edit.insert ?? PreparedTokenSlice.empty;
516
- addSection(sections, data, edit.to - edit.from, insert.length, insert);
517
- output += insert.length;
518
- }
519
- input = edit.to;
520
- }
521
- addSection(sections, data, length - input, -1, null);
522
- const outputOf = (position) => {
523
- let shift = 0;
524
- for (const edit of edits) {
525
- if (edit.to > position) {
526
- if (edit.from <= position && edit.from !== edit.to) fail(`position ${position} is dropped by a derived change`);
527
- break;
528
- }
529
- const removed = edit.to - edit.from;
530
- shift += (edit.modifications ? removed : edit.insert?.length ?? 0) - removed;
531
- }
532
- return position + shift;
533
- };
534
- return {
535
- change: RootChange.fromSections(sections, data),
536
- outputOf,
537
- starts
538
- };
539
- };
540
- const readStep = (change) => {
541
- let input = 0;
542
- let piece = null;
543
- let closed = false;
544
- for (let index = 0; index < change.sections.length; index += 2) {
545
- const length = change.sections[index];
546
- const inserted = change.sections[index + 1];
547
- if (inserted === -1) {
548
- if (piece) closed = true;
549
- input += length;
550
- continue;
551
- }
552
- countCoreWork("crossingPieces");
553
- if (closed || piece?.modifications) fail("the step holds more than one piece");
554
- if (inserted === -2) {
555
- if (piece) fail("the step holds more than one piece");
556
- piece = {
557
- at: input,
558
- dropped: 0,
559
- modifications: change.data[index >> 1],
560
- written: []
561
- };
562
- } else {
563
- piece ??= {
564
- at: input,
565
- dropped: 0,
566
- modifications: null,
567
- written: []
568
- };
569
- piece.dropped += length;
570
- piece.written.push(change.data[index >> 1]);
571
- }
572
- input += length;
573
- }
574
- return piece ?? fail("the step holds no piece");
575
- };
576
- const asChange = (root, change, facts) => ({
577
- change: createInternalDocumentChange(/* @__PURE__ */ new Map([[root, change]])),
578
- facts
579
- });
580
- /**
581
- * Follows a stored undo step across a change history skipped, for a pair
582
- * phase 1's rule admits. Both changes apply to `document`. The crossing reads
583
- * positions, facts and token kinds and never compares two values: a step's
584
- * edit follows the token it was bound to, at one gap the skipped change's
585
- * letters come first, and a join moves the joined line's children to the end
586
- * of the line it joins, wherever the skipped change put either. A pair it
587
- * cannot place is a bug, so it throws.
588
- *
589
- * @internal
590
- */
591
- const crossRecord = (document, step, skipped) => {
592
- const stepRoot = writtenRoot(step.change);
593
- const skippedRoot = writtenRoot(skipped.change);
594
- if (!stepRoot) return fail("the step writes nothing");
595
- if (!skippedRoot || skippedRoot.root !== stepRoot.root) return {
596
- followed: step,
597
- leftover: skipped
598
- };
599
- const { root } = stepRoot;
600
- const base = valueRootIndex(document, root);
601
- const stepChange = stepRoot.change;
602
- const skippedChange = skippedRoot.change;
603
- if (base.length !== stepChange.length || base.length !== skippedChange.length) fail("a change does not fit the document");
604
- const stepFacts = rootFactsOf(step.facts, root);
605
- const skippedFacts = rootFactsOf(skipped.facts, root);
606
- countCoreWork("crossingPieces", stepFacts.heirs.length + stepFacts.merges.length + skippedFacts.carries.length);
607
- const piece = readStep(stepChange);
608
- const k = readSkipped(base, skippedChange, skippedFacts);
609
- const written = PreparedTokenSlice.concat(piece.written);
610
- const join = piece.dropped > 0 && stepFacts.merges.length > 0;
611
- const levels = piece.dropped / 2;
612
- const joinedClose = join ? (base.nodeStartingAt(piece.at + levels)?.to ?? fail("a join drops no open of the line it joins")) - 1 : -1;
613
- const followed = followStep({
614
- joinedClose,
615
- k,
616
- levels,
617
- piece,
618
- skippedChange,
619
- stepFacts,
620
- written
621
- });
622
- const leftover = leaveSkipped({
623
- base,
624
- join,
625
- joinedClose,
626
- k,
627
- piece,
628
- written
629
- });
630
- return {
631
- followed: asChange(root, followed.change, recordedFacts([[root, followed.facts]])),
632
- leftover: leftover ? asChange(root, leftover.change, recordedFacts([[root, {
633
- carries: leftover.carries,
634
- heirs: [],
635
- merges: []
636
- }]])) : {
637
- change: DocumentChange.empty,
638
- facts: NO_FACTS
639
- }
640
- };
641
- };
642
- const followStep = ({ joinedClose, k, levels, piece, skippedChange, stepFacts, written }) => {
643
- const length = skippedChange.newLength;
644
- const carries = [];
645
- const heirs = [];
646
- const merges = [];
647
- if (piece.modifications) {
648
- const at = k.outputOf(piece.at);
649
- const { change } = changeFrom(length, [{
650
- from: at,
651
- modifications: piece.modifications,
652
- to: at + 1
653
- }]);
654
- return {
655
- change,
656
- facts: {
657
- carries,
658
- heirs,
659
- merges
660
- }
661
- };
662
- }
663
- if (written.length > 0) {
664
- if (piece.at === 0) fail("the step writes before every token");
665
- const at = k.pastFresh(k.outputOf(piece.at - 1) + 1);
666
- const { change } = changeFrom(length, [{
667
- from: at,
668
- insert: written,
669
- to: at
670
- }]);
671
- for (const [heir, of] of stepFacts.heirs) heirs.push([at + heir - piece.at, k.outputOf(of)]);
672
- return {
673
- change,
674
- facts: {
675
- carries,
676
- heirs,
677
- merges
678
- }
679
- };
680
- }
681
- if (stepFacts.merges.length === 0) {
682
- const edits = k.outputRuns(piece.at, piece.at + piece.dropped);
683
- return {
684
- change: changeFrom(length, edits).change,
685
- facts: {
686
- carries,
687
- heirs,
688
- merges
689
- }
690
- };
691
- }
692
- const closes = k.outputOf(piece.at);
693
- const lineClose = k.outputOf(piece.at + levels - 1);
694
- const lineOpen = k.outputOf(piece.at + levels);
695
- for (let level = 0; level < levels; level++) if (k.outputOf(piece.at + level) !== closes + level || k.outputOf(piece.at + levels + level) !== lineOpen + level) fail("the leaves a join merges are apart");
696
- const adjacent = lineOpen === lineClose + 1;
697
- const contentEnd = k.outputOf(joinedClose);
698
- const moved = contentEnd - lineOpen - levels;
699
- const edits = adjacent ? [{
700
- from: closes,
701
- to: closes + 2 * levels
702
- }] : moved === 0 ? [{
703
- from: lineOpen,
704
- to: contentEnd + 1
705
- }] : [{
706
- from: closes,
707
- insert: k.outputSlice(lineOpen + levels, contentEnd),
708
- to: lineClose
709
- }, {
710
- from: lineOpen,
711
- to: contentEnd + 1
712
- }].sort((left, right) => left.from - right.from);
713
- const built = changeFrom(length, edits);
714
- if (!adjacent && moved > 0) {
715
- const copy = built.starts[edits.findIndex((edit) => edit.insert)];
716
- carries.push([
717
- copy,
718
- lineOpen + levels,
719
- moved
720
- ]);
721
- }
722
- for (const [at, into] of stepFacts.merges) merges.push([k.outputOf(at), built.outputOf(k.outputOf(into))]);
723
- return {
724
- change: built.change,
725
- facts: {
726
- carries,
727
- heirs,
728
- merges
729
- }
730
- };
731
- };
732
- const insertsBeforeDrops = (left, right) => left.from - right.from || Number(left.from !== left.to) - Number(right.from !== right.to);
733
- const leaveSkipped = ({ base, join, joinedClose, k, piece, written }) => {
734
- const from = piece.at;
735
- const to = piece.at + (piece.modifications ? 0 : piece.dropped);
736
- const shift = (piece.modifications ? 0 : written.length) - (to - from);
737
- const positionOf = (position) => position < from ? position : position >= to ? position + shift : null;
738
- const gapOf = (gap) => gap <= from ? gap : gap >= to ? gap + shift : from;
739
- const afterJoined = () => (positionOf(joinedClose) ?? fail("the step drops the joined line's close")) + 1;
740
- const pieceTokens = piece.modifications ? applyPropertyModificationsToSlice(base.slice(from, from + 1), piece.modifications) : written;
741
- const pieceEnd = from + pieceTokens.length;
742
- const sourceEnd = piece.modifications ? from + 1 : to;
743
- const stepSlice = (a, b) => {
744
- const parts = [];
745
- if (a < from) parts.push(base.slice(a, Math.min(b, from)));
746
- if (b > from && a < pieceEnd) parts.push(pieceTokens.slice(Math.max(a, from) - from, Math.min(b, pieceEnd) - from));
747
- if (b > pieceEnd) parts.push(base.slice(Math.max(a, pieceEnd) - pieceEnd + sourceEnd, b - pieceEnd + sourceEnd));
748
- return PreparedTokenSlice.concat(parts);
749
- };
750
- let start = -1;
751
- let end = -1;
752
- let target = -1;
753
- if (k.drop) {
754
- start = positionOf(k.drop.from) ?? afterJoined();
755
- end = (positionOf(k.drop.to - 1) ?? afterJoined() - 1) + 1;
756
- target = join && from < k.copyGap && k.copyGap < to ? afterJoined() : gapOf(k.copyGap);
757
- if (target > start && target < end) fail("the moved run lands inside itself");
758
- }
759
- const moves = start < end && target !== start && target !== end;
760
- const { drop } = k;
761
- const inside = [];
762
- const outside = [];
763
- for (const each of k.fresh) (drop && drop.from < each.baseGap && each.baseGap < drop.to ? inside : outside).push(each);
764
- const edits = [];
765
- const copyLetters = [];
766
- let outsideAt = 0;
767
- let insideAt = 0;
768
- while (outsideAt < outside.length || insideAt < inside.length) {
769
- countCoreWork("crossingPieces");
770
- const fromInside = insideAt < inside.length && (outsideAt >= outside.length || inside[insideAt].baseGap < outside[outsideAt].baseGap);
771
- const each = fromInside ? inside[insideAt] : outside[outsideAt];
772
- if (fromInside) insideAt += 1;
773
- else outsideAt += 1;
774
- const at = gapOf(each.baseGap);
775
- const runEnd = each.offset + each.length;
776
- if (moves && at > start && at < end) copyLetters.push({
777
- at,
778
- from: each.offset,
779
- slice: each.slice,
780
- to: runEnd
781
- });
782
- else edits.push({
783
- from: at,
784
- insert: each.slice.slice(each.offset, runEnd),
785
- to: at
786
- });
787
- }
788
- const carries = [];
789
- let copyEdit = null;
790
- const parts = [];
791
- if (moves) {
792
- const moved = stepSlice(start, end);
793
- const ranges = [];
794
- let at = start;
795
- for (const letter of [...copyLetters, {
796
- at: end,
797
- from: 0,
798
- slice: PreparedTokenSlice.empty,
799
- to: 0
800
- }]) {
801
- ranges.push({
802
- from: at - start,
803
- slice: moved,
804
- to: letter.at - start
805
- });
806
- ranges.push(letter);
807
- parts.push([at, letter.at]);
808
- ({at} = letter);
809
- }
810
- copyEdit = {
811
- from: target,
812
- insert: joinRanges(ranges),
813
- to: target
814
- };
815
- edits.push({
816
- from: start,
817
- to: end
818
- }, copyEdit);
819
- }
820
- if (edits.length === 0) return null;
821
- edits.sort(insertsBeforeDrops);
822
- const built = changeFrom(base.length + shift, edits);
823
- if (copyEdit) {
824
- let output = built.starts[edits.indexOf(copyEdit)];
825
- parts.forEach(([partFrom, partTo], index) => {
826
- if (partTo > partFrom) carries.push([
827
- output,
828
- partFrom,
829
- partTo - partFrom
830
- ]);
831
- const letter = copyLetters.at(index);
832
- output += partTo - partFrom + (letter ? letter.to - letter.from : 0);
833
- });
834
- }
835
- return {
836
- carries,
837
- change: built.change
838
- };
839
- };
840
- //#endregion
841
- //#region src/core/change/cross-rule.ts
842
- const piecesOf = (change) => {
843
- const pieces = [];
844
- let at = 0;
845
- let out = 0;
846
- let open = null;
847
- const close = () => {
848
- if (!open) return;
849
- pieces.push({
850
- at: open.at,
851
- dropped: open.dropped,
852
- out: open.out,
853
- properties: [],
854
- setLength: 0,
855
- written: PreparedTokenSlice.concat(open.slices)
856
- });
857
- open = null;
858
- };
859
- for (let index = 0; index < change.sections.length; index += 2) {
860
- const length = change.sections[index];
861
- const inserted = change.sections[index + 1];
862
- if (inserted < 0) {
863
- close();
864
- if (inserted === -2) pieces.push({
865
- at,
866
- dropped: 0,
867
- out,
868
- properties: change.data[index >> 1],
869
- setLength: length,
870
- written: PreparedTokenSlice.empty
871
- });
872
- at += length;
873
- out += length;
874
- continue;
875
- }
876
- open ??= {
877
- at,
878
- dropped: 0,
879
- out,
880
- slices: []
881
- };
882
- open.dropped += length;
883
- open.slices.push(change.data[index >> 1]);
884
- at += length;
885
- out += inserted;
886
- }
887
- close();
888
- return pieces;
889
- };
890
- const writtenRoots = (change) => [...getInternalDocumentChangeEntries(change)].flatMap(([root, rootChange]) => {
891
- const pieces = piecesOf(rootChange);
892
- return pieces.length === 0 ? [] : [{
893
- pieces,
894
- root,
895
- rootChange
896
- }];
897
- });
898
- const changesRootsOrRecords = (change) => change.createRoots.size > 0 || change.deleteRoots.size > 0 || getInternalDocumentChangeRecords(change).size > 0;
899
- const factsOf = (facts, root) => facts.roots.get(root) ?? NO_ROOT_FACTS;
900
- const factCount = (facts) => facts.carries.length + facts.heirs.length + facts.merges.length;
901
- const isText = (token) => token.kind === "text";
902
- const readTokens = (document, from, to) => {
903
- countCoreWork("ruleTokens", to - from);
904
- return document.slice(from, to).tokens;
905
- };
906
- const enclosing = (document, gap) => {
907
- if (gap >= document.length) return [];
908
- const context = document.openContextAt(gap).filter((range) => range.contentFrom <= gap && gap <= range.contentTo);
909
- countCoreWork("ruleTokens", context.length);
910
- return context;
911
- };
912
- const isBlock = (document, range, schema) => range?.kind === "element" && !schema.isInline(document.node(range.path));
913
- const contentAt = (document, range, schema) => schema.content(document.node(range.path));
914
- const allowsBlocks = (content, schema) => content.allowsUnknownElements || [...content.allowedElementTypes].some((type) => !schema.isInline({
915
- children: [],
916
- type
917
- }));
918
- const isTextBlock = (element, schema) => {
919
- const content = schema.content(element);
920
- return content !== "unknown" && content.allowsText && !allowsBlocks(content, schema) && !schema.isInline(element) && !schema.ownsContentRoot(element);
921
- };
922
- const retypesNoParent = (element, properties, schema) => {
923
- const retype = properties.find(({ key }) => key === "type");
924
- return !retype || retype.type === "set" && typeof retype.value === "string" && isTextBlock(element, schema) && isTextBlock({
925
- children: [],
926
- type: retype.value
927
- }, schema);
928
- };
929
- const ROOT_CONTENT_ALLOWS_TEXT = false;
930
- const parentAt = (document, gap) => enclosing(document, gap).at(-1) ?? null;
931
- const parentAllowsText = (document, parent, schema) => {
932
- if (parent === null) return ROOT_CONTENT_ALLOWS_TEXT;
933
- const content = contentAt(document, parent, schema);
934
- return content === "unknown" ? content : content.allowsText;
935
- };
936
- const destinationInside = (parent, destination) => parent === null || parent.contentFrom <= destination && destination <= parent.contentTo;
937
- const contentRejection = (document, index, root, [leaves, enters], destination, schema) => {
938
- const contentOf = (parent) => parent === null ? schema.rootContent(document, root) : contentAt(index, parent, schema);
939
- if (leaves?.from === enters?.from) {
940
- const parent = contentOf(leaves);
941
- return parent !== "unknown" && (parent.prefix?.length ?? 0) > 0 ? "the skipped change moves a block inside a parent whose content has a prefix" : null;
942
- }
943
- if (schema.propertiesReadParents()) return "the skipped change moves a block to another parent while a property target reads the parent";
944
- const left = contentOf(leaves);
945
- const entered = contentOf(enters);
946
- if (left === "unknown" || entered === "unknown") return "the skipped change moves a block out of or into an element of a type the schema does not know";
947
- const keptChildren = destinationInside(leaves, destination) ? 1 : 0;
948
- if (left.min > keptChildren || entered.max !== null || (left.prefix?.length ?? 0) > 0 || (entered.prefix?.length ?? 0) > 0) return "the skipped change moves a block out of or into a parent whose content bounds its children";
949
- return left.allowsUnknownElements && !entered.allowsUnknownElements || [...left.allowedElementTypes].some((type) => !entered.allowedElementTypes.has(type)) ? "the skipped change moves a block into a parent that refuses an element type the parent it leaves allows" : null;
950
- };
951
- const mirrors = (run) => {
952
- const levels = run.length / 2;
953
- if (!Number.isInteger(levels) || levels === 0) return false;
954
- for (let level = 0; level < levels; level++) {
955
- const close = run[levels - 1 - level];
956
- const open = run[levels + level];
957
- if (close.kind !== "close" || open.kind !== "open" || close.nodeKind !== open.nodeKind) return false;
958
- }
959
- return true;
960
- };
961
- const MOST_MIRRORED_LEVELS = 2;
962
- const droppedRun = (document, { at, dropped }) => {
963
- const leaf = enclosing(document, at).at(-1);
964
- if (leaf?.kind === "text" && at + dropped <= leaf.contentTo) return "letters";
965
- return dropped > 2 * MOST_MIRRORED_LEVELS ? "long" : readTokens(document, at, at + dropped);
966
- };
967
- /** @internal */
968
- const stepRejection = (document, step, schema) => {
969
- const { change, facts } = step;
970
- if (facts.kind === "unknown") return "the step has unknown facts";
971
- if (changesRootsOrRecords(change)) return "the step changes roots or records";
972
- const roots = writtenRoots(change);
973
- const pieceCount = roots.reduce((sum, { pieces }) => sum + pieces.length, 0);
974
- if ([...facts.roots.values()].some(({ carries }) => carries.length > 0)) return "the step carries";
975
- if (pieceCount !== 1) return `the step holds ${pieceCount} pieces`;
976
- const [{ pieces, root }] = roots;
977
- const [piece] = pieces;
978
- const { heirs, merges } = factsOf(facts, root);
979
- if ([...facts.roots].some(([other, rootFacts]) => other !== root && factCount(rootFacts) > 0)) return "a fact names no piece";
980
- const index = valueRootIndex(document, root);
981
- if (piece.setLength > 0) {
982
- if (heirs.length + merges.length > 0) return "a fact names no piece";
983
- countCoreWork("ruleTokens");
984
- const target = index.nodeStartingAt(piece.at);
985
- if (piece.setLength !== 1 || !target || !isBlock(index, target, schema)) return "a set that is not on a kept block";
986
- return retypesNoParent(index.node(target.path), piece.properties, schema) ? null : "a set writes a type other than one text block for another";
987
- }
988
- if (piece.dropped > 0 && piece.written.length > 0) return "a piece both drops and writes";
989
- const writes = piece.written.length > 0;
990
- const run = writes ? piece.written.tokens : droppedRun(index, piece);
991
- if (run === "letters" || run !== "long" && run.every(isText)) return heirs.length + merges.length > 0 ? "a fact names no piece" : null;
992
- if (run === "long") return "a run that is no mirrored split or join";
993
- if (run.some(isText)) return "a run mixes letters with structure";
994
- if (!mirrors(run)) return "a run that is no mirrored split or join";
995
- const levels = run.length / 2;
996
- const around = enclosing(index, piece.at);
997
- if (around.length < levels) return "a run closes more elements than its gap sits in";
998
- const outer = around[around.length - levels];
999
- if (!isBlock(index, outer, schema)) return "a run that is no mirrored split or join";
1000
- if (levels > MOST_MIRRORED_LEVELS || levels === MOST_MIRRORED_LEVELS && around.at(-1)?.kind !== "text") return "a run splits or joins more than a block and its text leaf";
1001
- const contents = [outer, writes ? null : index.nodeStartingAt(piece.at + levels)].flatMap((range) => range === null ? [] : [contentAt(index, range, schema)]);
1002
- if (contents.includes("unknown")) return "a run splits or joins an element of a type the schema does not know";
1003
- const known = contents.filter((content) => content !== "unknown");
1004
- if (known.some((content) => !content.allowsText)) return "a run splits or joins an element whose content allows no text";
1005
- if (known.some((content) => allowsBlocks(content, schema))) return "a run splits or joins an element whose content allows blocks";
1006
- for (let level = 0; level < levels; level++) {
1007
- const source = around[around.length - levels + level];
1008
- const open = run[levels + level];
1009
- if (open?.kind !== "open" || source.kind !== open.nodeKind) return "a run closes another kind of element";
1010
- if (writes) {
1011
- if (heirs.find(([at]) => at === piece.out + levels + level)?.[1] !== source.from) return "an heir does not name the element its mirror close ends";
1012
- } else if (merges.find(([at]) => at === piece.at + levels + level)?.[1] !== source.from) return "a merge does not name the element its mirror close ends";
1013
- }
1014
- return (writes ? heirs.length === levels && merges.length === 0 : merges.length === levels && heirs.length === 0) ? null : "a fact names no piece";
1015
- };
1016
- /** @internal */
1017
- const skippedRejection = (document, skipped, schema) => {
1018
- const { change, facts } = skipped;
1019
- if (facts.kind === "unknown") return "the skipped change has unknown facts";
1020
- if (changesRootsOrRecords(change)) return "the skipped change changes roots or records";
1021
- const tables = [...facts.roots.values()];
1022
- if (tables.some((each) => each.heirs.length + each.merges.length > 0)) return "the skipped change splits or joins";
1023
- if (tables.every((each) => each.carries.length === 0)) return "the skipped change moves nothing";
1024
- const roots = writtenRoots(change);
1025
- if (roots.some(({ pieces }) => pieces.some((piece) => piece.setLength > 0))) return "the skipped change sets a property";
1026
- const drops = roots.flatMap(({ pieces, root }) => pieces.filter((piece) => piece.dropped > 0).map((piece) => ({
1027
- piece,
1028
- root
1029
- })));
1030
- if (drops.length !== 1 || drops[0].piece.written.length > 0) return "the skipped change does not drop exactly one run";
1031
- if (roots.length > 1) return "the skipped change writes in more than one root";
1032
- const [{ piece: drop, root }] = drops;
1033
- const index = valueRootIndex(document, root);
1034
- countCoreWork("ruleTokens");
1035
- const block = index.nodeStartingAt(drop.at);
1036
- if (!isBlock(index, block, schema) || block?.to !== drop.at + drop.dropped) return "the skipped change drops no whole block";
1037
- const { carries } = factsOf(facts, root);
1038
- const [first] = carries;
1039
- let next = drop.at;
1040
- for (const [, from, length] of carries) {
1041
- if (from !== next) return "the carries do not cover the moved block in order";
1042
- next += length;
1043
- }
1044
- if (next !== drop.at + drop.dropped) return "the carries do not cover the moved block in order";
1045
- const copy = roots[0].pieces.find((piece) => piece.out <= first[0] && first[0] < piece.out + piece.written.length);
1046
- const last = carries.at(-1);
1047
- if (!copy || !last || last[0] + last[2] > copy.out + copy.written.length) return "the carries do not cover the moved block in order";
1048
- const ends = [parentAt(index, drop.at), parentAt(index, copy.at)];
1049
- const parents = new Set(ends.map((parent) => parentAllowsText(index, parent, schema)));
1050
- if (parents.has("unknown")) return "the skipped change moves a block out of or into an element of a type the schema does not know";
1051
- if (parents.has(true)) return "the skipped change moves a block out of or into an element whose content allows text";
1052
- const refused = contentRejection(document, index, root, ends, copy.at, schema);
1053
- if (refused) return refused;
1054
- for (const piece of roots[0].pieces) {
1055
- let position = piece.out;
1056
- let carry = 0;
1057
- for (const token of piece.written.tokens) {
1058
- const length = token.kind === "text" ? token.text.length : 1;
1059
- if (token.kind !== "text") {
1060
- while (carry < carries.length && carries[carry][0] + carries[carry][2] <= position) carry += 1;
1061
- if (!(carry < carries.length && carries[carry][0] <= position && position < carries[carry][0] + carries[carry][2])) return "the skipped change writes structure it does not carry";
1062
- }
1063
- position += length;
1064
- }
1065
- }
1066
- for (const [at, from, length] of carries) {
1067
- const source = readTokens(index, from, from + length);
1068
- const written = copy.written.slice(at - copy.out, at - copy.out + length).tokens;
1069
- if (source.length !== written.length || source.some((token, position) => !tokensEqual(token, written[position]))) return "the skipped change copies its block with other tokens";
1070
- }
1071
- return null;
1072
- };
1073
- //#endregion
1074
272
  //#region src/core/change/carried-projection.ts
1075
273
  /** A projection the documents leave no place for. */
1076
274
  var CarriedProjectionError = class extends Error {
@@ -3113,428 +2311,14 @@ const carriedRunOf = ({ after, carry, output, repair }, root) => {
3113
2311
  };
3114
2312
  };
3115
2313
  //#endregion
3116
- //#region src/history/history-character-map.ts
3117
- const projections = /* @__PURE__ */ new WeakMap();
3118
- const project = (children) => {
3119
- const cached = projections.get(children);
3120
- if (cached) return cached;
3121
- const result = [];
3122
- for (const child of children) if (isTextNode(child)) {
3123
- const previous = result.at(-1);
3124
- if (previous && isTextNode(previous)) result[result.length - 1] = { text: previous.text + child.text };
3125
- else result.push({ text: child.text });
3126
- } else result.push({
3127
- ...nodeProps(child),
3128
- children: project(child.children)
3129
- });
3130
- projections.set(children, result);
3131
- return result;
3132
- };
3133
- const textHostAt = (index, path) => {
3134
- const parent = index.node(path.slice(0, -1));
3135
- if (isTextNode(parent)) throw new Error("A text host requires an element.");
3136
- let from = getDefined(path.at(-1));
3137
- while (from > 0 && isTextNode(parent.children[from - 1])) from -= 1;
3138
- const leaves = [];
3139
- for (let at = from; at < parent.children.length && isTextNode(parent.children[at]); at += 1) leaves.push(parent.children[at]);
3140
- countCoreWork("walkedSlots", getDefined(path.at(-1)) - from + leaves.length);
3141
- return {
3142
- path: [...path.slice(0, -1), from],
3143
- leaves,
3144
- text: leaves.map((leaf) => leaf.text).join("")
3145
- };
3146
- };
3147
- const projectedPath = (children, path) => {
3148
- const result = [];
3149
- let current = children;
3150
- for (const childIndex of path) {
3151
- let projected = -1;
3152
- let wasText = false;
3153
- for (let at = 0; at <= childIndex; at += 1) {
3154
- const text = isTextNode(current[at]);
3155
- if (!text || !wasText) projected += 1;
3156
- wasText = text;
3157
- }
3158
- result.push(projected);
3159
- const node = current[childIndex];
3160
- current = isTextNode(node) ? [] : node.children;
3161
- }
3162
- return result;
3163
- };
3164
- const actualPath = (children, path) => {
3165
- const result = [];
3166
- let current = children;
3167
- for (const childIndex of path) {
3168
- let projected = -1;
3169
- let wasText = false;
3170
- for (let at = 0; at < current.length; at += 1) {
3171
- const text = isTextNode(current[at]);
3172
- if (!text || !wasText) projected += 1;
3173
- if (projected === childIndex) {
3174
- result.push(at);
3175
- const node = current[at];
3176
- current = isTextNode(node) ? [] : node.children;
3177
- break;
3178
- }
3179
- wasText = text;
3180
- }
3181
- }
3182
- return result;
3183
- };
3184
- const retainedSections = (change) => {
3185
- const sections = [];
3186
- let beforePosition = 0;
3187
- let afterPosition = 0;
3188
- countCoreWork("sectionsWalked", change.data.length);
3189
- change.data.forEach((_, section) => {
3190
- const length = change.sections[section * 2];
3191
- const inserted = change.sections[section * 2 + 1];
3192
- if (inserted < 0 && length > 0) sections.push({
3193
- from: beforePosition,
3194
- to: beforePosition + length,
3195
- at: afterPosition
3196
- });
3197
- beforePosition += length;
3198
- afterPosition += inserted < 0 ? length : inserted;
3199
- });
3200
- return sections;
3201
- };
3202
- const retainedRanges = (sections, from, to) => {
3203
- let low = 0;
3204
- let high = sections.length;
3205
- while (low < high) {
3206
- const middle = low + high >> 1;
3207
- if (sections[middle].to <= from) low = middle + 1;
3208
- else high = middle;
3209
- }
3210
- const ranges = [];
3211
- for (let at = low; at < sections.length && sections[at].from < to; at += 1) {
3212
- const section = sections[at];
3213
- const start = Math.max(from, section.from);
3214
- const end = Math.min(to, section.to);
3215
- if (start < end) ranges.push({
3216
- from: start,
3217
- to: end,
3218
- at: section.at + start - section.from
3219
- });
3220
- }
3221
- return ranges;
3222
- };
3223
- /**
3224
- * Pair the letters of `before` with the letters `change` keeps in `after`.
3225
- * With `exact`, letters pair only through the tokens `change` retains and
3226
- * the parents it moves whole, never by comparing letter values. `letterAt`
3227
- * pairs the letters it knows instead, by token position.
3228
- */
3229
- const createCharacterCorrespondence = (before, after, change, root, exact = false, letterAt) => {
3230
- const source = valueRootIndex(before, root);
3231
- const target = valueRootIndex(after, root);
3232
- let joinedLines;
3233
- let relocations;
3234
- let retained;
3235
- const joinedChange = (line) => {
3236
- const rootChange = getInternalDocumentRootChange(change, root);
3237
- joinedLines ??= new Set(rootChange ? joinsOf(rootChange, source).flatMap((join) => [join.first.from, join.second.from]) : []);
3238
- return rootChange && joinedLines.has(line.from) ? rootChange : void 0;
3239
- };
3240
- const parents = /* @__PURE__ */ new Map();
3241
- const exactParent = (parentPath) => {
3242
- const rootChange = getInternalDocumentRootChange(change, root);
3243
- if (!rootChange) return null;
3244
- relocations ??= getDocumentChangeRelocations(change, root, source, target);
3245
- const relocation = relocations.find((move) => move.path.length <= parentPath.length && move.path.every((part, at) => part === parentPath[at]));
3246
- if (relocation) {
3247
- const nextPath = [...relocation.targetPath, ...parentPath.slice(relocation.path.length)];
3248
- const previous = source.node(parentPath);
3249
- const next = target.node(nextPath);
3250
- if (!isTextNode(previous) && next && !isTextNode(next)) {
3251
- const from = DocumentIndex.fromValue(project(previous.children));
3252
- const to = DocumentIndex.fromValue(project(next.children));
3253
- const kept = RootChange.betweenChangedBlocks(from, to);
3254
- if (kept.empty) return {
3255
- path: nextPath,
3256
- children: next.children,
3257
- before: from,
3258
- after: to,
3259
- change: kept
3260
- };
3261
- }
3262
- }
3263
- return { retained: rootChange };
3264
- };
3265
- const parentPair = (path) => {
3266
- const parentPath = path.slice(0, -1);
3267
- const key = parentPath.join(".");
3268
- if (parents.has(key)) return parents.get(key) ?? null;
3269
- if (exact) {
3270
- const moved = exactParent(parentPath);
3271
- if (moved) {
3272
- parents.set(key, moved);
3273
- return moved;
3274
- }
3275
- }
3276
- const range = source.nodeRange(parentPath);
3277
- const joined = joinedChange(range);
3278
- if (joined) {
3279
- parents.set(key, { retained: joined });
3280
- return { retained: joined };
3281
- }
3282
- const mapped = mapInternalDocumentChangePosition(change, root, range.from, 1, "after");
3283
- let nextPath = mapped === null ? void 0 : target.nodeStartingAt(mapped)?.path;
3284
- const rootChange = getInternalDocumentRootChange(change, root);
3285
- if (nextPath && rootChange) {
3286
- const close = mapInternalDocumentChangePosition(change, root, range.to - 1, 1, "after");
3287
- if (close !== null && close !== target.nodeRange(nextPath).to - 1) {
3288
- parents.set(key, { retained: rootChange });
3289
- return { retained: rootChange };
3290
- }
3291
- }
3292
- if (!nextPath) {
3293
- relocations ??= getDocumentChangeRelocations(change, root, source, target);
3294
- const relocation = relocations.find((move) => move.path.length <= parentPath.length && move.path.every((part, at) => part === parentPath[at]));
3295
- if (relocation) nextPath = [...relocation.targetPath, ...parentPath.slice(relocation.path.length)];
3296
- }
3297
- if (!nextPath && rootChange !== void 0) {
3298
- parents.set(key, { retained: rootChange });
3299
- return { retained: rootChange };
3300
- }
3301
- const previous = source.node(parentPath);
3302
- const next = nextPath ? target.node(nextPath) : null;
3303
- if (!nextPath || isTextNode(previous) || !next || isTextNode(next)) {
3304
- parents.set(key, null);
3305
- return null;
3306
- }
3307
- const from = DocumentIndex.fromValue(project(previous.children));
3308
- const to = DocumentIndex.fromValue(project(next.children));
3309
- const pair = {
3310
- path: nextPath,
3311
- children: next.children,
3312
- before: from,
3313
- after: to,
3314
- change: RootChange.betweenChangedBlocks(from, to)
3315
- };
3316
- parents.set(key, pair);
3317
- return pair;
3318
- };
3319
- const sourcePosition = (span, pair) => {
3320
- const parent = source.node(span.path.slice(0, -1));
3321
- if (isTextNode(parent)) throw new Error("A text host requires an element.");
3322
- return pair.before.nodeRange(projectedPath(parent.children, [getDefined(span.path.at(-1))])).from + 1;
3323
- };
3324
- const targetHosts = /* @__PURE__ */ new Map();
3325
- const targetHostOf = (path) => {
3326
- const parentPath = path.slice(0, -1);
3327
- const key = parentPath.join(".");
3328
- let hosts = targetHosts.get(key);
3329
- if (!hosts) {
3330
- const parent = target.node(parentPath);
3331
- if (isTextNode(parent)) throw new Error("A text host requires an element.");
3332
- const built = [];
3333
- let host = null;
3334
- let offset = 0;
3335
- countCoreWork("walkedSlots", parent.children.length);
3336
- parent.children.forEach((child, at) => {
3337
- if (!isTextNode(child)) {
3338
- host = null;
3339
- return;
3340
- }
3341
- if (!host) {
3342
- host = [...parentPath, at];
3343
- offset = 0;
3344
- }
3345
- built[at] = {
3346
- offset,
3347
- path: host
3348
- };
3349
- offset += child.text?.length ?? 0;
3350
- });
3351
- hosts = built;
3352
- targetHosts.set(key, hosts);
3353
- }
3354
- return getDefined(hosts[getDefined(path.at(-1))]);
3355
- };
3356
- const retainedFragments = (span, rootChange) => {
3357
- const host = textHostAt(source, span.path);
3358
- const fragments = [];
3359
- retained ??= retainedSections(rootChange);
3360
- const sections = retained;
3361
- let base = 0;
3362
- host.leaves.forEach((leaf, at) => {
3363
- const length = leaf.text?.length ?? 0;
3364
- const path = [...host.path.slice(0, -1), getDefined(host.path.at(-1)) + at];
3365
- const start = source.positionAt({
3366
- path,
3367
- offset: 0
3368
- }) - base;
3369
- const from = Math.max(span.from, base);
3370
- const to = Math.min(span.to, base + length);
3371
- base += length;
3372
- for (const range of retainedRanges(sections, start + from, start + to)) {
3373
- let mapped = range.at;
3374
- const end = range.at + range.to - range.from;
3375
- while (mapped < end) {
3376
- const entry = target.textAt(mapped);
3377
- if (!entry) break;
3378
- const stop = Math.min(end, entry.contentTo);
3379
- if (stop <= mapped) break;
3380
- const { offset, path: next } = targetHostOf(entry.path);
3381
- fragments.push({
3382
- from: range.from - start + mapped - range.at,
3383
- to: range.from - start + stop - range.at,
3384
- target: {
3385
- path: next,
3386
- from: offset + mapped - entry.contentFrom,
3387
- to: offset + stop - entry.contentFrom
3388
- }
3389
- });
3390
- mapped = stop;
3391
- }
3392
- }
3393
- });
3394
- return fragments;
3395
- };
3396
- const pairedFragments = (span) => {
3397
- const pair = parentPair(span.path);
3398
- if (!pair) return [];
3399
- if ("retained" in pair) return retainedFragments(span, pair.retained);
3400
- const start = sourcePosition(span, pair);
3401
- if (pair.change.empty) {
3402
- const entry = pair.after.textAt(start);
3403
- return entry ? [{
3404
- from: span.from,
3405
- to: span.to,
3406
- target: {
3407
- path: [...pair.path, ...actualPath(pair.children, entry.path)],
3408
- from: span.from,
3409
- to: span.to
3410
- }
3411
- }] : [];
3412
- }
3413
- const fragments = [];
3414
- let beforePosition = 0;
3415
- let afterPosition = 0;
3416
- pair.change.data.forEach((_, section) => {
3417
- const length = pair.change.sections[section * 2];
3418
- const inserted = pair.change.sections[section * 2 + 1];
3419
- if (inserted < 0) {
3420
- const from = Math.max(start + span.from, beforePosition);
3421
- const to = Math.min(start + span.to, beforePosition + length);
3422
- let mapped = afterPosition + from - beforePosition;
3423
- while (mapped < afterPosition + to - beforePosition) {
3424
- const entry = pair.after.textAt(mapped);
3425
- if (!entry) break;
3426
- const end = Math.min(afterPosition + to - beforePosition, entry.contentTo);
3427
- if (end <= mapped) break;
3428
- fragments.push({
3429
- from: beforePosition + mapped - afterPosition - start,
3430
- to: beforePosition + end - afterPosition - start,
3431
- target: {
3432
- path: [...pair.path, ...actualPath(pair.children, entry.path)],
3433
- from: mapped - entry.contentFrom,
3434
- to: end - entry.contentFrom
3435
- }
3436
- });
3437
- mapped = end;
3438
- }
3439
- }
3440
- beforePosition += length;
3441
- afterPosition += inserted < 0 ? length : inserted;
3442
- });
3443
- return fragments;
3444
- };
3445
- const letterFragments = (span, at) => {
3446
- const host = textHostAt(source, span.path);
3447
- const fragments = [];
3448
- let unpaired = null;
3449
- let offset = 0;
3450
- const flush = (to) => {
3451
- if (unpaired === null) return;
3452
- fragments.push(...pairedFragments({
3453
- ...span,
3454
- from: unpaired,
3455
- to
3456
- }));
3457
- unpaired = null;
3458
- };
3459
- host.leaves.forEach((leaf, index) => {
3460
- const length = leaf.text?.length ?? 0;
3461
- const start = source.positionAt({
3462
- offset: 0,
3463
- path: [...host.path.slice(0, -1), getDefined(host.path.at(-1)) + index]
3464
- });
3465
- for (let letter = Math.max(span.from, offset); letter < Math.min(span.to, offset + length); letter++) {
3466
- const landed = at(start + letter - offset);
3467
- if (landed === void 0) {
3468
- unpaired ??= letter;
3469
- continue;
3470
- }
3471
- flush(letter);
3472
- const entry = landed === null ? null : target.textAt(landed);
3473
- if (!entry || landed === null) continue;
3474
- const next = targetHostOf(entry.path);
3475
- const from = next.offset + landed - entry.contentFrom;
3476
- const last = fragments.at(-1);
3477
- if (last && last.to === letter && last.target.to === from && last.target.path.join(".") === next.path.join(".")) fragments[fragments.length - 1] = {
3478
- ...last,
3479
- target: {
3480
- ...last.target,
3481
- to: from + 1
3482
- },
3483
- to: letter + 1
3484
- };
3485
- else fragments.push({
3486
- from: letter,
3487
- target: {
3488
- from,
3489
- path: next.path,
3490
- to: from + 1
3491
- },
3492
- to: letter + 1
3493
- });
3494
- }
3495
- offset += length;
3496
- });
3497
- flush(span.to);
3498
- return fragments;
3499
- };
3500
- return {
3501
- fragments: (span) => letterAt ? letterFragments(span, letterAt) : pairedFragments(span),
3502
- point(point, association) {
3503
- const pair = parentPair(point.path);
3504
- if (!pair || "retained" in pair) return null;
3505
- const host = textHostAt(source, point.path);
3506
- let { offset } = point;
3507
- for (let at = getDefined(host.path.at(-1)); at < getDefined(point.path.at(-1)); at += 1) offset += source.node([...point.path.slice(0, -1), at]).text?.length ?? 0;
3508
- const position = sourcePosition({
3509
- ...host,
3510
- from: 0,
3511
- to: 0
3512
- }, pair) + offset;
3513
- const mapped = pair.change.empty ? position : pair.change.mapPos(position, association);
3514
- const projected = mapped === null ? null : pair.after.pointAt(mapped, association);
3515
- if (!projected) return null;
3516
- const path = [...pair.path, ...actualPath(pair.children, projected.path)];
3517
- const next = textHostAt(target, path);
3518
- let remaining = projected.offset;
3519
- for (let at = 0; at < next.leaves.length; at += 1) {
3520
- const length = next.leaves[at].text?.length ?? 0;
3521
- if (remaining < length || remaining === length && association < 0 || at === next.leaves.length - 1) return {
3522
- path: [...next.path.slice(0, -1), getDefined(next.path.at(-1)) + at],
3523
- offset: remaining
3524
- };
3525
- remaining -= length;
3526
- }
3527
- return null;
3528
- }
3529
- };
3530
- };
3531
- //#endregion
3532
- //#region src/history/history-replay.ts
2314
+ //#region src/history/history-replay-schema.ts
3533
2315
  const historyReplaySchemaOf = (editor) => {
3534
2316
  const schema = getEditorSchema(editor);
3535
2317
  return {
3536
- canonicalize: (properties, path, root, key, value) => schema.canonicalizeTextPropertiesAt(properties, [...path], root, key, value),
3537
2318
  allows: (key, path, root, value) => schema.isTextPropertyAllowedAt(key, [...path], root, value),
2319
+ canContain: (parent, child) => ElementApi.isElement(parent) && schema.canContain(parent, child),
2320
+ canonicalize: (properties, path, root, key, value) => schema.canonicalizeTextPropertiesAt(properties, [...path], root, key, value),
2321
+ isSetValued: schema.isSetValuedProperty,
3538
2322
  lines: {
3539
2323
  isInline: (node) => ElementApi.isElement(node) && schema.isInline(node),
3540
2324
  isVoid: (node) => ElementApi.isElement(node) && schema.isVoid(node),
@@ -3547,100 +2331,1417 @@ const historyReplaySchemaOf = (editor) => {
3547
2331
  ...schema.elementPropertiesForSplitAt(node, [...path], root, nodes),
3548
2332
  type: node.type
3549
2333
  } : {},
3550
- isSetValued: schema.isSetValuedProperty,
3551
2334
  repairCanonical: (before, change, after) => constructCanonicalDocumentChange(editor, after, change, {
3552
2335
  before,
3553
2336
  displacement: "none"
3554
- })
2337
+ }),
2338
+ validateChildren: (children, root, ancestors) => {
2339
+ try {
2340
+ schema.validateChildrenAt(children, root, ancestors);
2341
+ return true;
2342
+ } catch {
2343
+ return false;
2344
+ }
2345
+ }
3555
2346
  };
3556
2347
  };
3557
- const replayOver = (schema, edit, step, base, { anchor, carriesLift, readBack }) => transformInternalDocumentChange(edit, step, base, {
2348
+ const replayTransformOptions = (schema, rules) => ({
2349
+ isSetValued: schema.isSetValued,
3558
2350
  keepRecordWrites: true,
3559
2351
  replay: {
3560
- anchor,
3561
- carriesLift,
2352
+ anchor: rules.anchor,
2353
+ canContain: schema.canContain,
2354
+ carriesLift: rules.carriesLift,
3562
2355
  pieceProps: (element, parent, root, nodes) => schema.pieceProps(element, [...parent, 0], root, nodes),
3563
- readBack
2356
+ readBack: rules.readBack,
2357
+ validateChildren: schema.validateChildren
3564
2358
  }
3565
2359
  });
3566
- const rewriteSpans = (value, spans, properties) => {
3567
- let result = value;
3568
- for (const [root, ranges] of spans) {
3569
- const index = valueRootIndex(result, root);
3570
- const groups = /* @__PURE__ */ new Map();
3571
- for (const span of ranges) {
3572
- const key = span.path.join(".");
3573
- const group = groups.get(key) ?? [];
3574
- group.push(span);
3575
- groups.set(key, group);
3576
- }
3577
- const replacements = /* @__PURE__ */ new Map();
3578
- for (const group of groups.values()) {
3579
- const host = textHostAt(index, group[0].path);
3580
- const children = [];
3581
- let position = 0;
3582
- for (let at = 0; at < host.leaves.length; at += 1) {
3583
- const leaf = host.leaves[at];
3584
- if (!isTextNode(leaf)) continue;
3585
- const edges = [.../* @__PURE__ */ new Set([
3586
- position,
3587
- position + leaf.text.length,
3588
- ...group.flatMap((span) => [span.from, span.to]).filter((edge) => edge > position && edge < position + leaf.text.length)
3589
- ])].sort((a, b) => a - b);
3590
- for (let edge = 1; edge < edges.length; edge += 1) {
3591
- const from = edges[edge - 1];
3592
- const to = edges[edge];
3593
- let props = nodeProps(leaf);
3594
- for (const span of group) if (span.from <= from && to <= span.to) props = properties(span, props, [...host.path.slice(0, -1), getDefined(host.path.at(-1)) + at], root);
3595
- const text = leaf.text.slice(from - position, to - position);
3596
- const previous = children.at(-1);
3597
- if (previous && isTextNode(previous) && jsonEqual(nodeProps(previous), props)) children[children.length - 1] = {
3598
- ...props,
3599
- text: previous.text + text
2360
+ //#endregion
2361
+ //#region src/history/v4-history-rebase.ts
2362
+ const collectElementIds = (nodes, into) => {
2363
+ for (const node of nodes) {
2364
+ if (!isElementNode(node)) continue;
2365
+ if (typeof node.id !== "string" || node.id.length === 0) return false;
2366
+ into.add(node.id);
2367
+ if (!collectElementIds(node.children, into)) return false;
2368
+ }
2369
+ return true;
2370
+ };
2371
+ const collectLiveElementIds = (value) => {
2372
+ const ids = /* @__PURE__ */ new Set();
2373
+ if (!collectElementIds(value.children, ids)) return null;
2374
+ if (value.roots) {
2375
+ for (const root of visitRootNames(value.roots)) if (!collectElementIds(value.roots[root], ids)) return null;
2376
+ }
2377
+ return ids;
2378
+ };
2379
+ const collectSubtreeIds = (node, into) => {
2380
+ if (!isElementNode(node)) return;
2381
+ if (typeof node.id === "string" && node.id.length > 0) into.add(node.id);
2382
+ for (const child of node.children) collectSubtreeIds(child, into);
2383
+ };
2384
+ const indexElements = (value) => {
2385
+ const map = /* @__PURE__ */ new Map();
2386
+ const walk = (nodes) => {
2387
+ for (const node of nodes) {
2388
+ if (!isElementNode(node)) continue;
2389
+ if (typeof node.id === "string" && node.id.length > 0) map.set(node.id, node);
2390
+ walk(node.children);
2391
+ }
2392
+ };
2393
+ walk(value.children);
2394
+ if (value.roots) for (const root of visitRootNames(value.roots)) walk(value.roots[root]);
2395
+ return map;
2396
+ };
2397
+ const stepMutatedIds = (step) => {
2398
+ switch (step.op) {
2399
+ case "insert_text":
2400
+ case "delete_text":
2401
+ case "format_text":
2402
+ case "wrap_inline": return [step.target];
2403
+ case "unwrap_inline": return [step.parent, step.id];
2404
+ case "set_props":
2405
+ case "split_node": return [step.id];
2406
+ case "join_nodes": return [step.target, step.source];
2407
+ case "insert_node": return "id" in step.to ? [step.to.id] : [];
2408
+ default: return [];
2409
+ }
2410
+ };
2411
+ const filterUntouchedMovesForRemovedIds = (base, stepDocSteps, editDocSteps) => {
2412
+ const removedIds = /* @__PURE__ */ new Set();
2413
+ for (const step of stepDocSteps) if (step.op === "remove_node") removedIds.add(step.id);
2414
+ if (removedIds.size === 0) return editDocSteps;
2415
+ const movedRemovedIds = /* @__PURE__ */ new Set();
2416
+ for (const step of editDocSteps) if (step.op === "move_node" && removedIds.has(step.id)) movedRemovedIds.add(step.id);
2417
+ if (movedRemovedIds.size === 0) return editDocSteps;
2418
+ const byId = indexElements(base);
2419
+ const droppable = /* @__PURE__ */ new Set();
2420
+ for (const movedId of movedRemovedIds) {
2421
+ const node = byId.get(movedId);
2422
+ const subtree = /* @__PURE__ */ new Set([movedId]);
2423
+ if (node) collectSubtreeIds(node, subtree);
2424
+ let blocked = false;
2425
+ for (const step of stepDocSteps) if (step.op === "move_node" && step.id !== movedId && subtree.has(step.id) && !removedIds.has(step.id)) {
2426
+ blocked = true;
2427
+ break;
2428
+ }
2429
+ if (blocked) continue;
2430
+ for (const step of editDocSteps) {
2431
+ if (step.op === "move_node" && step.id === movedId) continue;
2432
+ for (const mutated of stepMutatedIds(step)) if (subtree.has(mutated)) {
2433
+ blocked = true;
2434
+ break;
2435
+ }
2436
+ if (blocked) break;
2437
+ if (step.op === "move_node" && "id" in step.to && subtree.has(step.to.id)) {
2438
+ blocked = true;
2439
+ break;
2440
+ }
2441
+ }
2442
+ if (!blocked) droppable.add(movedId);
2443
+ }
2444
+ if (droppable.size === 0) return editDocSteps;
2445
+ return editDocSteps.filter((step) => !(step.op === "move_node" && droppable.has(step.id)));
2446
+ };
2447
+ const rebindChangeNodeKeys = (target, source) => {
2448
+ const elementKeys = /* @__PURE__ */ new Map();
2449
+ const textKeysByParent = /* @__PURE__ */ new Map();
2450
+ for (const [, rootChange] of getInternalDocumentChangeEntries(source)) rootChange.collectInsertedNodeKeys(elementKeys, textKeysByParent);
2451
+ if (elementKeys.size === 0 && textKeysByParent.size === 0) return target;
2452
+ let result = target;
2453
+ for (const [root, rootChange] of getInternalDocumentChangeEntries(target)) {
2454
+ const rebound = rootChange.applyNodeKeysById(elementKeys, textKeysByParent);
2455
+ if (rebound !== rootChange) result = withInternalDocumentRootChange(result, root, rebound);
2456
+ }
2457
+ if (result !== target) copyV4StepsMetadata(target, result);
2458
+ return result;
2459
+ };
2460
+ const hasRootLifecycleConflict = (edit, step) => {
2461
+ if (edit.createRoots.size === 0 && edit.deleteRoots.size === 0 && step.createRoots.size === 0 && step.deleteRoots.size === 0) return false;
2462
+ const editRoots = /* @__PURE__ */ new Set([
2463
+ ...edit.createRoots,
2464
+ ...edit.deleteRoots,
2465
+ ...getInternalDocumentChangeRootKeys(edit)
2466
+ ]);
2467
+ const stepRoots = /* @__PURE__ */ new Set([
2468
+ ...step.createRoots,
2469
+ ...step.deleteRoots,
2470
+ ...getInternalDocumentChangeRootKeys(step)
2471
+ ]);
2472
+ for (const root of [...edit.createRoots, ...edit.deleteRoots]) if (stepRoots.has(root)) return true;
2473
+ for (const root of [...step.createRoots, ...step.deleteRoots]) if (editRoots.has(root)) return true;
2474
+ return false;
2475
+ };
2476
+ const wrapsAcrossPeerSplit = (editDocSteps, stepDocSteps) => {
2477
+ const splitIds = /* @__PURE__ */ new Set();
2478
+ for (const step of editDocSteps) if (step.op === "split_node") splitIds.add(step.id);
2479
+ if (splitIds.size === 0) return false;
2480
+ const insertedWrappers = /* @__PURE__ */ new Set();
2481
+ for (const step of stepDocSteps) if (step.op === "insert_node" && "id" in step.to && splitIds.has(step.to.id) && typeof step.node.id === "string") insertedWrappers.add(step.node.id);
2482
+ if (insertedWrappers.size === 0) return false;
2483
+ let movedIntoWrapper = 0;
2484
+ for (const step of stepDocSteps) if (step.op === "move_node" && "id" in step.to && insertedWrappers.has(step.to.id)) movedIntoWrapper += 1;
2485
+ return movedIntoWrapper >= 2;
2486
+ };
2487
+ const isAuthoredMarkKey = (key) => key.startsWith("authored");
2488
+ const isUserFormatStep = (step) => {
2489
+ if (step.op !== "format_text") return false;
2490
+ if (step.set && Object.keys(step.set).some(isAuthoredMarkKey)) return false;
2491
+ if (step.unset && step.unset.some(isAuthoredMarkKey)) return false;
2492
+ if (step.add && Object.keys(step.add).some(isAuthoredMarkKey)) return false;
2493
+ if (step.remove && Object.keys(step.remove).some(isAuthoredMarkKey)) return false;
2494
+ return true;
2495
+ };
2496
+ const isPureV4FormatChange = (base, change, after, isSetValued, allowAuthored = false) => {
2497
+ if (change.empty) return false;
2498
+ let steps = getV4Steps(change);
2499
+ if (!steps) try {
2500
+ steps = extractV4Between(base, after, { isSetValued });
2501
+ } catch {
2502
+ return false;
2503
+ }
2504
+ return steps.length > 0 && steps.every((step) => allowAuthored ? step.op === "format_text" : isUserFormatStep(step));
2505
+ };
2506
+ const tryRelocatedTextDeleteRebase = (base, editDocSteps, stepDocSteps, editAfter, stepAfter) => {
2507
+ let targetDel = null;
2508
+ for (const s of stepDocSteps) if (s.op === "delete_text") {
2509
+ if (targetDel !== null) return null;
2510
+ targetDel = s;
2511
+ } else if (s.op !== "format_text") return null;
2512
+ if (!targetDel) return null;
2513
+ for (const s of stepDocSteps) if (s.op === "format_text" && (s.target !== targetDel.target || s.offset < targetDel.offset || s.offset + s.length > targetDel.offset + targetDel.length)) return null;
2514
+ const delIdx = editDocSteps.findIndex((s) => s.op === "delete_text" && s.target === targetDel.target && s.offset === targetDel.offset && s.length === targetDel.length);
2515
+ if (delIdx === -1) return null;
2516
+ const baseHost = indexElements(base).get(targetDel.target);
2517
+ if (!baseHost || !isTextBearingElement(baseHost)) return null;
2518
+ const units = toV4TextStream(baseHost.children).units.slice(targetDel.offset, targetDel.offset + targetDel.length);
2519
+ if (units.length !== targetDel.length || units.some((u) => u.kind !== "char")) return null;
2520
+ const firstMarks = units[0]?.kind === "char" ? units[0].marks : {};
2521
+ if (!units.every((u) => u.kind === "char" && jsonEqual(u.marks, firstMarks))) return null;
2522
+ const deletedText = units.map((u) => u.kind === "char" ? u.ch : "").join("");
2523
+ let insIdx = editDocSteps.findIndex((s, i) => i !== delIdx && s.op === "insert_text" && s.text === deletedText && jsonEqual(s.marks ?? {}, firstMarks) && (s.target !== targetDel.target || s.offset !== targetDel.offset));
2524
+ let companionFmtIdx = -1;
2525
+ if (insIdx === -1) for (let i = 0; i < editDocSteps.length; i += 1) {
2526
+ if (i === delIdx) continue;
2527
+ const s = editDocSteps[i];
2528
+ if (s?.op !== "insert_text" || s.text !== deletedText || s.target === targetDel.target && s.offset === targetDel.offset) continue;
2529
+ const nextStep = editDocSteps[i + 1];
2530
+ if (nextStep?.op === "format_text" && nextStep.target === s.target && nextStep.offset === s.offset && nextStep.length === s.text.length && jsonEqual({
2531
+ ...s.marks,
2532
+ ...nextStep.set
2533
+ }, firstMarks)) {
2534
+ insIdx = i;
2535
+ companionFmtIdx = i + 1;
2536
+ break;
2537
+ }
2538
+ }
2539
+ if (insIdx === -1) return null;
2540
+ const insStep = editDocSteps[insIdx];
2541
+ if (insStep?.op !== "insert_text") return null;
2542
+ const destTarget = insStep.target;
2543
+ let destOffset = insStep.offset;
2544
+ for (let i = Math.max(insIdx, companionFmtIdx) + 1; i < editDocSteps.length; i += 1) {
2545
+ const later = editDocSteps[i];
2546
+ if (!later) continue;
2547
+ if (later.op === "insert_text" && later.target === destTarget) {
2548
+ if (later.offset <= destOffset) destOffset += later.text.length;
2549
+ } else if (later.op === "delete_text" && later.target === destTarget) {
2550
+ if (later.offset + later.length <= destOffset) destOffset -= later.length;
2551
+ else if (later.offset < destOffset + targetDel.length) return null;
2552
+ } else if (later.op === "split_node" || later.op === "join_nodes" || later.op === "remove_node") return null;
2553
+ }
2554
+ const nextStepDoc = [{
2555
+ length: targetDel.length,
2556
+ offset: destOffset,
2557
+ op: "delete_text",
2558
+ target: destTarget
2559
+ }];
2560
+ const nextEditDoc = editDocSteps.filter((_, i) => i !== delIdx && i !== insIdx && i !== companionFmtIdx);
2561
+ try {
2562
+ const viaEdit = applyV4Steps(editAfter, nextStepDoc);
2563
+ const viaStep = applyV4Steps(stepAfter, nextEditDoc);
2564
+ if (!jsonEqual(viaEdit.children, viaStep.children) || !jsonEqual(viaEdit.roots ?? {}, viaStep.roots ?? {})) return null;
2565
+ return {
2566
+ editDoc: nextEditDoc,
2567
+ stepDoc: nextStepDoc
2568
+ };
2569
+ } catch {
2570
+ return null;
2571
+ }
2572
+ };
2573
+ const rightAfterPlace = (doc, targetId, sourceId) => {
2574
+ const targetLoc = locateElementById(doc, targetId);
2575
+ const sourceLoc = locateElementById(doc, sourceId);
2576
+ if (!targetLoc || !sourceLoc || targetLoc.root !== sourceLoc.root) return null;
2577
+ const targetParentPath = targetLoc.path.slice(0, -1);
2578
+ const sourceParentPath = sourceLoc.path.slice(0, -1);
2579
+ const targetIdx = targetLoc.path.at(-1);
2580
+ const sourceIdx = sourceLoc.path.at(-1);
2581
+ if (targetIdx === void 0 || sourceIdx === void 0) return null;
2582
+ const sameParent = targetParentPath.length === sourceParentPath.length && targetParentPath.every((n, i) => n === sourceParentPath[i]);
2583
+ if (sameParent && sourceIdx === targetIdx + 1) return null;
2584
+ const destIndex = sameParent && sourceIdx < targetIdx ? targetIdx : targetIdx + 1;
2585
+ if (targetParentPath.length === 0) return {
2586
+ index: destIndex,
2587
+ root: targetLoc.root
2588
+ };
2589
+ const parentNode = valueRootIndex(doc, targetLoc.root).node(targetParentPath);
2590
+ if (!isElementNode(parentNode) || typeof parentNode.id !== "string" || parentNode.id.length === 0) return null;
2591
+ return {
2592
+ id: parentNode.id,
2593
+ index: destIndex
2594
+ };
2595
+ };
2596
+ const elementParentIdIn = (doc, id) => {
2597
+ const loc = locateElementById(doc, id);
2598
+ if (!loc || loc.path.length <= 1) return null;
2599
+ const parent = valueRootIndex(doc, loc.root).node(loc.path.slice(0, -1));
2600
+ return isElementNode(parent) && typeof parent.id === "string" ? parent.id : null;
2601
+ };
2602
+ const isEmptyTextSubtree = (node) => node.children.every((child) => isElementNode(child) ? isEmptyTextSubtree(child) : typeof child.text === "string" && child.text.length === 0);
2603
+ const tryRelocatedRestoreOnDeletedTarget = (base, editDocSteps, editAfter, stepDocSteps, stepAfter, isSetValued) => {
2604
+ const editRemoved = /* @__PURE__ */ new Set();
2605
+ for (const s of editDocSteps) if (s.op === "remove_node") editRemoved.add(s.id);
2606
+ else if (s.op !== "move_node") return null;
2607
+ if (editRemoved.size !== 1) return null;
2608
+ const [deletedTargetId] = editRemoved;
2609
+ if (!deletedTargetId) return null;
2610
+ if (!stepDocSteps.every((s) => s.op === "remove_node" || s.op === "insert_text" || s.op === "delete_text")) return null;
2611
+ const baseById = indexElements(base);
2612
+ const targetInStepAfter = indexElements(stepAfter).get(deletedTargetId);
2613
+ if (!targetInStepAfter || !isTextBearingElement(targetInStepAfter)) return null;
2614
+ const desiredUnits = toV4TextStream(targetInStepAfter.children).units;
2615
+ if (desiredUnits.length === 0 || !desiredUnits.every((u) => u.kind === "char")) return null;
2616
+ const desiredText = desiredUnits.map((u) => u.kind === "char" ? u.ch : "").join("");
2617
+ const afterById = indexElements(editAfter);
2618
+ let carrierId = null;
2619
+ let carrierText = "";
2620
+ let matchIdx = -1;
2621
+ for (const s of stepDocSteps) {
2622
+ if (s.op !== "remove_node") continue;
2623
+ const node = afterById.get(s.id);
2624
+ if (!node || !isTextBearingElement(node)) continue;
2625
+ const { units } = toV4TextStream(node.children);
2626
+ if (!units.every((u) => u.kind === "char")) continue;
2627
+ const text = units.map((u) => u.kind === "char" ? u.ch : "").join("");
2628
+ const idx = text.indexOf(desiredText);
2629
+ if (idx !== -1 && text.length > desiredText.length) {
2630
+ if (carrierId !== null) return null;
2631
+ carrierId = s.id;
2632
+ carrierText = text;
2633
+ matchIdx = idx;
2634
+ }
2635
+ }
2636
+ if (!carrierId || matchIdx === -1) return null;
2637
+ const baseTarget = baseById.get(deletedTargetId);
2638
+ if (!baseTarget || !isTextBearingElement(baseTarget)) return null;
2639
+ const stepRemoveCount = stepDocSteps.filter((s) => s.op === "remove_node").length;
2640
+ const stepEditsCarrier = stepDocSteps.some((s) => (s.op === "delete_text" || s.op === "insert_text") && s.target === carrierId);
2641
+ if (stepRemoveCount < 2 && !stepEditsCarrier) return null;
2642
+ const nextStepDoc = [];
2643
+ for (const s of stepDocSteps) if (s.op === "remove_node") {
2644
+ if (s.id === carrierId) {
2645
+ const suffixStart = matchIdx + desiredText.length;
2646
+ if (suffixStart < carrierText.length) nextStepDoc.push({
2647
+ length: carrierText.length - suffixStart,
2648
+ offset: suffixStart,
2649
+ op: "delete_text",
2650
+ target: carrierId
2651
+ });
2652
+ if (matchIdx > 0) nextStepDoc.push({
2653
+ length: matchIdx,
2654
+ offset: 0,
2655
+ op: "delete_text",
2656
+ target: carrierId
2657
+ });
2658
+ } else if (afterById.has(s.id)) nextStepDoc.push(s);
2659
+ } else if (s.target !== deletedTargetId && s.target !== carrierId && afterById.has(s.target)) nextStepDoc.push(s);
2660
+ try {
2661
+ const viaEdit = applyV4Steps(editAfter, nextStepDoc);
2662
+ const nextEditDoc = extractV4Between(stepAfter, viaEdit, { isSetValued });
2663
+ const viaStep = applyV4Steps(stepAfter, nextEditDoc);
2664
+ if (!jsonEqual(viaEdit.children, viaStep.children) || !jsonEqual(viaEdit.roots ?? {}, viaStep.roots ?? {})) return null;
2665
+ return {
2666
+ editDoc: nextEditDoc,
2667
+ stepDoc: nextStepDoc
2668
+ };
2669
+ } catch {
2670
+ return null;
2671
+ }
2672
+ };
2673
+ const tryHistoryEscalationRebase = (reason, base, editDocSteps, editAfter, stepDocSteps, stepAfter, isSetValued, canRemoveEmptyParent = false) => {
2674
+ if (reason !== "not-adjacent" && reason !== "move-conflict" && reason !== "target-deleted" && reason !== "dropped-moves") return null;
2675
+ const baseById = indexElements(base);
2676
+ const editInsertedTextTargets = /* @__PURE__ */ new Set();
2677
+ const editRemovedIds = /* @__PURE__ */ new Set();
2678
+ const editInsertedNonEmptyNodeIds = /* @__PURE__ */ new Set();
2679
+ for (const s of editDocSteps) if (s.op === "insert_text") editInsertedTextTargets.add(s.target);
2680
+ else if (s.op === "remove_node") {
2681
+ editRemovedIds.add(s.id);
2682
+ const removedNode = baseById.get(s.id);
2683
+ if (removedNode) collectSubtreeIds(removedNode, editRemovedIds);
2684
+ } else if (s.op === "insert_node" && !isEmptyTextSubtree(s.node) && typeof s.node.id === "string") editInsertedNonEmptyNodeIds.add(s.node.id);
2685
+ const stepRemovedIds = /* @__PURE__ */ new Set();
2686
+ for (const s of stepDocSteps) if (s.op === "remove_node") stepRemovedIds.add(s.id);
2687
+ const hasUnwrapConflict = !stepDocSteps.some((s) => s.op === "insert_node") && stepDocSteps.some((s) => {
2688
+ if (s.op !== "move_node") return false;
2689
+ const oldParent = elementParentIdIn(base, s.id);
2690
+ return oldParent !== null && stepRemovedIds.has(oldParent) && elementParentIdIn(editAfter, s.id) !== oldParent;
2691
+ });
2692
+ const simpleEdit = editDocSteps.every((s) => s.op === "remove_node" || s.op === "move_node" || s.op === "insert_text" || s.op === "delete_text" || s.op === "format_text" || s.op === "set_props");
2693
+ const preservePeerTextInRemoved = (reason === "target-deleted" || reason === "not-adjacent") && editInsertedTextTargets.size > 0 && simpleEdit && stepDocSteps.some((s) => s.op === "remove_node" && editInsertedTextTargets.has(s.id)) && stepDocSteps.every((s) => s.op === "join_nodes" || s.op === "remove_node" || s.op === "delete_text" || s.op === "format_text");
2694
+ if (reason === "target-deleted") {
2695
+ const pureRemoteDelete = editDocSteps.length > 0 && editDocSteps.every((s) => s.op === "remove_node") && stepDocSteps.some((s) => s.op === "remove_node" && editRemovedIds.has(s.id)) && stepDocSteps.every((s) => s.op === "remove_node" || s.op === "insert_text" || s.op === "delete_text" || s.op === "format_text");
2696
+ const pureRemovalOrDeleteStep = editRemovedIds.size > 0 && simpleEdit && stepDocSteps.every((s) => {
2697
+ if (s.op === "join_nodes" || s.op === "remove_node" || s.op === "delete_text" || s.op === "format_text" || s.op === "set_props") return true;
2698
+ if (s.op === "move_node") {
2699
+ const oldParent = elementParentIdIn(base, s.id);
2700
+ return oldParent !== null && stepRemovedIds.has(oldParent);
2701
+ }
2702
+ return false;
2703
+ });
2704
+ const editOnlyMovesRemovedWrappers = editDocSteps.length > 0 && editDocSteps.every((s) => s.op === "move_node" && stepRemovedIds.has(s.id)) && !stepDocSteps.some((s) => s.op === "insert_node");
2705
+ if (!pureRemoteDelete && !pureRemovalOrDeleteStep && !editOnlyMovesRemovedWrappers && !preservePeerTextInRemoved && !hasUnwrapConflict) return null;
2706
+ }
2707
+ if (reason === "move-conflict" && !hasUnwrapConflict) return null;
2708
+ if (reason === "not-adjacent") {
2709
+ if (!stepDocSteps.some((s) => s.op === "join_nodes")) return null;
2710
+ if (editDocSteps.some((s) => s.op !== "move_node" && s.op !== "remove_node" && s.op !== "insert_text" && s.op !== "delete_text" && s.op !== "format_text" && s.op !== "set_props")) return null;
2711
+ }
2712
+ const afterById = indexElements(editAfter);
2713
+ for (const id of stepRemovedIds) {
2714
+ const afterNode = afterById.get(id);
2715
+ if (!afterNode) continue;
2716
+ const baseNode = baseById.get(id);
2717
+ const baseSub = /* @__PURE__ */ new Set();
2718
+ if (baseNode) collectSubtreeIds(baseNode, baseSub);
2719
+ const afterSub = /* @__PURE__ */ new Set();
2720
+ collectSubtreeIds(afterNode, afterSub);
2721
+ for (const subId of afterSub) {
2722
+ if (editInsertedTextTargets.has(subId) && !(preservePeerTextInRemoved && subId === id) || editInsertedNonEmptyNodeIds.has(subId)) return null;
2723
+ if (!baseSub.has(subId) && !stepRemovedIds.has(subId)) {
2724
+ const intruder = afterById.get(subId);
2725
+ if (intruder && !isEmptyTextSubtree(intruder)) return null;
2726
+ }
2727
+ }
2728
+ }
2729
+ let cur = editAfter;
2730
+ const nextStepDoc = [];
2731
+ const removedByStep = /* @__PURE__ */ new Set();
2732
+ const skippedJoinedSourceLen = /* @__PURE__ */ new Map();
2733
+ try {
2734
+ for (const s of stepDocSteps) {
2735
+ const liveIds = indexElements(cur);
2736
+ if (s.op === "move_node") {
2737
+ const oldParent = elementParentIdIn(base, s.id);
2738
+ if (oldParent && stepRemovedIds.has(oldParent) && elementParentIdIn(cur, s.id) !== oldParent) continue;
2739
+ if (!liveIds.has(s.id)) {
2740
+ if (editRemovedIds.has(s.id)) continue;
2741
+ return null;
2742
+ }
2743
+ cur = applyV4Steps(cur, [s]);
2744
+ nextStepDoc.push(s);
2745
+ continue;
2746
+ }
2747
+ if (s.op === "join_nodes") {
2748
+ const hasTarget = liveIds.has(s.target);
2749
+ const hasSource = liveIds.has(s.source);
2750
+ if (!hasTarget || !hasSource) {
2751
+ if (!hasSource && editRemovedIds.has(s.source)) {
2752
+ const src = baseById.get(s.source);
2753
+ if (src && isEmptyTextSubtree(src)) continue;
2754
+ if (src && isTextBearingElement(src) && hasTarget) {
2755
+ const srcLen = elementStreamLength(src);
2756
+ const targetNode = liveIds.get(s.target);
2757
+ const targetLen = targetNode && isTextBearingElement(targetNode) ? elementStreamLength(targetNode) : -1;
2758
+ if (stepDocSteps.some((other) => other.op === "delete_text" && other.target === s.target && other.offset === targetLen && other.length === srcLen)) {
2759
+ skippedJoinedSourceLen.set(s.target, srcLen);
2760
+ continue;
2761
+ }
2762
+ }
2763
+ }
2764
+ if (stepRemovedIds.has(s.target)) {
2765
+ if (!hasTarget && editRemovedIds.has(s.target) && hasSource) {
2766
+ const sourceNode = liveIds.get(s.source);
2767
+ const sourceSub = /* @__PURE__ */ new Set();
2768
+ if (sourceNode) collectSubtreeIds(sourceNode, sourceSub);
2769
+ for (const subId of sourceSub) if (editInsertedTextTargets.has(subId) || editInsertedNonEmptyNodeIds.has(subId)) return null;
2770
+ const rem = {
2771
+ id: s.source,
2772
+ op: "remove_node"
2773
+ };
2774
+ cur = applyV4Steps(cur, [rem]);
2775
+ nextStepDoc.push(rem);
2776
+ for (const subId of sourceSub) removedByStep.add(subId);
2777
+ continue;
2778
+ }
2779
+ if (!hasSource && editRemovedIds.has(s.source)) continue;
2780
+ }
2781
+ return null;
2782
+ }
2783
+ const moveTo = rightAfterPlace(cur, s.target, s.source);
2784
+ if (moveTo) {
2785
+ const srcParentId = elementParentIdIn(cur, s.source);
2786
+ const dstParentId = "id" in moveTo ? moveTo.id : null;
2787
+ const emptiesSrcParent = srcParentId !== null && srcParentId !== dstParentId && (liveIds.get(srcParentId)?.children.length ?? 0) === 1;
2788
+ const moveStep = {
2789
+ id: s.source,
2790
+ op: "move_node",
2791
+ to: moveTo
3600
2792
  };
3601
- else children.push({
3602
- ...props,
3603
- text
3604
- });
2793
+ cur = applyV4Steps(cur, [moveStep]);
2794
+ nextStepDoc.push(moveStep);
2795
+ cur = applyV4Steps(cur, [s]);
2796
+ nextStepDoc.push(s);
2797
+ if (emptiesSrcParent && srcParentId) {
2798
+ if (!canRemoveEmptyParent) return null;
2799
+ const remEmpty = {
2800
+ id: srcParentId,
2801
+ op: "remove_node"
2802
+ };
2803
+ cur = applyV4Steps(cur, [remEmpty]);
2804
+ nextStepDoc.push(remEmpty);
2805
+ }
2806
+ continue;
2807
+ }
2808
+ cur = applyV4Steps(cur, [s]);
2809
+ nextStepDoc.push(s);
2810
+ continue;
2811
+ }
2812
+ if (s.op === "remove_node") {
2813
+ if (!liveIds.has(s.id)) {
2814
+ if (editRemovedIds.has(s.id) || removedByStep.has(s.id)) continue;
2815
+ return null;
2816
+ }
2817
+ if (preservePeerTextInRemoved && editInsertedTextTargets.has(s.id)) {
2818
+ const baseNode = baseById.get(s.id);
2819
+ if (!baseNode || !isTextBearingElement(baseNode)) return null;
2820
+ const baseLen = elementStreamLength(baseNode);
2821
+ if (baseLen > 0) {
2822
+ const textDel = {
2823
+ length: baseLen,
2824
+ offset: 0,
2825
+ op: "delete_text",
2826
+ target: s.id
2827
+ };
2828
+ const rebased = rebaseV4Changes(base, editDocSteps.filter((es) => (es.op === "insert_text" || es.op === "delete_text" || es.op === "format_text") && es.target === s.id), [textDel]);
2829
+ if (!rebased.ok) return null;
2830
+ for (const piece of rebased.bPrime) {
2831
+ cur = applyV4Steps(cur, [piece]);
2832
+ nextStepDoc.push(piece);
2833
+ }
2834
+ } else {
2835
+ const loc = locateElementById(cur, s.id);
2836
+ if (!loc) return null;
2837
+ const parentNodes = loc.path.length === 1 ? valueRoot(cur, loc.root) : (() => {
2838
+ const p = valueRootIndex(cur, loc.root).node(loc.path.slice(0, -1));
2839
+ return isElementNode(p) ? p.children : [];
2840
+ })();
2841
+ const myIdx = loc.path.at(-1) ?? -1;
2842
+ const sibling = parentNodes.find((child, idx) => idx !== myIdx && isElementNode(child) && typeof child.id === "string" && !stepRemovedIds.has(child.id) && isTextBearingElement(child));
2843
+ if (!sibling || !isElementNode(sibling) || typeof sibling.id !== "string") return null;
2844
+ const siblingId = sibling.id;
2845
+ const joinMove = rightAfterPlace(cur, siblingId, s.id);
2846
+ if (joinMove) {
2847
+ const mv = {
2848
+ id: s.id,
2849
+ op: "move_node",
2850
+ to: joinMove
2851
+ };
2852
+ cur = applyV4Steps(cur, [mv]);
2853
+ nextStepDoc.push(mv);
2854
+ }
2855
+ const jn = {
2856
+ op: "join_nodes",
2857
+ source: s.id,
2858
+ target: siblingId
2859
+ };
2860
+ cur = applyV4Steps(cur, [jn]);
2861
+ nextStepDoc.push(jn);
2862
+ }
2863
+ continue;
2864
+ }
2865
+ const remNode = liveIds.get(s.id);
2866
+ const remSub = /* @__PURE__ */ new Set();
2867
+ if (remNode) collectSubtreeIds(remNode, remSub);
2868
+ cur = applyV4Steps(cur, [s]);
2869
+ nextStepDoc.push(s);
2870
+ for (const subId of remSub) removedByStep.add(subId);
2871
+ continue;
2872
+ }
2873
+ if (s.op === "delete_text" && skippedJoinedSourceLen.get(s.target) === s.length) {
2874
+ const targetNode = liveIds.get(s.target);
2875
+ if (targetNode && isTextBearingElement(targetNode) && s.offset === elementStreamLength(targetNode)) {
2876
+ skippedJoinedSourceLen.delete(s.target);
2877
+ continue;
2878
+ }
2879
+ }
2880
+ if ((s.op === "insert_text" || s.op === "delete_text" || s.op === "format_text" || s.op === "wrap_inline") && !liveIds.has(s.target)) {
2881
+ if (editRemovedIds.has(s.target)) continue;
2882
+ return null;
2883
+ }
2884
+ if (s.op === "unwrap_inline" && (!liveIds.has(s.id) || !liveIds.has(s.parent))) {
2885
+ if (editRemovedIds.has(s.id) || editRemovedIds.has(s.parent)) continue;
2886
+ return null;
2887
+ }
2888
+ if ((s.op === "set_props" || s.op === "split_node") && !liveIds.has(s.id)) {
2889
+ if (editRemovedIds.has(s.id)) continue;
2890
+ return null;
2891
+ }
2892
+ cur = applyV4Steps(cur, [s]);
2893
+ nextStepDoc.push(s);
2894
+ }
2895
+ const nextEditDoc = extractV4Between(stepAfter, cur, { isSetValued });
2896
+ const viaStep = applyV4Steps(stepAfter, nextEditDoc);
2897
+ if (!jsonEqual(cur.children, viaStep.children) || !jsonEqual(cur.roots ?? {}, viaStep.roots ?? {})) return null;
2898
+ return {
2899
+ editDoc: nextEditDoc,
2900
+ stepDoc: nextStepDoc
2901
+ };
2902
+ } catch {
2903
+ return null;
2904
+ }
2905
+ };
2906
+ const tryV4HistoryRebase = (base, edit, editAfter, step, stepAfter, isSetValued, exact = false, canRemoveEmptyParent = false) => {
2907
+ if (hasRootLifecycleConflict(edit, step)) return null;
2908
+ const isExternalYjs = isExternalRootChangeOrigin(edit) || hasInternalDocumentChangeStepFirstAt(edit);
2909
+ if (isExternalYjs) {
2910
+ const attachedStepFast = getV4Steps(step);
2911
+ if (!attachedStepFast || attachedStepFast.length === 0 || !attachedStepFast.every((item) => item.op === "format_text")) return null;
2912
+ if (attachedStepFast.every(isUserFormatStep) && getV4RegisterSteps(step).length === 0 && getInternalDocumentChangeRecords(step).size === 0) {
2913
+ const roots = [.../* @__PURE__ */ new Set([...getInternalDocumentChangeRootKeys(edit), ...getInternalDocumentChangeRootKeys(step)])];
2914
+ if (roots.length === 1) {
2915
+ const root = roots[0];
2916
+ const beforeIndex = valueRootIndex(base, root);
2917
+ const afterIndex = valueRootIndex(editAfter, root);
2918
+ const direct = getInternalDocumentRootChange(edit, root);
2919
+ const directRuns = direct ? keptRunsOf$1(direct, 0, afterIndex.length) : [];
2920
+ const aligned = RootChange.aligned(beforeIndex, afterIndex);
2921
+ const alignedRuns = aligned ? keptRunsOf$1(aligned, 0, afterIndex.length) : [];
2922
+ const findIn = (runs, pos) => {
2923
+ for (const run of runs) {
2924
+ const len = run.to - run.from;
2925
+ if (pos >= run.at && pos < run.at + len) return run.from + (pos - run.at);
2926
+ }
2927
+ return null;
2928
+ };
2929
+ const mapped = rebaseCarriedFormatViaLetters(base, step, stepAfter, {
2930
+ letterAt: (pos) => findIn(directRuns, pos) ?? findIn(alignedRuns, pos),
2931
+ root
2932
+ }, DocumentChange.empty, edit, editAfter, isSetValued);
2933
+ if (mapped) {
2934
+ const origTargets = new Set(attachedStepFast.filter((s) => s.op === "format_text").map((s) => s.target));
2935
+ if ((getV4Steps(mapped.b) ?? []).some((s) => s.op === "format_text" && !origTargets.has(s.target))) return mapped;
3605
2936
  }
3606
- position += leaf.text.length;
3607
2937
  }
3608
- replacements.set(group[0].path.join("."), children);
3609
2938
  }
3610
- const visit = (nodes, parent, offset = 0) => {
3611
- const output = [];
3612
- for (let at = 0; at < nodes.length; at += 1) {
3613
- const node = nodes[at];
3614
- const path = [...parent, at + offset];
3615
- const replacement = replacements.get(path.join("."));
3616
- if (replacement) {
3617
- output.push(...replacement);
3618
- while (at + 1 < nodes.length && isTextNode(nodes[at + 1])) at += 1;
3619
- } else if (!isTextNode(node) && ranges.some((span) => path.every((part, depth) => span.path[depth] === part))) output.push({
3620
- ...node,
3621
- children: visit(node.children, path)
2939
+ }
2940
+ const attachedEdit = getV4Steps(edit);
2941
+ const attachedStep = getV4Steps(step);
2942
+ if ((!attachedEdit && !edit.empty || !attachedStep && !step.empty) && (!collectLiveElementIds(base) || !collectLiveElementIds(editAfter))) return null;
2943
+ let editRawSteps;
2944
+ let stepRawSteps;
2945
+ try {
2946
+ editRawSteps = attachedEdit ?? (edit.empty ? [] : extractV4Between(base, editAfter, { isSetValued }));
2947
+ stepRawSteps = attachedStep ?? (step.empty ? [] : extractV4Between(base, stepAfter, { isSetValued }));
2948
+ } catch {
2949
+ return null;
2950
+ }
2951
+ const editRegSteps = getV4RegisterSteps(edit);
2952
+ const stepRegSteps = getV4RegisterSteps(step);
2953
+ const editDocSteps = editRawSteps.filter((item) => item.op !== "set_register");
2954
+ const stepDocSteps = stepRawSteps.filter((item) => item.op !== "set_register");
2955
+ if (!edit.empty && editDocSteps.length === 0 && editRegSteps.length === 0 && getInternalDocumentChangeRecords(edit).size === 0) return null;
2956
+ if (isExternalYjs && !editDocSteps.every((s) => s.op === "format_text")) return null;
2957
+ if (editDocSteps.length === 2) {
2958
+ const rem = editDocSteps.find((s) => s.op === "remove_node");
2959
+ const ins = editDocSteps.find((s) => s.op === "insert_node");
2960
+ if (rem?.op === "remove_node" && ins?.op === "insert_node" && typeof ins.node.id === "string") {
2961
+ const oldNode = indexElements(base).get(rem.id);
2962
+ if (oldNode && oldNode.type === ins.node.type && jsonEqual(oldNode.children, ins.node.children) && stepDocSteps.some((s) => s.op === "remove_node" && s.id === rem.id)) {
2963
+ const replacementId = ins.node.id;
2964
+ const rewrittenStep = stepDocSteps.map((s) => s.op === "remove_node" && s.id === rem.id ? {
2965
+ id: replacementId,
2966
+ op: "remove_node"
2967
+ } : s);
2968
+ try {
2969
+ const viaEdit = applyV4Steps(editAfter, rewrittenStep);
2970
+ const nextEdit = extractV4Between(stepAfter, viaEdit, { isSetValued });
2971
+ const viaStep = applyV4Steps(stepAfter, nextEdit);
2972
+ if (jsonEqual(viaEdit.children, viaStep.children) && jsonEqual(viaEdit.roots ?? {}, viaStep.roots ?? {})) {
2973
+ const records = {
2974
+ first: getInternalDocumentChangeRecords(edit),
2975
+ second: getInternalDocumentChangeRecords(step)
2976
+ };
2977
+ const nextStepSteps = [...rewrittenStep, ...stepRegSteps];
2978
+ const nextEditSteps = [...nextEdit, ...editRegSteps];
2979
+ const b = rebindChangeNodeKeys(bindV4DocumentChange(createV4DocumentChange(nextStepSteps, { records: records.second }), editAfter), step);
2980
+ return {
2981
+ a: rebindChangeNodeKeys(bindV4DocumentChange(createV4DocumentChange(nextEditSteps, { records: records.first }), stepAfter), edit),
2982
+ b
2983
+ };
2984
+ }
2985
+ } catch {}
2986
+ }
2987
+ }
2988
+ }
2989
+ let nextStepRegs = stepRegSteps;
2990
+ let nextEditRegs = editRegSteps;
2991
+ if (editRegSteps.length > 0 || stepRegSteps.length > 0) {
2992
+ let regRebase;
2993
+ try {
2994
+ regRebase = rebaseV4Changes(base, editRegSteps, stepRegSteps);
2995
+ } catch {
2996
+ return null;
2997
+ }
2998
+ if (!regRebase.ok) return null;
2999
+ nextEditRegs = regRebase.aPrime.filter((item) => item.op === "set_register");
3000
+ nextStepRegs = regRebase.bPrime.filter((item) => item.op === "set_register");
3001
+ }
3002
+ const filteredEditDoc = filterUntouchedMovesForRemovedIds(base, stepDocSteps, editDocSteps);
3003
+ const droppedMoves = filteredEditDoc.length !== editDocSteps.length;
3004
+ const bothRemovedIds = /* @__PURE__ */ new Set();
3005
+ for (const s of editDocSteps) if (s.op === "remove_node" && stepDocSteps.some((st) => st.op === "remove_node" && st.id === s.id)) bothRemovedIds.add(s.id);
3006
+ const effectiveStepDoc = bothRemovedIds.size > 0 ? stepDocSteps.filter((s) => {
3007
+ if ((s.op === "insert_text" || s.op === "delete_text" || s.op === "format_text") && bothRemovedIds.has(s.target)) return false;
3008
+ if (s.op === "set_props" && bothRemovedIds.has(s.id)) return false;
3009
+ return true;
3010
+ }) : stepDocSteps;
3011
+ let nextStepDoc = effectiveStepDoc;
3012
+ let nextEditDoc = filteredEditDoc;
3013
+ if (filteredEditDoc.length > 0 || effectiveStepDoc.length > 0) {
3014
+ if (wrapsAcrossPeerSplit(filteredEditDoc, effectiveStepDoc)) return null;
3015
+ const relocated = tryRelocatedTextDeleteRebase(base, filteredEditDoc, effectiveStepDoc, editAfter, stepAfter);
3016
+ if (relocated) {
3017
+ nextEditDoc = relocated.editDoc;
3018
+ nextStepDoc = relocated.stepDoc;
3019
+ } else {
3020
+ let docRebase;
3021
+ try {
3022
+ docRebase = rebaseV4Changes(base, filteredEditDoc, effectiveStepDoc, {
3023
+ formatConflictWinner: "a",
3024
+ insertTieBreak: exact ? "a" : "b"
3622
3025
  });
3623
- else output.push(node);
3026
+ } catch {
3027
+ return null;
3028
+ }
3029
+ if (!docRebase.ok) {
3030
+ const recovered = tryHistoryEscalationRebase(docRebase.reason, base, editDocSteps, editAfter, effectiveStepDoc, stepAfter, isSetValued, canRemoveEmptyParent) ?? (docRebase.reason === "target-deleted" ? tryRelocatedRestoreOnDeletedTarget(base, editDocSteps, editAfter, effectiveStepDoc, stepAfter, isSetValued) : null);
3031
+ if (!recovered) return null;
3032
+ nextEditDoc = recovered.editDoc;
3033
+ nextStepDoc = recovered.stepDoc;
3034
+ } else {
3035
+ nextEditDoc = docRebase.aPrime;
3036
+ nextStepDoc = docRebase.bPrime;
3037
+ const editRemovedTextNodes = /* @__PURE__ */ new Set();
3038
+ for (const s of editDocSteps) if (s.op === "remove_node") editRemovedTextNodes.add(s.id);
3039
+ if (editRemovedTextNodes.size > 0) {
3040
+ const baseById = indexElements(base);
3041
+ const deletedTexts = /* @__PURE__ */ new Set();
3042
+ for (const s of effectiveStepDoc) if (s.op === "remove_node" && editRemovedTextNodes.has(s.id)) {
3043
+ const node = baseById.get(s.id);
3044
+ if (node && isTextBearingElement(node)) {
3045
+ const { units } = toV4TextStream(node.children);
3046
+ if (units.length > 0 && units.every((u) => u.kind === "char")) deletedTexts.add(units.map((u) => u.kind === "char" ? u.ch : "").join(""));
3047
+ }
3048
+ }
3049
+ if (deletedTexts.size > 0) {
3050
+ const matchesDeletedText = (text) => {
3051
+ for (const deleted of deletedTexts) if (deleted === text || deleted.includes(text)) return true;
3052
+ return false;
3053
+ };
3054
+ const stripped = nextStepDoc.filter((s) => !(s.op === "insert_text" && matchesDeletedText(s.text)));
3055
+ if (stripped.length !== nextStepDoc.length) try {
3056
+ const viaEdit = applyV4Steps(editAfter, stripped);
3057
+ const nextA = extractV4Between(stepAfter, viaEdit, { isSetValued });
3058
+ const viaStep = applyV4Steps(stepAfter, nextA);
3059
+ if (jsonEqual(viaEdit.children, viaStep.children) && jsonEqual(viaEdit.roots ?? {}, viaStep.roots ?? {})) {
3060
+ nextStepDoc = stripped;
3061
+ nextEditDoc = nextA;
3062
+ }
3063
+ } catch {}
3064
+ }
3065
+ }
3624
3066
  }
3625
- return output;
3067
+ }
3068
+ }
3069
+ const records = {
3070
+ first: getInternalDocumentChangeRecords(edit),
3071
+ second: getInternalDocumentChangeRecords(step)
3072
+ };
3073
+ let nextStepSteps = [...nextStepDoc, ...nextStepRegs];
3074
+ let nextEditSteps = [...nextEditDoc, ...nextEditRegs];
3075
+ if (droppedMoves) {
3076
+ let ok = false;
3077
+ try {
3078
+ const viaEdit = applyV4Steps(editAfter, nextStepSteps);
3079
+ const viaStep = applyV4Steps(stepAfter, nextEditSteps);
3080
+ ok = jsonEqual(viaEdit.children, viaStep.children) && jsonEqual(viaEdit.roots ?? {}, viaStep.roots ?? {});
3081
+ } catch {
3082
+ ok = false;
3083
+ }
3084
+ if (!ok) {
3085
+ const recovered = tryHistoryEscalationRebase("dropped-moves", base, editDocSteps, editAfter, stepDocSteps, stepAfter, isSetValued);
3086
+ if (!recovered) return null;
3087
+ nextStepDoc = recovered.stepDoc;
3088
+ nextEditDoc = recovered.editDoc;
3089
+ nextStepSteps = [...nextStepDoc, ...nextStepRegs];
3090
+ nextEditSteps = [...nextEditDoc, ...nextEditRegs];
3091
+ }
3092
+ }
3093
+ try {
3094
+ const b = rebindChangeNodeKeys(bindV4DocumentChange(createV4DocumentChange(nextStepSteps, { records: records.second }), editAfter), step);
3095
+ return {
3096
+ a: rebindChangeNodeKeys(bindV4DocumentChange(createV4DocumentChange(nextEditSteps, { records: records.first }), stepAfter), edit),
3097
+ b
3626
3098
  };
3627
- const changes = [...new Set(ranges.map((span) => span.path[0]))].map((at) => {
3628
- const node = index.node([at]);
3629
- const range = index.nodeRange([at]);
3630
- return {
3631
- from: range.from,
3632
- to: range.to,
3633
- insert: PreparedTokenSlice.fromNodes(visit([node], [], at))
3099
+ } catch {
3100
+ return null;
3101
+ }
3102
+ };
3103
+ const textPropsOf = (node) => {
3104
+ const out = {};
3105
+ for (const [key, value] of Object.entries(node)) if (key !== "text") out[key] = value;
3106
+ return out;
3107
+ };
3108
+ const diffUserMarkDelta = (beforeMarks, afterMarks) => {
3109
+ const set = {};
3110
+ const unset = [];
3111
+ const keys = /* @__PURE__ */ new Set([...Object.keys(beforeMarks), ...Object.keys(afterMarks)]);
3112
+ for (const key of keys) {
3113
+ if (isAuthoredMarkKey(key)) continue;
3114
+ if (jsonEqual(beforeMarks[key], afterMarks[key])) continue;
3115
+ if (Object.hasOwn(afterMarks, key)) set[key] = afterMarks[key];
3116
+ else unset.push(key);
3117
+ }
3118
+ if (Object.keys(set).length === 0 && unset.length === 0) return null;
3119
+ return {
3120
+ ...Object.keys(set).length > 0 ? { set } : {},
3121
+ ...unset.length > 0 ? { unset } : {}
3122
+ };
3123
+ };
3124
+ const formatStepDelta = (step) => ({
3125
+ ...step.set ? { set: step.set } : {},
3126
+ ...step.unset ? { unset: step.unset } : {},
3127
+ ...step.add ? { add: step.add } : {},
3128
+ ...step.remove ? { remove: step.remove } : {}
3129
+ });
3130
+ const coalesceFormatCharTargets = (items) => {
3131
+ const out = [];
3132
+ for (const item of items) {
3133
+ const prev = out.at(-1);
3134
+ if (prev && prev.target === item.id && prev.offset + prev.length === item.offset && jsonEqual(formatStepDelta(prev), item.delta)) out[out.length - 1] = {
3135
+ ...prev,
3136
+ length: prev.length + 1
3137
+ };
3138
+ else out.push({
3139
+ ...item.delta,
3140
+ length: 1,
3141
+ offset: item.offset,
3142
+ op: "format_text",
3143
+ target: item.id
3144
+ });
3145
+ }
3146
+ return out;
3147
+ };
3148
+ const elementCharTokenPositions = (docIndex, elementPath) => {
3149
+ const node = docIndex.node(elementPath);
3150
+ if (!isElementNode(node) || !isTextBearingElement(node)) return null;
3151
+ const positions = [];
3152
+ let pos = docIndex.nodeRange(elementPath).from + 1;
3153
+ for (let i = 0; i < node.children.length; i += 1) {
3154
+ const child = node.children[i];
3155
+ if (isTextNode(child)) {
3156
+ pos += 1;
3157
+ for (let c = 0; c < child.text.length; c += 1) positions.push(pos + c);
3158
+ pos += child.text.length + 1;
3159
+ } else {
3160
+ const childRange = docIndex.nodeRange([...elementPath, i]);
3161
+ positions.push(-1);
3162
+ pos += childRange.to - childRange.from;
3163
+ }
3164
+ }
3165
+ return positions;
3166
+ };
3167
+ const charTargetAtTokenPos = (docIndex, tokenPos) => {
3168
+ const context = docIndex.openContextAt(tokenPos);
3169
+ let hostEntry;
3170
+ for (let i = context.length - 1; i >= 0; i -= 1) if (context[i]?.kind === "element") {
3171
+ hostEntry = context[i];
3172
+ break;
3173
+ }
3174
+ if (!hostEntry) return null;
3175
+ const hostNode = docIndex.node(hostEntry.path);
3176
+ if (!isElementNode(hostNode) || !isTextBearingElement(hostNode) || typeof hostNode.id !== "string" || hostNode.id.length === 0) return null;
3177
+ let pos = hostEntry.from + 1;
3178
+ let offset = 0;
3179
+ for (let i = 0; i < hostNode.children.length; i += 1) {
3180
+ const child = hostNode.children[i];
3181
+ if (isTextNode(child)) {
3182
+ const textStart = pos + 1;
3183
+ const textEnd = textStart + child.text.length;
3184
+ if (tokenPos >= textStart && tokenPos < textEnd) return {
3185
+ id: hostNode.id,
3186
+ offset: offset + (tokenPos - textStart)
3634
3187
  };
3188
+ offset += child.text.length;
3189
+ pos = textEnd + 1;
3190
+ } else {
3191
+ const childRange = docIndex.nodeRange([...hostEntry.path, i]);
3192
+ offset += 1;
3193
+ pos += childRange.to - childRange.from;
3194
+ }
3195
+ }
3196
+ return null;
3197
+ };
3198
+ const locateElementById = (value, targetId) => {
3199
+ const lookup = getValueIdLookup(value);
3200
+ if (lookup) {
3201
+ const found = lookup(targetId);
3202
+ if (found) return found;
3203
+ }
3204
+ const scan = (nodes, prefix) => {
3205
+ for (let i = 0; i < nodes.length; i += 1) {
3206
+ const node = nodes[i];
3207
+ if (!isElementNode(node)) continue;
3208
+ const path = [...prefix, i];
3209
+ if (node.id === targetId) return path;
3210
+ const nested = scan(node.children, path);
3211
+ if (nested) return nested;
3212
+ }
3213
+ return null;
3214
+ };
3215
+ const mainPath = scan(value.children, []);
3216
+ if (mainPath) return {
3217
+ path: mainPath,
3218
+ root: "main"
3219
+ };
3220
+ if (value.roots) for (const root of visitRootNames(value.roots)) {
3221
+ const path = scan(value.roots[root], []);
3222
+ if (path) return {
3223
+ path,
3224
+ root
3225
+ };
3226
+ }
3227
+ return null;
3228
+ };
3229
+ const extractRunStream = (docIndex, from, length) => {
3230
+ const top = docIndex.openContextAt(from).at(-1);
3231
+ let activeMarks = top?.kind === "text" ? textPropsOf(docIndex.node(top.path)) : {};
3232
+ const { tokens } = docIndex.slice(from, from + length);
3233
+ const items = [];
3234
+ let pos = from;
3235
+ for (const token of tokens) if (token.kind === "open" && token.nodeKind === "text") {
3236
+ activeMarks = token.props;
3237
+ pos += 1;
3238
+ } else if (token.kind === "close" && token.nodeKind === "text") {
3239
+ activeMarks = {};
3240
+ pos += 1;
3241
+ } else if (token.kind === "text") {
3242
+ for (let i = 0; i < token.text.length; i += 1) items.push({
3243
+ ch: token.text[i],
3244
+ kind: "char",
3245
+ marks: activeMarks,
3246
+ tokenPos: pos + i
3247
+ });
3248
+ pos += token.text.length;
3249
+ } else {
3250
+ items.push({
3251
+ kind: "token",
3252
+ token
3635
3253
  });
3636
- result = createInternalDocumentChange(/* @__PURE__ */ new Map([[root, RootChange.create(index, changes)]])).apply(result);
3254
+ pos += 1;
3255
+ }
3256
+ return items;
3257
+ };
3258
+ const composeAndStripNoops = (base, change, formatInverse) => {
3259
+ let structure = change.compose(formatInverse, base);
3260
+ for (const [root, rootChange] of getInternalDocumentChangeEntries(structure)) {
3261
+ const cleaned = rootChange.stripNoopSections(valueRootIndex(base, root));
3262
+ if (cleaned !== rootChange) structure = withInternalDocumentRootChange(structure, root, cleaned);
3263
+ }
3264
+ return structure;
3265
+ };
3266
+ const splitCarriedRunFormatTail = (base, change, after, carried) => {
3267
+ const forwardChars = [];
3268
+ const inverseChars = [];
3269
+ for (const run of carried) {
3270
+ const baseIndex = valueRootIndex(base, run.root);
3271
+ const afterIndex = valueRootIndex(after, run.root);
3272
+ const baseItems = extractRunStream(baseIndex, run.source, run.length);
3273
+ const afterItems = extractRunStream(afterIndex, run.at, run.landed);
3274
+ if (baseItems.length !== afterItems.length) return null;
3275
+ for (let i = 0; i < baseItems.length; i += 1) {
3276
+ const left = baseItems[i];
3277
+ const right = afterItems[i];
3278
+ if (left.kind !== right.kind) return null;
3279
+ if (left.kind === "token" && right.kind === "token") {
3280
+ if (!tokensEqual(left.token, right.token)) return null;
3281
+ continue;
3282
+ }
3283
+ if (left.kind !== "char" || right.kind !== "char") return null;
3284
+ if (left.ch !== right.ch) return null;
3285
+ if (jsonEqual(left.marks, right.marks)) continue;
3286
+ const forwardDelta = diffUserMarkDelta(left.marks, right.marks);
3287
+ const inverseDelta = diffUserMarkDelta(right.marks, left.marks);
3288
+ if (!forwardDelta || !inverseDelta) return null;
3289
+ const target = charTargetAtTokenPos(afterIndex, right.tokenPos);
3290
+ if (!target) return null;
3291
+ forwardChars.push({
3292
+ delta: forwardDelta,
3293
+ id: target.id,
3294
+ offset: target.offset
3295
+ });
3296
+ inverseChars.push({
3297
+ delta: inverseDelta,
3298
+ id: target.id,
3299
+ offset: target.offset
3300
+ });
3301
+ }
3637
3302
  }
3638
- return result;
3303
+ if (forwardChars.length === 0) return null;
3304
+ const formatSteps = coalesceFormatCharTargets(forwardChars);
3305
+ const invFormatSteps = coalesceFormatCharTargets(inverseChars);
3306
+ try {
3307
+ const structureAfter = applyV4Steps(after, invFormatSteps);
3308
+ const format = bindV4DocumentChange(createV4DocumentChange(formatSteps), structureAfter);
3309
+ const formatInverse = bindV4DocumentChange(createV4DocumentChange(invFormatSteps), after);
3310
+ return {
3311
+ format,
3312
+ formatInverse,
3313
+ structure: composeAndStripNoops(base, change, formatInverse),
3314
+ structureAfter
3315
+ };
3316
+ } catch {
3317
+ return null;
3318
+ }
3319
+ };
3320
+ const splitV4FormatTail = (base, change, after, isSetValued, allowExtract = false, carried) => {
3321
+ const attached = getV4Steps(change);
3322
+ if (attached || allowExtract && !change.empty) {
3323
+ let steps = null;
3324
+ try {
3325
+ steps = attached ?? extractV4Between(base, after, { isSetValued });
3326
+ } catch {
3327
+ steps = null;
3328
+ }
3329
+ if (steps && steps.length > 0) {
3330
+ let hasFormat = false;
3331
+ let hasStruct = false;
3332
+ for (const step of steps) if (isUserFormatStep(step)) hasFormat = true;
3333
+ else hasStruct = true;
3334
+ if (hasFormat && hasStruct) {
3335
+ const structSteps = steps.filter((step) => !isUserFormatStep(step));
3336
+ try {
3337
+ const structureAfter = applyV4Steps(base, structSteps);
3338
+ const formatSteps = extractV4Between(structureAfter, after, { isSetValued });
3339
+ if (formatSteps.length > 0 && formatSteps.every(isUserFormatStep)) {
3340
+ const format = bindV4DocumentChange(createV4DocumentChange(formatSteps), structureAfter);
3341
+ const formatInverse = format.invert(structureAfter);
3342
+ return {
3343
+ format,
3344
+ formatInverse,
3345
+ structure: composeAndStripNoops(base, change, formatInverse),
3346
+ structureAfter
3347
+ };
3348
+ }
3349
+ } catch {}
3350
+ }
3351
+ }
3352
+ }
3353
+ if (carried && carried.length > 0) return splitCarriedRunFormatTail(base, change, after, carried);
3354
+ return null;
3355
+ };
3356
+ const rebaseCarriedFormatViaLetters = (structureAfter, format, recordedAfter, letters, structRepair, repairedStructA, repairedStructAfter, isSetValued) => {
3357
+ let formatSteps;
3358
+ try {
3359
+ formatSteps = getV4Steps(format) ?? extractV4Between(structureAfter, recordedAfter, { isSetValued });
3360
+ } catch {
3361
+ return null;
3362
+ }
3363
+ if (formatSteps.length === 0 || !formatSteps.every(isUserFormatStep)) return null;
3364
+ const structureIndex = valueRootIndex(structureAfter, letters.root);
3365
+ const repairedIndex = valueRootIndex(repairedStructAfter, letters.root);
3366
+ const repairRoot = structRepair.empty ? null : getInternalDocumentRootChange(structRepair, letters.root) ?? null;
3367
+ const projectedChars = [];
3368
+ const unprojectedChars = [];
3369
+ const otherRootSteps = [];
3370
+ for (const step of formatSteps) {
3371
+ if (step.op !== "format_text") return null;
3372
+ const loc = locateElementById(structureAfter, step.target);
3373
+ if (!loc) return null;
3374
+ if (loc.root !== letters.root) {
3375
+ otherRootSteps.push(step);
3376
+ continue;
3377
+ }
3378
+ const positions = elementCharTokenPositions(structureIndex, loc.path);
3379
+ if (!positions) return null;
3380
+ const delta = formatStepDelta(step);
3381
+ for (let k = 0; k < step.length; k += 1) {
3382
+ const charOffset = step.offset + k;
3383
+ const tokPos = positions[charOffset];
3384
+ if (tokPos === void 0 || tokPos < 0) {
3385
+ unprojectedChars.push({
3386
+ delta,
3387
+ id: step.target,
3388
+ offset: charOffset
3389
+ });
3390
+ continue;
3391
+ }
3392
+ const landed = letters.letterAt(tokPos);
3393
+ if (landed === null) continue;
3394
+ if (typeof landed === "number") {
3395
+ const mappedPos = repairRoot ? repairRoot.mapPos(landed, 1) : landed;
3396
+ if (mappedPos === null) continue;
3397
+ const dest = charTargetAtTokenPos(repairedIndex, mappedPos);
3398
+ if (!dest) return null;
3399
+ projectedChars.push({
3400
+ delta,
3401
+ id: dest.id,
3402
+ offset: dest.offset
3403
+ });
3404
+ } else unprojectedChars.push({
3405
+ delta,
3406
+ id: step.target,
3407
+ offset: charOffset
3408
+ });
3409
+ }
3410
+ }
3411
+ const mappedSteps = [...coalesceFormatCharTargets(projectedChars)];
3412
+ const unprojectedSteps = [...coalesceFormatCharTargets(unprojectedChars), ...otherRootSteps];
3413
+ if (unprojectedSteps.length > 0) {
3414
+ let editSteps;
3415
+ try {
3416
+ editSteps = getV4Steps(repairedStructA) ?? (repairedStructA.empty ? [] : extractV4Between(structureAfter, repairedStructAfter, { isSetValued }));
3417
+ } catch {
3418
+ return null;
3419
+ }
3420
+ try {
3421
+ const rebased = rebaseV4Changes(structureAfter, editSteps, unprojectedSteps, {
3422
+ formatConflictWinner: "a",
3423
+ insertTieBreak: "b"
3424
+ });
3425
+ if (!rebased.ok) return null;
3426
+ for (const step of rebased.bPrime) {
3427
+ if (step.op !== "format_text") return null;
3428
+ mappedSteps.push(step);
3429
+ }
3430
+ } catch {
3431
+ return null;
3432
+ }
3433
+ }
3434
+ try {
3435
+ const b = bindV4DocumentChange(createV4DocumentChange(mappedSteps), repairedStructAfter);
3436
+ const afterFmt = b.apply(repairedStructAfter);
3437
+ return {
3438
+ a: DocumentChange.between(recordedAfter, afterFmt),
3439
+ b
3440
+ };
3441
+ } catch {
3442
+ return null;
3443
+ }
3444
+ };
3445
+ const locateTextPointById = (value, root, point) => {
3446
+ if (point.path.length < 2) return null;
3447
+ const hostPath = point.path.slice(0, -1);
3448
+ const leafIndex = point.path.at(-1);
3449
+ if (leafIndex === void 0) return null;
3450
+ let host;
3451
+ try {
3452
+ host = valueRootIndex(value, root).node(hostPath);
3453
+ } catch {
3454
+ return null;
3455
+ }
3456
+ if (!isElementNode(host) || !isTextBearingElement(host) || typeof host.id !== "string" || host.id.length === 0) return null;
3457
+ let offset = 0;
3458
+ for (let i = 0; i < leafIndex; i += 1) {
3459
+ const child = host.children[i];
3460
+ if (!child) return null;
3461
+ offset += isTextNode(child) ? child.text.length : 1;
3462
+ }
3463
+ return {
3464
+ id: host.id,
3465
+ offset: offset + point.offset
3466
+ };
3467
+ };
3468
+ const resolveIdOffsetToPoint = (after, root, targetId, targetOffset, hintPath) => {
3469
+ let found = null;
3470
+ if (hintPath && hintPath.length > 0) try {
3471
+ const node = valueRootIndex(after, root).node(hintPath);
3472
+ if (isElementNode(node) && node.id === targetId) found = {
3473
+ node,
3474
+ path: hintPath
3475
+ };
3476
+ } catch {
3477
+ found = null;
3478
+ }
3479
+ if (!found) {
3480
+ const lookup = getValueIdLookup(after);
3481
+ if (lookup) {
3482
+ const loc = lookup(targetId);
3483
+ if (loc && loc.root === root) try {
3484
+ const node = valueRootIndex(after, root).node(loc.path);
3485
+ if (isElementNode(node) && node.id === targetId) found = {
3486
+ node,
3487
+ path: loc.path
3488
+ };
3489
+ } catch {
3490
+ found = null;
3491
+ }
3492
+ }
3493
+ }
3494
+ if (!found) {
3495
+ const nodes = valueRoot(after, root);
3496
+ const find = (list, prefix) => {
3497
+ for (let i = 0; i < list.length; i += 1) {
3498
+ const node = list[i];
3499
+ if (!isElementNode(node)) continue;
3500
+ const path = [...prefix, i];
3501
+ if (node.id === targetId) return {
3502
+ node,
3503
+ path
3504
+ };
3505
+ const nested = find(node.children, path);
3506
+ if (nested) return nested;
3507
+ }
3508
+ return null;
3509
+ };
3510
+ found = find(nodes, []);
3511
+ }
3512
+ if (!found || !isTextBearingElement(found.node)) return null;
3513
+ let cursor = 0;
3514
+ let lastTextIndex = -1;
3515
+ let lastTextLength = 0;
3516
+ for (let i = 0; i < found.node.children.length; i += 1) {
3517
+ const child = found.node.children[i];
3518
+ if (isTextNode(child)) {
3519
+ const end = cursor + child.text.length;
3520
+ if (targetOffset >= cursor && targetOffset <= end) return {
3521
+ offset: targetOffset - cursor,
3522
+ path: [...found.path, i]
3523
+ };
3524
+ lastTextIndex = i;
3525
+ lastTextLength = child.text.length;
3526
+ cursor = end;
3527
+ } else cursor += 1;
3528
+ }
3529
+ if (lastTextIndex !== -1) return {
3530
+ offset: lastTextLength,
3531
+ path: [...found.path, lastTextIndex]
3532
+ };
3533
+ return null;
3534
+ };
3535
+ const lookupTextBearingLength = (value, targetId) => {
3536
+ const lookup = getValueIdLookup(value);
3537
+ if (lookup) {
3538
+ const loc = lookup(targetId);
3539
+ if (!loc) return void 0;
3540
+ try {
3541
+ const node = valueRootIndex(value, loc.root).node(loc.path);
3542
+ if (isElementNode(node) && isTextBearingElement(node)) return elementStreamLength(node);
3543
+ } catch {
3544
+ return;
3545
+ }
3546
+ return;
3547
+ }
3548
+ const node = indexElements(value).get(targetId);
3549
+ return node && isTextBearingElement(node) ? elementStreamLength(node) : void 0;
3550
+ };
3551
+ const mapPointThroughV4Steps = (before, after, steps, point, root) => {
3552
+ const located = locateTextPointById(before, root, point);
3553
+ if (!located) return null;
3554
+ let { id } = located;
3555
+ let { offset } = located;
3556
+ const needsLengths = steps.some((step) => step.op === "split_node" || step.op === "join_nodes");
3557
+ const lengths = /* @__PURE__ */ new Map();
3558
+ const getLength = (targetId) => {
3559
+ if (!needsLengths) return void 0;
3560
+ if (lengths.has(targetId)) return lengths.get(targetId);
3561
+ const len = lookupTextBearingLength(before, targetId);
3562
+ if (len !== void 0) lengths.set(targetId, len);
3563
+ return len;
3564
+ };
3565
+ for (const step of steps) switch (step.op) {
3566
+ case "insert_text":
3567
+ if (step.target === id && step.offset < offset) offset += step.text.length;
3568
+ if (needsLengths) {
3569
+ const prev = getLength(step.target);
3570
+ if (prev !== void 0) lengths.set(step.target, prev + step.text.length);
3571
+ }
3572
+ break;
3573
+ case "delete_text":
3574
+ if (step.target === id) {
3575
+ if (offset > step.offset + step.length) offset -= step.length;
3576
+ else if (offset > step.offset) ({offset} = step);
3577
+ }
3578
+ if (needsLengths) {
3579
+ const prev = getLength(step.target);
3580
+ if (prev !== void 0) lengths.set(step.target, Math.max(0, prev - step.length));
3581
+ }
3582
+ break;
3583
+ case "split_node": {
3584
+ const prev = getLength(step.id);
3585
+ if (prev !== void 0) {
3586
+ lengths.set(step.id, step.at);
3587
+ lengths.set(step.newId, Math.max(0, prev - step.at));
3588
+ }
3589
+ if (step.id === id && offset > step.at) {
3590
+ id = step.newId;
3591
+ offset -= step.at;
3592
+ }
3593
+ break;
3594
+ }
3595
+ case "join_nodes": {
3596
+ const leftLen = getLength(step.target);
3597
+ const rightLen = getLength(step.source);
3598
+ if (step.source === id) {
3599
+ if (leftLen === void 0) return null;
3600
+ id = step.target;
3601
+ offset += leftLen;
3602
+ }
3603
+ if (leftLen !== void 0 && rightLen !== void 0) lengths.set(step.target, leftLen + rightLen);
3604
+ lengths.delete(step.source);
3605
+ break;
3606
+ }
3607
+ case "remove_node":
3608
+ if (step.id === id) return null;
3609
+ lengths.delete(step.id);
3610
+ break;
3611
+ case "insert_node":
3612
+ if ("offset" in step.to) {
3613
+ if (step.to.id === id && step.to.offset < offset) offset += 1;
3614
+ if (needsLengths) {
3615
+ const prev = getLength(step.to.id);
3616
+ if (prev !== void 0) lengths.set(step.to.id, prev + 1);
3617
+ }
3618
+ }
3619
+ break;
3620
+ case "wrap_inline":
3621
+ case "unwrap_inline":
3622
+ if (step.op === "wrap_inline" && step.target === id || step.op === "unwrap_inline" && (step.parent === id || step.id === id)) return null;
3623
+ break;
3624
+ default: break;
3625
+ }
3626
+ return resolveIdOffsetToPoint(after, root, id, offset, id === located.id ? point.path.slice(0, -1) : void 0);
3627
+ };
3628
+ const mapTextSelectionViaV4 = (editor, selection, change, before, after, root, exact = false) => {
3629
+ if (exact || !selection || !SelectionApi.isText(selection)) return mapSelectionThroughChange(editor, selection, change, before, after, root).selection;
3630
+ const steps = getV4Steps(change);
3631
+ if (steps) {
3632
+ const anchor = mapPointThroughV4Steps(before, after, steps, selection.anchor, root);
3633
+ const focus = mapPointThroughV4Steps(before, after, steps, selection.focus, root);
3634
+ if (anchor && focus) return {
3635
+ ...selection,
3636
+ anchor: {
3637
+ ...selection.anchor,
3638
+ ...anchor
3639
+ },
3640
+ focus: {
3641
+ ...selection.focus,
3642
+ ...focus
3643
+ }
3644
+ };
3645
+ }
3646
+ return mapSelectionThroughChange(editor, selection, change, before, after, root).selection;
3647
+ };
3648
+ const remintForeignRestoredV4Change = (change, liveIds, currentScope, mint, renamed) => {
3649
+ const steps = getV4Steps(change);
3650
+ if (!steps || steps.length === 0) return change;
3651
+ let changed = false;
3652
+ const mapRef = (id) => {
3653
+ const mapped = renamed.get(id);
3654
+ if (mapped !== void 0) {
3655
+ changed = true;
3656
+ return mapped;
3657
+ }
3658
+ return id;
3659
+ };
3660
+ const mintIfForeignNonLive = (id) => {
3661
+ if (liveIds.has(id)) return id;
3662
+ const existing = renamed.get(id);
3663
+ if (existing !== void 0) {
3664
+ changed = true;
3665
+ return existing;
3666
+ }
3667
+ const parsed = parseScopedElementId(id);
3668
+ if (parsed && parsed.scope === currentScope) return id;
3669
+ const fresh = mint();
3670
+ renamed.set(id, fresh);
3671
+ changed = true;
3672
+ return fresh;
3673
+ };
3674
+ const remapNode = (node) => {
3675
+ if (!isElementNode(node)) return node;
3676
+ const nextId = typeof node.id === "string" ? mintIfForeignNonLive(node.id) : node.id;
3677
+ const nextChildren = node.children.map(remapNode);
3678
+ if (nextId === node.id && nextChildren.every((child, index) => child === node.children[index])) return node;
3679
+ return {
3680
+ ...node,
3681
+ ...nextId === void 0 ? {} : { id: nextId },
3682
+ children: nextChildren
3683
+ };
3684
+ };
3685
+ const remapPlace = (place) => "id" in place ? {
3686
+ ...place,
3687
+ id: mapRef(place.id)
3688
+ } : place;
3689
+ const nextSteps = steps.map((step) => {
3690
+ switch (step.op) {
3691
+ case "insert_text":
3692
+ case "delete_text":
3693
+ case "format_text": return {
3694
+ ...step,
3695
+ target: mapRef(step.target)
3696
+ };
3697
+ case "insert_node": return {
3698
+ ...step,
3699
+ node: remapNode(step.node),
3700
+ to: remapPlace(step.to)
3701
+ };
3702
+ case "remove_node":
3703
+ case "set_props": return {
3704
+ ...step,
3705
+ id: mapRef(step.id)
3706
+ };
3707
+ case "move_node": return {
3708
+ ...step,
3709
+ id: mapRef(step.id),
3710
+ to: remapPlace(step.to)
3711
+ };
3712
+ case "split_node": return {
3713
+ ...step,
3714
+ id: mapRef(step.id),
3715
+ newId: mintIfForeignNonLive(step.newId)
3716
+ };
3717
+ case "join_nodes": return {
3718
+ ...step,
3719
+ source: mapRef(step.source),
3720
+ target: mapRef(step.target)
3721
+ };
3722
+ case "wrap_inline": return {
3723
+ ...step,
3724
+ node: remapNode(step.node),
3725
+ target: mapRef(step.target)
3726
+ };
3727
+ case "unwrap_inline": return {
3728
+ ...step,
3729
+ id: mapRef(step.id),
3730
+ parent: mapRef(step.parent)
3731
+ };
3732
+ default: return step;
3733
+ }
3734
+ });
3735
+ if (!changed) return change;
3736
+ return createV4DocumentChange(nextSteps, { records: getInternalDocumentChangeRecords(change) });
3639
3737
  };
3738
+ //#endregion
3739
+ //#region src/history/history-replay.ts
3740
+ const replayOver = (schema, edit, step, base, rules) => transformInternalDocumentChange(edit, step, base, replayTransformOptions(schema, rules));
3640
3741
  const recordHistoryReplay = (schema, base, change, direction, { after, carried, parts, program } = {}) => {
3641
3742
  if (parts) {
3642
- const unsettle = recordPart(schema, base, parts.unsettle, direction);
3643
- return pairedReplay(change, direction, unsettle, recordPart(schema, unsettle.record().after, parts.rest, direction));
3743
+ const unsettle = recordPart(schema, base, parts.unsettle, direction, "unsettle");
3744
+ return pairedReplay(change, direction, unsettle, recordPart(schema, unsettle.record().after, parts.rest, direction, "rest"));
3644
3745
  }
3645
3746
  let recorded;
3646
3747
  const known = after ? { after } : {};
@@ -3650,14 +3751,14 @@ const recordHistoryReplay = (schema, base, change, direction, { after, carried,
3650
3751
  direction,
3651
3752
  ...known,
3652
3753
  program,
3653
- record: () => recorded ??= recordReplay(schema, base, change, false, known)
3754
+ record: () => recorded ??= recordReplay(schema, base, change, known)
3654
3755
  };
3655
3756
  return {
3656
3757
  change,
3657
3758
  ...carried?.length ? { carried } : {},
3658
3759
  direction,
3659
3760
  ...known,
3660
- record: () => recorded ??= recordReplay(schema, base, change, false, {
3761
+ record: () => recorded ??= recordReplay(schema, base, change, {
3661
3762
  ...known,
3662
3763
  carried
3663
3764
  })
@@ -3809,14 +3910,14 @@ const mapProgramReplay = (schema, replay, program, base, mapping, rules) => {
3809
3910
  rest: createInternalDocumentChange(/* @__PURE__ */ new Map([[root, carryRest(previous.final, edit, before, next.final)]]))
3810
3911
  };
3811
3912
  };
3812
- const recordPart = (schema, base, change, direction) => {
3913
+ const recordPart = (schema, base, change, direction, exact) => {
3813
3914
  const part = classifyDocumentChange(base, change.apply(base), change);
3814
3915
  let recorded;
3815
3916
  return {
3816
3917
  change: part,
3817
3918
  direction,
3818
- exact: true,
3819
- record: () => recorded ??= recordReplay(schema, base, part, true)
3919
+ exact,
3920
+ record: () => recorded ??= recordReplay(schema, base, part, { exact: exact === "rest" })
3820
3921
  };
3821
3922
  };
3822
3923
  const pairedReplay = (change, direction, unsettle, rest) => ({
@@ -3828,7 +3929,6 @@ const pairedReplay = (change, direction, unsettle, rest) => ({
3828
3929
  },
3829
3930
  record: () => ({
3830
3931
  after: rest.record().after,
3831
- format: /* @__PURE__ */ new Map(),
3832
3932
  structure: change
3833
3933
  })
3834
3934
  });
@@ -3846,176 +3946,32 @@ const exactRunsOf = (runs, structure, before, after) => {
3846
3946
  }
3847
3947
  return exact.length > 0 ? exact : void 0;
3848
3948
  };
3849
- /** Each carried letter of `root` in `before`, with where it lands in `after`. */
3850
- const carriedLettersOf = (runs, root, before, after) => {
3851
- const letters = /* @__PURE__ */ new Map();
3852
- for (const run of runs ?? []) {
3853
- if (run.root !== root) continue;
3854
- for (const { from, to } of carriedLetterPairs(run, valueRootIndex(before, root), valueRootIndex(after, root))) letters.set(from, to);
3855
- }
3856
- return letters.size > 0 ? (position) => letters.get(position) : void 0;
3857
- };
3858
- const recordReplay = (schema, base, change, exact = false, known = {}) => {
3859
- const { carried } = known;
3949
+ const recordReplay = (schema, base, change, known = {}) => {
3860
3950
  const after = known.after ?? change.apply(base);
3861
- const format = /* @__PURE__ */ new Map();
3862
- const unformatted = () => {
3863
- const runs = exactRunsOf(carried, change, base, after);
3864
- return {
3865
- structure: change,
3866
- format,
3867
- after,
3868
- ...runs ? { runs } : {}
3869
- };
3870
- };
3871
- if (change.empty || isInternalTextOnlyDocumentChange(change)) return unformatted();
3872
- const reset = /* @__PURE__ */ new Map();
3873
- const resets = /* @__PURE__ */ new Map();
3874
- for (const [root] of getInternalDocumentChangeEntries(change)) {
3875
- const source = valueRootIndex(base, root);
3876
- const target = valueRootIndex(after, root);
3877
- const correspondence = createCharacterCorrespondence(base, after, change, root, exact, carriedLettersOf(carried, root, base, after));
3878
- const spans = [];
3879
- const rootResets = [];
3880
- const visit = (node, path) => {
3881
- if (isTextNode(node)) return;
3882
- for (let at = 0; at < node.children.length; at += 1) {
3883
- const child = node.children[at];
3884
- if (!isTextNode(child)) {
3885
- visit(child, [...path, at]);
3886
- continue;
3887
- }
3888
- const host = textHostAt(source, [...path, at]);
3889
- let offset = 0;
3890
- for (const leaf of host.leaves) {
3891
- if (!isTextNode(leaf)) continue;
3892
- for (const fragment of correspondence.fragments({
3893
- path: host.path,
3894
- from: offset,
3895
- to: offset + leaf.text.length
3896
- })) {
3897
- const nextHost = textHostAt(target, fragment.target.path);
3898
- let nextOffset = 0;
3899
- for (let nextIndex = 0; nextIndex < nextHost.leaves.length; nextIndex += 1) {
3900
- const next = nextHost.leaves[nextIndex];
3901
- if (!isTextNode(next)) continue;
3902
- const from = Math.max(fragment.target.from, nextOffset);
3903
- const to = Math.min(fragment.target.to, nextOffset + next.text.length);
3904
- if (from < to) {
3905
- const previous = nodeProps(leaf);
3906
- const props = nodeProps(next);
3907
- const writes = [];
3908
- for (const key of /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(props)])) {
3909
- if (jsonEqual(previous[key], props[key])) continue;
3910
- if (schema.isSetValued(next, key, getDocumentPropertyContext(target, [...nextHost.path.slice(0, -1), getDefined(nextHost.path.at(-1)) + nextIndex], root === "main" ? null : root))) {
3911
- const beforeMembers = Array.isArray(previous[key]) ? previous[key] : [];
3912
- const afterMembers = Array.isArray(props[key]) ? props[key] : [];
3913
- writes.push({
3914
- key,
3915
- kind: "members",
3916
- add: afterMembers.filter((member) => !beforeMembers.some((old) => jsonEqual(old, member))),
3917
- remove: beforeMembers.filter((member) => !afterMembers.some((candidate) => jsonEqual(candidate, member)))
3918
- });
3919
- } else writes.push({
3920
- key,
3921
- kind: "value",
3922
- expect: previous[key],
3923
- value: props[key]
3924
- });
3925
- }
3926
- if (writes.length > 0) spans.push({
3927
- ...fragment.target,
3928
- from,
3929
- to,
3930
- writes
3931
- });
3932
- const range = {
3933
- ...fragment.target,
3934
- from,
3935
- to
3936
- };
3937
- reset.set(range, previous);
3938
- rootResets.push(range);
3939
- }
3940
- nextOffset += next.text.length;
3941
- }
3942
- }
3943
- offset += leaf.text.length;
3944
- }
3945
- at += host.leaves.length - 1;
3946
- }
3947
- };
3948
- for (const [from, to] of source.changedChildren(target)) for (let at = from; at < to; at += 1) {
3949
- const node = source.child(at);
3950
- if (node) visit(node, [at]);
3951
- }
3952
- if (spans.length) format.set(root, spans);
3953
- if (rootResets.length) resets.set(root, rootResets);
3954
- }
3955
- if (format.size === 0) return unformatted();
3956
- const middle = rewriteSpans(after, resets, (span) => reset.get(span) ?? {});
3957
- const aligned = Boolean(carried?.length) ? alignedDocumentChange(after, middle) : null;
3958
- const resetChange = aligned ?? DocumentChange.between(after, middle, { isSetValued: schema.isSetValued });
3959
- for (const [root, spans] of format) {
3960
- const correspondence = createCharacterCorrespondence(after, middle, resetChange, root, aligned !== null);
3961
- format.set(root, spans.flatMap((span) => correspondence.fragments(span).map(({ target }) => ({
3962
- ...target,
3963
- writes: span.writes
3964
- }))));
3965
- }
3966
- if (aligned) {
3967
- const structure = change.compose(aligned);
3968
- const moved = carried?.map((run) => {
3969
- const rootReset = getInternalDocumentRootChange(aligned, run.root);
3970
- return rootReset ? mapCarriedRunThrough(run, rootReset, valueRootIndex(after, run.root)) : run;
3971
- });
3972
- const runs = moved?.every((run) => run !== null) ? exactRunsOf(moved, structure, base, middle) : void 0;
3973
- return {
3974
- structure,
3975
- format,
3976
- after,
3977
- ...runs ? { runs } : {}
3978
- };
3979
- }
3951
+ const split = known.carried?.length || known.exact ? splitV4FormatTail(base, change, after, schema.isSetValued, known.maybeFormatted === true || known.exact === true, known.carried) : null;
3952
+ const structure = split ? split.structure : change;
3953
+ const structureAfter = split ? split.structureAfter : after;
3954
+ const carriedForStructure = split && known.carried ? landCarriedRuns(known.carried, [{
3955
+ after: structureAfter,
3956
+ before: after,
3957
+ change: split.formatInverse
3958
+ }], {
3959
+ after: structureAfter,
3960
+ before: base,
3961
+ change: structure
3962
+ }) ?? known.carried : known.carried;
3963
+ const runs = exactRunsOf(carriedForStructure, structure, base, structureAfter);
3964
+ const useSplit = Boolean(split && (runs || known.exact));
3980
3965
  return {
3981
- structure: exact ? collapseDocumentElementPropertyWrites(change.compose(DocumentChange.between(after, middle, { isSetValued: schema.isSetValued })), base, schema.isSetValued, { textLeaves: true }) : DocumentChange.between(base, middle, { isSetValued: schema.isSetValued }),
3982
- format,
3983
- after
3966
+ after,
3967
+ ...useSplit && split ? {
3968
+ format: split.format,
3969
+ structureAfter
3970
+ } : {},
3971
+ ...runs ? { runs } : {},
3972
+ structure: useSplit ? structure : change
3984
3973
  };
3985
3974
  };
3986
- const applyFormatIntent = (schema, value, format, direction) => {
3987
- const writes = /* @__PURE__ */ new Map();
3988
- for (const spans of format.values()) for (const span of spans) writes.set(span, span.writes);
3989
- return rewriteSpans(value, format, (span, properties, path, root) => {
3990
- const result = { ...properties };
3991
- const preferred = [];
3992
- for (const write of writes.get(span) ?? []) {
3993
- if (!schema.allows(write.key, path, root, value)) continue;
3994
- if (write.kind === "members") {
3995
- const current = result[write.key];
3996
- const next = normalizeSetValues([...(Array.isArray(current) ? current : []).filter((member) => !write.remove.some((removed) => jsonEqual(member, removed))), ...write.add]);
3997
- if (next.length) result[write.key] = next;
3998
- else delete result[write.key];
3999
- } else {
4000
- if (direction === "undo" && !jsonEqual(result[write.key], write.expect)) continue;
4001
- if (write.value === void 0) delete result[write.key];
4002
- else {
4003
- const candidate = {
4004
- ...result,
4005
- [write.key]: write.value
4006
- };
4007
- const canonical = schema.canonicalize(candidate, path, root, write.key, value);
4008
- if (direction === "undo" && Object.keys(result).some((key) => key !== write.key && !Object.hasOwn(canonical, key))) continue;
4009
- result[write.key] = write.value;
4010
- preferred.push(write.key);
4011
- }
4012
- }
4013
- }
4014
- let canonical = result;
4015
- for (const key of preferred) canonical = { ...schema.canonicalize(canonical, path, root, key, value) };
4016
- return canonical;
4017
- });
4018
- };
4019
3975
  const composeRepair = (change, repair) => repair.empty ? change : change.compose(repair);
4020
3976
  /**
4021
3977
  * Map a step that carries runs through an outside edit: by content when the
@@ -4114,7 +4070,7 @@ const holdsOnly = (change, root) => change.createRoots.size === 0 && change.dele
4114
4070
  * Map a step through an outside edit from its base. A two-part step maps its
4115
4071
  * take-back first, then its rest through what is left of the edit.
4116
4072
  */
4117
- const mapHistoryReplay = (schema, replay, base, mapping, { anchor, readBack: reads }) => {
4073
+ const mapHistoryReplay = (schema, replay, base, mapping, { anchor, canRemoveEmptyParent, readBack: reads }) => {
4118
4074
  const readBack = reads ? {
4119
4075
  changed: false,
4120
4076
  projected: false
@@ -4122,6 +4078,7 @@ const mapHistoryReplay = (schema, replay, base, mapping, { anchor, readBack: rea
4122
4078
  return {
4123
4079
  ...mapReplay(schema, replay, base, mapping, {
4124
4080
  anchor,
4081
+ canRemoveEmptyParent,
4125
4082
  readBack
4126
4083
  }),
4127
4084
  projected: readBack?.projected === true,
@@ -4146,7 +4103,7 @@ const mapReplay = (schema, replay, base, mapping, rules) => {
4146
4103
  rest: rest.rest
4147
4104
  };
4148
4105
  };
4149
- const replayedStructure = (replay, recorded, base, mapping) => !replay.exact && !replay.carried && mapping.textOnly && recorded.format.size === 0 && isInternalTextOnlyDocumentChange(replay.change) ? DocumentChange.between(base, recorded.after) : recorded.structure;
4106
+ const replayedStructure = (replay, recorded, base, mapping) => !replay.exact && !replay.carried && mapping.textOnly && isInternalTextOnlyDocumentChange(replay.change) ? DocumentChange.between(base, recorded.after) : recorded.structure;
4150
4107
  const rangesApart = (step, delivered) => step.createRoots.size === 0 && step.deleteRoots.size === 0 && getInternalDocumentChangeRecords(step).size === 0 && [...getInternalDocumentChangeClassificationEntries(step)].every(([root, kind]) => {
4151
4108
  if (!kind.text || kind.properties || kind.structure || delivered.createRoots.has(root) || delivered.deleteRoots.has(root)) return false;
4152
4109
  const theirs = getInternalDocumentChangeRanges(delivered, root);
@@ -4156,8 +4113,9 @@ const keepsUndoThrough = (schema, replay, base, mapping) => {
4156
4113
  if (replay.direction !== "undo" || replay.after === void 0 || replay.carried || replay.exact || replay.parts || replay.program) return false;
4157
4114
  if (rangesApart(replay.change, mapping.change)) return true;
4158
4115
  const recorded = replay.record();
4159
- if (recorded.format.size > 0) return false;
4160
4116
  try {
4117
+ const v4 = tryV4HistoryRebase(base, mapping.change, mapping.after, replay.change, recorded.after, schema.isSetValued);
4118
+ if (v4) return !v4.b.empty;
4161
4119
  return !replayOver(schema, mapping.change, replayedStructure(replay, recorded, base, mapping), base, {
4162
4120
  anchor: false,
4163
4121
  readBack: {
@@ -4188,122 +4146,74 @@ const mapOneReplay = (schema, replay, base, mapping, rules) => {
4188
4146
  direction: replay.direction,
4189
4147
  record
4190
4148
  };
4191
- return {
4192
- change: classifyDocumentChange(mapping.after, record().after, change),
4193
- direction: replay.direction,
4194
- exact,
4195
- record
4196
- };
4197
- };
4198
- const recorded = replay.record();
4199
- let middleValue;
4200
- const middleOf = () => middleValue ??= recorded.structure.apply(base);
4201
- const carry = replay.carried && !exact && recorded.runs ? carryReplay(schema, recorded.runs, recorded, base, middleOf(), mapping, stepRules) : null;
4202
- const transformed = carry ?? replayOver(schema, mapping.change, replayedStructure(replay, recorded, base, mapping), base, stepRules);
4203
- const { keptWrap } = transformed;
4204
- if (recorded.format.size === 0) {
4205
- const mappedAfter = carry ? transformed.b.apply(mapping.after) : transformed.a.apply(recorded.after);
4206
- const repair = schema.repairCanonical(mapping.after, transformed.b, mappedAfter);
4207
- const change = composeRepair(transformed.b, repair);
4208
- const after = repair.empty ? mappedAfter : repair.apply(mappedAfter);
4209
- const rest = composeRepair(transformed.a, repair);
4210
- const carried = carry?.runs && landCarriedRuns(carry.runs, [{
4211
- after,
4212
- before: mappedAfter,
4213
- change: repair
4214
- }], {
4215
- after,
4216
- before: mapping.after,
4217
- change
4218
- });
4219
- return {
4220
- keptWrap,
4221
- replay: {
4222
- ...asReplay(change, () => {
4223
- const runs = exactRunsOf(carried ?? void 0, change, mapping.after, after);
4224
- return {
4225
- structure: change,
4226
- format: recorded.format,
4227
- after,
4228
- ...runs ? { runs } : {}
4229
- };
4230
- }),
4231
- after,
4232
- ...carried ? { carried } : {}
4233
- },
4234
- rest
4149
+ return {
4150
+ change: classifyDocumentChange(mapping.after, record().after, change),
4151
+ direction: replay.direction,
4152
+ exact,
4153
+ record
4235
4154
  };
4236
- }
4237
- const middle = middleOf();
4238
- const mappedMiddle = transformed.b.apply(mapping.after);
4239
- const format = /* @__PURE__ */ new Map();
4240
- for (const [root, spans] of recorded.format) {
4241
- const letters = carry?.letters?.root === root ? carry.letters : void 0;
4242
- const correspondence = createCharacterCorrespondence(middle, mappedMiddle, transformed.a, root, exact, letters?.letterAt);
4243
- format.set(root, spans.flatMap((span) => correspondence.fragments(span).map(({ target }) => ({
4244
- ...target,
4245
- writes: span.writes
4246
- }))));
4247
- }
4248
- const formatted = applyFormatIntent(schema, mappedMiddle, format, replay.direction);
4249
- const formatWrites = DocumentChange.between(mappedMiddle, formatted, { isSetValued: schema.isSetValued });
4250
- const formattedChange = format.size ? transformed.b.compose(formatWrites) : transformed.b;
4251
- const repair = schema.repairCanonical(mapping.after, formattedChange, formatted);
4252
- const change = composeRepair(formattedChange, repair);
4253
- const after = repair.empty ? formatted : repair.apply(formatted);
4254
- const carried = carry?.runs && landCarriedRuns(carry.runs, [{
4255
- after: formatted,
4256
- before: mappedMiddle,
4257
- change: formatWrites
4258
- }, {
4155
+ };
4156
+ const recorded = replay.record();
4157
+ const structureAfter = recorded.structureAfter ?? recorded.after;
4158
+ const carry = replay.carried && !exact && recorded.runs ? carryReplay(schema, recorded.runs, recorded, base, structureAfter, mapping, stepRules) : null;
4159
+ const pureFormat = !carry && (stepRules.anchor || exact === "rest") ? isPureV4FormatChange(base, replay.change, recorded.after, schema.isSetValued, stepRules.anchor && !exact) : false;
4160
+ const v4Mapped = !carry && (!stepRules.anchor || pureFormat) && (!exact || exact === "rest" && pureFormat) ? tryV4HistoryRebase(base, mapping.change, mapping.after, replay.change, recorded.after, schema.isSetValued, false, rules.canRemoveEmptyParent === true) : null;
4161
+ const transformed = carry ?? (v4Mapped ? {
4162
+ a: v4Mapped.a,
4163
+ b: v4Mapped.b,
4164
+ keptWrap: null
4165
+ } : replayOver(schema, mapping.change, replayedStructure(replay, recorded, base, mapping), base, stepRules));
4166
+ const { keptWrap } = transformed;
4167
+ const mappedStructureAfter = carry || v4Mapped ? transformed.b.apply(mapping.after) : transformed.a.apply(structureAfter);
4168
+ let mappedB = transformed.b;
4169
+ let mappedA = transformed.a;
4170
+ let mappedAfter = mappedStructureAfter;
4171
+ let mappedFormat = null;
4172
+ if ((carry || exact === "rest") && recorded.format) {
4173
+ const structRepair = schema.repairCanonical(mapping.after, transformed.b, mappedStructureAfter);
4174
+ const repairedStructB = composeRepair(transformed.b, structRepair);
4175
+ const repairedStructA = composeRepair(transformed.a, structRepair);
4176
+ const repairedStructAfter = structRepair.empty ? mappedStructureAfter : structRepair.apply(mappedStructureAfter);
4177
+ const fmtTransformed = (carry?.letters ? rebaseCarriedFormatViaLetters(structureAfter, recorded.format, recorded.after, carry.letters, structRepair, repairedStructA, repairedStructAfter, schema.isSetValued) : null) ?? tryV4HistoryRebase(structureAfter, repairedStructA, repairedStructAfter, recorded.format, recorded.after, schema.isSetValued) ?? replayOver(schema, repairedStructA, recorded.format, structureAfter, stepRules);
4178
+ mappedFormat = structRepair.empty ? fmtTransformed.b : structRepair.compose(fmtTransformed.b);
4179
+ mappedB = repairedStructB.compose(fmtTransformed.b);
4180
+ mappedA = fmtTransformed.a;
4181
+ mappedAfter = fmtTransformed.b.apply(repairedStructAfter);
4182
+ }
4183
+ const repair = schema.repairCanonical(mapping.after, mappedB, mappedAfter);
4184
+ const change = composeRepair(mappedB, repair);
4185
+ const after = repair.empty ? mappedAfter : repair.apply(mappedAfter);
4186
+ const rest = composeRepair(mappedA, repair);
4187
+ const landingSteps = [...mappedFormat ? [{
4188
+ after: mappedAfter,
4189
+ before: mappedStructureAfter,
4190
+ change: mappedFormat
4191
+ }] : [], {
4259
4192
  after,
4260
- before: formatted,
4193
+ before: mappedAfter,
4261
4194
  change: repair
4262
- }], {
4195
+ }];
4196
+ const carried = carry?.runs && landCarriedRuns(carry.runs, landingSteps, {
4263
4197
  after,
4264
4198
  before: mapping.after,
4265
4199
  change
4266
4200
  });
4267
- const formatChange = DocumentChange.between(middle, recorded.after, { isSetValued: schema.isSetValued });
4268
- const mapped = transformInternalDocumentChange(transformed.a, formatChange, middle, { keepRecordWrites: true }).a;
4269
- const intermediate = mapped.apply(recorded.after);
4270
- const rest = composeRepair(mapped.compose(DocumentChange.between(intermediate, formatted, { isSetValued: schema.isSetValued })), repair);
4271
- const replayed = asReplay(change, () => {
4272
- const runs = exactRunsOf(carry?.runs ?? void 0, transformed.b, mapping.after, mappedMiddle);
4273
- return {
4274
- structure: transformed.b,
4275
- format,
4276
- after,
4277
- ...runs ? { runs } : {}
4278
- };
4279
- });
4280
4201
  return {
4281
4202
  keptWrap,
4282
- replay: carried ? {
4283
- ...replayed,
4284
- carried
4285
- } : replayed,
4286
- rest
4287
- };
4288
- };
4289
- const mapHistorySelection = (editor, selection, change, before, after, root, exact = false) => {
4290
- if (!selection || !SelectionApi.isText(selection)) return mapSelectionThroughChange(editor, selection, change, before, after, root).selection;
4291
- const correspondence = createCharacterCorrespondence(before, after, change, root, exact);
4292
- const anchor = correspondence.point(selection.anchor, -1);
4293
- const focus = correspondence.point(selection.focus, -1);
4294
- if (!anchor || !focus) return mapSelectionThroughChange(editor, selection, change, before, after, root).selection;
4295
- return {
4296
- ...selection,
4297
- anchor: {
4298
- ...selection.anchor,
4299
- ...anchor
4203
+ replay: {
4204
+ ...asReplay(change, () => recordReplay(schema, mapping.after, change, {
4205
+ after,
4206
+ carried: carried ?? void 0,
4207
+ exact: exact === "rest",
4208
+ maybeFormatted: Boolean((carry || exact === "rest") && recorded.format)
4209
+ })),
4210
+ after,
4211
+ ...carried ? { carried } : {}
4300
4212
  },
4301
- focus: {
4302
- ...selection.focus,
4303
- ...focus
4304
- }
4213
+ rest
4305
4214
  };
4306
4215
  };
4216
+ const mapHistorySelection = (editor, selection, change, before, after, root, exact = false) => mapTextSelectionViaV4(editor, selection, change, before, after, root, exact);
4307
4217
  //#endregion
4308
4218
  //#region src/history/history-carets.ts
4309
4219
  const keyedHistoryCarets = (carets, before, after) => ({
@@ -4540,7 +4450,20 @@ const getCollapsedPoint = (selection, fallbackRoot, root) => {
4540
4450
  path: Object.freeze([...point.path])
4541
4451
  }) : null;
4542
4452
  };
4543
- const selectionIsExpandedInRoot = (selection, fallbackRoot, root) => Boolean(selection && RangeApi.isRange(selection) && !RangeApi.isCollapsed(selection) && (selection.anchor.root ?? fallbackRoot) === root && (selection.focus.root ?? fallbackRoot) === root);
4453
+ const getTextAtPath = (nodes, path) => {
4454
+ if (path.length === 0) return null;
4455
+ let current = nodes[path[0]];
4456
+ for (let index = 1; index < path.length; index += 1) {
4457
+ if (!current || !ElementApi.isElement(current)) return null;
4458
+ current = current.children[path[index]];
4459
+ }
4460
+ return current && TextApi.isText(current) ? current.text : null;
4461
+ };
4462
+ const selectionReplacesContentInRoot = (selection, fallbackRoot, root) => {
4463
+ if (!selection) return false;
4464
+ if (SelectionApi.isNode(selection)) return (SelectionApi.root(selection) ?? fallbackRoot) === root;
4465
+ return Boolean(RangeApi.isRange(selection) && !RangeApi.isCollapsed(selection) && (selection.anchor.root ?? fallbackRoot) === root && (selection.focus.root ?? fallbackRoot) === root);
4466
+ };
4544
4467
  const getTarget = (commit, root, path) => {
4545
4468
  const nodeKeys = commit.changed.nodeKeys("text", toPublicRoot(root));
4546
4469
  if (!path && nodeKeys.length !== 1) return null;
@@ -4607,7 +4530,7 @@ const createHistoryBatchGroup = (commit) => {
4607
4530
  const range = ranges.length === 1 ? ranges[0] : null;
4608
4531
  const changedSpan = getChangedSpan(ranges);
4609
4532
  const changedPath = getDeepestChangedPath(commit.changed.paths(publicRoot));
4610
- const replacedSelection = selectionIsExpandedInRoot(commit.selectionBefore, commit.selectionBeforeRoot ?? "main", root);
4533
+ const replacedSelection = selectionReplacesContentInRoot(commit.selectionBefore, commit.selectionBeforeRoot ?? "main", root);
4611
4534
  const afterPoint = getCollapsedPoint(commit.selectionAfter, commit.selectionAfterRoot ?? "main", root);
4612
4535
  const beforePoint = getCollapsedPoint(commit.selectionBefore, commit.selectionBeforeRoot ?? "main", root);
4613
4536
  if (recordedDelete) {
@@ -4636,10 +4559,28 @@ const createHistoryBatchGroup = (commit) => {
4636
4559
  if (fallbackPropertyGroup) return fallbackPropertyGroup;
4637
4560
  }
4638
4561
  const selectionStart = RangeApi.isRange(commit.selectionBefore) ? RangeApi.edges(commit.selectionBefore)[0] : null;
4639
- const structuralReplacementInsertedText = Boolean(selectionStart && afterPoint && (selectionStart.root ?? commit.selectionBeforeRoot ?? "main") === root && isSameHistoryPath(selectionStart.path, afterPoint.path) && afterPoint.offset > selectionStart.offset);
4640
4562
  const textChanged = commit.changed.has("text", publicRoot);
4641
4563
  const structureChanged = commit.changed.has("structure", publicRoot);
4642
4564
  const propertiesChanged = commit.changed.has("properties", publicRoot);
4565
+ const textNodeKeys = commit.changed.nodeKeys("text", publicRoot);
4566
+ const opened = structureChanged ? commit.changed.nodeKeys("presence", publicRoot) : [];
4567
+ let afterLeafKey = null;
4568
+ let structuralReplacementInsertedText = false;
4569
+ if (replacedSelection && structureChanged && afterPoint) {
4570
+ const afterSnapshot = getEditorCommitSnapshot(commit, root, "after");
4571
+ afterLeafKey = afterSnapshot.index.keyAt(afterPoint.path);
4572
+ if (selectionStart && (selectionStart.root ?? commit.selectionBeforeRoot ?? "main") === root && isSameHistoryPath(selectionStart.path, afterPoint.path) && afterPoint.offset > selectionStart.offset) structuralReplacementInsertedText = true;
4573
+ else if (afterPoint.offset > 0 && afterLeafKey && textNodeKeys.includes(afterLeafKey) && (SelectionApi.isNode(commit.selectionBefore) ? textNodeKeys.length === 1 : opened.every((key) => textNodeKeys.includes(key)))) {
4574
+ const afterText = getTextAtPath(afterSnapshot.children, afterPoint.path);
4575
+ if (afterText !== null) if (opened.includes(afterLeafKey)) structuralReplacementInsertedText = true;
4576
+ else {
4577
+ const beforeSnapshot = getEditorCommitSnapshot(commit, root, "before");
4578
+ const beforeLeafPath = beforeSnapshot.index.pathOf(afterLeafKey);
4579
+ const beforeText = beforeLeafPath ? getTextAtPath(beforeSnapshot.children, beforeLeafPath) : null;
4580
+ structuralReplacementInsertedText = beforeText !== null && afterText.length > beforeText.length;
4581
+ }
4582
+ }
4583
+ }
4643
4584
  const textTarget = getTarget(commit, root, changedPath ?? afterPoint?.path ?? beforePoint?.path ?? null);
4644
4585
  if (changedSpan && replacedSelection && structuralReplacementInsertedText && afterPoint && structureChanged) return Object.freeze({
4645
4586
  afterPoint,
@@ -4650,12 +4591,14 @@ const createHistoryBatchGroup = (commit) => {
4650
4591
  mode: "structural-replace",
4651
4592
  replacedSelection: true,
4652
4593
  root,
4653
- target: getTarget(commit, root, afterPoint.path) ?? failInvariant$1("Expected value to be defined"),
4594
+ target: Object.freeze({
4595
+ path: pathKey(afterPoint.path),
4596
+ ...afterLeafKey ? { nodeKey: afterLeafKey } : {}
4597
+ }),
4654
4598
  toAfter: changedSpan[3],
4655
4599
  toBefore: changedSpan[1]
4656
4600
  });
4657
- const opened = structureChanged ? commit.changed.nodeKeys("presence", publicRoot) : [];
4658
- const opensLeaf = !replacedSelection && opened.length > 0 && opened.every((key) => commit.changed.nodeKeys("text", publicRoot).includes(key));
4601
+ const opensLeaf = !replacedSelection && opened.length > 0 && opened.every((key) => textNodeKeys.includes(key));
4659
4602
  if (range && textTarget && (opensLeaf || textChanged && !structureChanged) && !propertiesChanged) {
4660
4603
  const beforeLength = range[1] - range[0];
4661
4604
  const afterLength = range[3] - range[2];
@@ -4932,17 +4875,18 @@ const publishStore = (editor, store, patch) => {
4932
4875
  setStore$1(editor, next);
4933
4876
  return next;
4934
4877
  };
4935
- //#endregion
4936
- //#region src/history/history-state.ts
4937
- const stepBranchTracks = (value, commit, otherWriter) => stepBranchTracks$1(value, commit, otherWriter, withKeptBranch);
4938
- const KEPT_REDO_ATTEMPTS = /* @__PURE__ */ new Map();
4939
- const getStore = (editor) => getStore$1(editor);
4940
- const captureHistoryState = (editor) => captureHistoryState$1(editor);
4941
- const setStore = (editor, store) => setStore$1(editor, store);
4942
- const publish = (editor, store, patch) => publishStore(editor, store, {
4943
- ...patch,
4944
- ...trimmedRedoOf(store, patch)
4945
- });
4878
+ const DROPPED_HISTORY_CAUSES = /* @__PURE__ */ new WeakMap();
4879
+ const recordDroppedCause = (editor, cause) => {
4880
+ const causes = DROPPED_HISTORY_CAUSES.get(editor) ?? [];
4881
+ causes.push(cause);
4882
+ DROPPED_HISTORY_CAUSES.set(editor, causes);
4883
+ countCoreWork("carriedFallbacks");
4884
+ };
4885
+ const takeDroppedHistoryCauses = (editor) => {
4886
+ const causes = DROPPED_HISTORY_CAUSES.get(editor) ?? [];
4887
+ DROPPED_HISTORY_CAUSES.delete(editor);
4888
+ return causes;
4889
+ };
4946
4890
  const HISTORY_FALLBACKS = /* @__PURE__ */ new WeakMap();
4947
4891
  const withHistoryFallback = (batch, fallback) => {
4948
4892
  HISTORY_FALLBACKS.set(batch, fallback);
@@ -4955,6 +4899,120 @@ const historyFallbackOf = (batch) => {
4955
4899
  HISTORY_FALLBACKS.set(batch, mapped);
4956
4900
  return mapped;
4957
4901
  };
4902
+ //#endregion
4903
+ //#region src/history/history-superseded-effects.ts
4904
+ const journalEntries = (journal) => {
4905
+ const entries = [];
4906
+ for (let item = journal; item; item = item.previous) entries.push(item.entry);
4907
+ return entries.reverse();
4908
+ };
4909
+ const collectSupersededEffectKeys$1 = (entries) => {
4910
+ let combined = null;
4911
+ let single;
4912
+ for (const entry of entries) {
4913
+ const keys = entry.supersededEffectKeys;
4914
+ if (!keys || keys.size === 0) continue;
4915
+ if (!single && !combined) {
4916
+ single = keys;
4917
+ continue;
4918
+ }
4919
+ if (!combined) {
4920
+ combined = new Set(single);
4921
+ single = void 0;
4922
+ }
4923
+ for (const key of keys) combined.add(key);
4924
+ }
4925
+ return combined ?? single;
4926
+ };
4927
+ const appendPendingMapping = (previous, entry, carries) => {
4928
+ const coalescedSuperseded = previous?.entry.change.empty && entry.change.empty && previous.entry.supersededEffectKeys && entry.supersededEffectKeys ? collectSupersededEffectKeys$1([previous.entry, entry]) : void 0;
4929
+ if (coalescedSuperseded && previous) return Object.freeze({
4930
+ entry: Object.freeze({
4931
+ after: entry.after,
4932
+ change: DocumentChange.empty,
4933
+ supersededEffectKeys: coalescedSuperseded,
4934
+ textOnly: false
4935
+ }),
4936
+ previous: previous.previous
4937
+ });
4938
+ if (!carries && previous?.entry.textOnly && entry.textOnly) return Object.freeze({
4939
+ entry: Object.freeze({
4940
+ after: entry.after,
4941
+ change: previous.entry.change.compose(entry.change),
4942
+ textOnly: true
4943
+ }),
4944
+ previous: previous.previous
4945
+ });
4946
+ return Object.freeze({
4947
+ entry,
4948
+ previous
4949
+ });
4950
+ };
4951
+ const mapBatchEffects = (effects, mapping) => effects.flatMap((effect) => {
4952
+ if (mapping.supersededEffectKeys?.has(effect.type.key)) return [];
4953
+ const mappedEffect = mapEffect(effect, mapping.change);
4954
+ return mappedEffect ? [mappedEffect] : [];
4955
+ });
4956
+ const applyEmptyChangeMapping = (batchValue, next, nextBase, mapping, freezeBatch, attach) => {
4957
+ const superseded = mapping.supersededEffectKeys;
4958
+ if (!superseded || superseded.size === 0) return {
4959
+ batchValue,
4960
+ next
4961
+ };
4962
+ const effects = batchValue.effects.filter((effect) => !superseded.has(effect.type.key));
4963
+ return {
4964
+ batchValue: effects.length === batchValue.effects.length ? batchValue : withHistoryProgram(freezeBatch({
4965
+ ...batchValue,
4966
+ effects
4967
+ }), historyProgramOf(batchValue)),
4968
+ next: attach(next, {
4969
+ after: nextBase,
4970
+ change: DocumentChange.empty,
4971
+ supersededEffectKeys: superseded,
4972
+ textOnly: false
4973
+ })
4974
+ };
4975
+ };
4976
+ const buildPropagatedMapping = (after, change, supersededEffectKeys, crossing) => {
4977
+ if (change.empty && !supersededEffectKeys) return null;
4978
+ return {
4979
+ after,
4980
+ change,
4981
+ textOnly: false,
4982
+ ...crossing && !change.empty ? { crossing } : {},
4983
+ ...supersededEffectKeys ? { supersededEffectKeys } : {}
4984
+ };
4985
+ };
4986
+ const buildQueuedHistoryMapping = (after, change, crosses, facts, supersededEffectKeys, textOnly) => Object.freeze({
4987
+ after,
4988
+ ...change.empty ? {} : { anchors: true },
4989
+ change,
4990
+ ...supersededEffectKeys ? { supersededEffectKeys } : {},
4991
+ textOnly: !supersededEffectKeys && textOnly,
4992
+ ...crosses ? { crossing: facts } : {}
4993
+ });
4994
+ const forwardedSupersededMapping = (from, next) => {
4995
+ if (!next || !from.mappings) return null;
4996
+ const supersededEffectKeys = collectSupersededEffectKeys$1(journalEntries(from.mappings));
4997
+ if (!supersededEffectKeys) return null;
4998
+ return {
4999
+ after: next.mappings?.entry.after ?? next.base,
5000
+ change: DocumentChange.empty,
5001
+ supersededEffectKeys,
5002
+ textOnly: false
5003
+ };
5004
+ };
5005
+ //#endregion
5006
+ //#region src/history/history-state.ts
5007
+ const stepBranchTracks = (value, commit, otherWriter) => stepBranchTracks$1(value, commit, otherWriter, withKeptBranch);
5008
+ const KEPT_REDO_ATTEMPTS = /* @__PURE__ */ new Map();
5009
+ const getStore = (editor) => getStore$1(editor);
5010
+ const captureHistoryState = (editor) => captureHistoryState$1(editor);
5011
+ const setStore = (editor, store) => setStore$1(editor, store);
5012
+ const publish = (editor, store, patch) => publishStore(editor, store, {
5013
+ ...patch,
5014
+ ...trimmedRedoOf(store, patch)
5015
+ });
4958
5016
  const outsideFallbackCount = (run) => {
4959
5017
  const fallbacks = readCoreWork().carriedFallbacks;
4960
5018
  const result = run();
@@ -4993,31 +5051,47 @@ const replayedOf = (batch) => ({
4993
5051
  unsettle: batch.unsettle
4994
5052
  } : void 0
4995
5053
  });
5054
+ const attachHistoryLazyV4 = (change, base) => {
5055
+ if (hasV4StepsSource(change)) return;
5056
+ attachLazyV4Compute(change, () => extractV4Between(base, change.apply(base), { isSetValued: (_node, key) => key === "authored" }));
5057
+ };
4996
5058
  const branch = (batch, base, replay, next, mappings = null, group = null, recovery = null, anchorCeiling = 0, identity = {}, carets = null, kept = null, origin = Object.freeze({
4997
5059
  base,
4998
5060
  change: replay.change,
4999
5061
  outside: null,
5000
5062
  track: null
5001
- })) => Object.freeze({
5002
- anchorCeiling,
5003
- base,
5004
- batch: withHistoryStep(withHistoryFacts(withHistoryProgram(freezeBatch({
5005
- ...batch,
5006
- change: replay.change
5007
- }), replay.program), replay.change === batch.change ? historyFactsOf(batch) : void 0), identity),
5008
- carets,
5009
- carries: replay.carried !== void 0 || (next?.carries ?? false),
5010
- replay,
5011
- depth: (next?.depth ?? 0) + 1,
5012
- group,
5013
- hasActiveTrack: branchHasActiveTrack(origin, next, kept),
5014
- identity,
5015
- kept,
5016
- mappings,
5017
- next,
5018
- origin,
5019
- recovery
5020
- });
5063
+ })) => {
5064
+ attachHistoryLazyV4(replay.change, base);
5065
+ if (batch.unsettle) attachHistoryLazyV4(batch.unsettle, base);
5066
+ if (batch.rest && !hasV4StepsSource(batch.rest)) {
5067
+ const restChange = batch.rest;
5068
+ const unsettleChange = batch.unsettle;
5069
+ attachLazyV4Compute(restChange, () => {
5070
+ const restBase = unsettleChange ? unsettleChange.apply(base) : base;
5071
+ return extractV4Between(restBase, restChange.apply(restBase), { isSetValued: (_node, key) => key === "authored" });
5072
+ });
5073
+ }
5074
+ return Object.freeze({
5075
+ anchorCeiling,
5076
+ base,
5077
+ batch: withHistoryStep(withHistoryFacts(withHistoryProgram(freezeBatch({
5078
+ ...batch,
5079
+ change: replay.change
5080
+ }), replay.program), replay.change === batch.change ? historyFactsOf(batch) : void 0), identity),
5081
+ carets,
5082
+ carries: replay.carried !== void 0 || (next?.carries ?? false),
5083
+ replay,
5084
+ depth: (next?.depth ?? 0) + 1,
5085
+ group,
5086
+ hasActiveTrack: branchHasActiveTrack(origin, next, kept),
5087
+ identity,
5088
+ kept,
5089
+ mappings,
5090
+ next,
5091
+ origin,
5092
+ recovery
5093
+ });
5094
+ };
5021
5095
  const withKeptBranch = (kept, change) => {
5022
5096
  if (!kept) return null;
5023
5097
  if (kept.kind === "fallback") {
@@ -5053,29 +5127,12 @@ const pushBranch = (value, batchValue, base, replay, maxDepth, group = null, rec
5053
5127
  const addMapping = (value, entry) => {
5054
5128
  if (!value) return null;
5055
5129
  countCoreWork("historyMappingNodes");
5056
- const previous = value.mappings;
5057
- const mappings = !value.carries && previous?.entry.textOnly && entry.textOnly ? Object.freeze({
5058
- entry: Object.freeze({
5059
- after: entry.after,
5060
- change: previous.entry.change.compose(entry.change),
5061
- textOnly: true
5062
- }),
5063
- previous: previous.previous
5064
- }) : Object.freeze({
5065
- entry,
5066
- previous
5067
- });
5068
5130
  return Object.freeze({
5069
5131
  ...value,
5070
5132
  kept: withKeptBranch(value.kept, (other) => addMapping(other, entry)),
5071
- mappings
5133
+ mappings: appendPendingMapping(value.mappings, entry, value.carries)
5072
5134
  });
5073
5135
  };
5074
- const journalEntries = (journal) => {
5075
- const entries = [];
5076
- for (let item = journal; item; item = item.previous) entries.push(item.entry);
5077
- return entries.reverse();
5078
- };
5079
5136
  const retainMappedCompositionGroup = (group) => {
5080
5137
  if (group?.native?.composition === void 0) return null;
5081
5138
  const shared = {
@@ -5094,62 +5151,6 @@ const retainMappedCompositionGroup = (group) => {
5094
5151
  };
5095
5152
  const yieldTo = (change, edit, base) => transformInternalDocumentChange(change, edit, base, { keepRecordWrites: true }).a;
5096
5153
  const crossingDropCount = (editor) => captureHistoryState(editor)?.crossingDrops ?? 0;
5097
- const changedRootIndexes = (value, change) => new Map(getInternalDocumentChangeRootKeys(change).map((root) => [root, valueRootIndex(value, root)]));
5098
- const crossOrDrop = (editor, drops, replay, base, facts, mapping, crossing) => {
5099
- countCoreWork("crossedSteps");
5100
- try {
5101
- if (!facts) throw new Error("A crossing reached a step with no facts.");
5102
- const { followed, leftover } = crossRecord(base, {
5103
- change: replay.change,
5104
- facts
5105
- }, {
5106
- change: mapping.change,
5107
- facts: crossing
5108
- });
5109
- const after = followed.change.apply(mapping.after);
5110
- getEditorSchema(editor).checkDocumentChange({
5111
- after,
5112
- before: mapping.after,
5113
- change: followed.change,
5114
- indexedAfter: changedRootIndexes(after, followed.change),
5115
- indexedBefore: changedRootIndexes(mapping.after, followed.change)
5116
- });
5117
- const change = classifyDocumentChange(mapping.after, after, followed.change);
5118
- return {
5119
- facts: followed.facts,
5120
- kind: "crossed",
5121
- keptWrap: null,
5122
- projected: false,
5123
- readBack: false,
5124
- replay: recordHistoryReplay(historyReplaySchemaOf(editor), mapping.after, change, replay.direction, { after }),
5125
- rest: leftover.change,
5126
- restFacts: leftover.facts
5127
- };
5128
- } catch (error) {
5129
- drops.push({
5130
- cause: error,
5131
- direction: replay.direction,
5132
- editor
5133
- });
5134
- return { kind: "dropped" };
5135
- }
5136
- };
5137
- const headAfterDrop = (editor, value, target) => {
5138
- const { next } = value;
5139
- const from = next?.mappings?.entry.after ?? next?.base;
5140
- const correction = next && from ? DocumentChange.between(from, target, { isSetValued: historyReplaySchemaOf(editor).isSetValued }) : DocumentChange.empty;
5141
- return {
5142
- head: correction.empty ? next : addMapping(next, {
5143
- after: target,
5144
- change: correction,
5145
- textOnly: isTextOnlyMapping(correction)
5146
- }),
5147
- keptWrap: null,
5148
- projected: false,
5149
- projectedAfterReadBack: false,
5150
- readBack: false
5151
- };
5152
- };
5153
5154
  const mapHead = (editor, drops, value, { anchor, readBack: reads }, count = Number.POSITIVE_INFINITY) => {
5154
5155
  if (!value.mappings) return {
5155
5156
  head: value,
@@ -5159,6 +5160,7 @@ const mapHead = (editor, drops, value, { anchor, readBack: reads }, count = Numb
5159
5160
  readBack: false
5160
5161
  };
5161
5162
  let keptWrap = null;
5163
+ let mappedDocument = false;
5162
5164
  let readBack = false;
5163
5165
  let projected = false;
5164
5166
  let projectedAfterReadBack = false;
@@ -5170,15 +5172,21 @@ const mapHead = (editor, drops, value, { anchor, readBack: reads }, count = Numb
5170
5172
  let { carets, recovery } = value;
5171
5173
  let batchFacts = historyFactsOf(value.batch);
5172
5174
  const entries = journalEntries(value.mappings);
5173
- for (const mapping of entries.slice(0, count)) {
5175
+ const limit = Math.min(entries.length, count);
5176
+ for (let index = 0; index < limit; index += 1) {
5177
+ const mapping = entries[index];
5174
5178
  const nextBase = replay.record().after;
5175
- const crossed = mapping.crossing ? crossOrDrop(editor, drops, replay, batchBase, batchFacts, mapping, mapping.crossing) : null;
5176
- if (crossed?.kind === "dropped") return headAfterDrop(editor, value, (entries.at(-1) ?? mapping).after);
5177
- const mapped = crossed ?? mapHistoryReplay(historyReplaySchemaOf(editor), replay, batchBase, mapping, {
5179
+ if (mapping.change.empty) {
5180
+ ({batchValue, next} = applyEmptyChangeMapping(batchValue, next, nextBase, mapping, freezeBatch, addMapping));
5181
+ continue;
5182
+ }
5183
+ if (!isInternalRecordsOnlyChange(mapping.change)) mappedDocument = true;
5184
+ const mapped = mapHistoryReplay(historyReplaySchemaOf(editor), replay, batchBase, mapping, {
5178
5185
  anchor: anchor && mapping.anchors === true,
5186
+ canRemoveEmptyParent: next === null,
5179
5187
  readBack: reads
5180
5188
  });
5181
- batchFacts = crossed?.facts;
5189
+ batchFacts = void 0;
5182
5190
  keptWrap ??= mapped.keptWrap;
5183
5191
  projected ||= mapped.projected;
5184
5192
  projectedAfterReadBack ||= readBack && mapped.projected;
@@ -5196,7 +5204,7 @@ const mapHead = (editor, drops, value, { anchor, readBack: reads }, count = Numb
5196
5204
  after: mappedNextBase,
5197
5205
  before: nextBase,
5198
5206
  change: mapped.rest,
5199
- facts: crossed?.restFacts ?? null
5207
+ facts: null
5200
5208
  };
5201
5209
  const sides = replay.direction === "undo" ? {
5202
5210
  after: batchEdge,
@@ -5219,31 +5227,24 @@ const mapHead = (editor, drops, value, { anchor, readBack: reads }, count = Numb
5219
5227
  ...parts ?? (unsettle && !unsettle.empty ? { unsettle } : {}),
5220
5228
  ...replay.carried ? { carried: replay.carried } : {},
5221
5229
  change: replay.change,
5222
- effects: batchValue.effects.flatMap((effect) => {
5223
- const mappedEffect = mapEffect(effect, mapping.change);
5224
- return mappedEffect ? [mappedEffect] : [];
5225
- }),
5230
+ effects: mapBatchEffects(batchValue.effects, mapping),
5226
5231
  selectionAfter: mapHistorySelection(editor, batchValue.selectionAfter, sides.after.change, sides.after.before, sides.after.after, batchValue.selectionAfterRoot ?? "main"),
5227
5232
  selectionBefore: mapHistorySelection(editor, batchValue.selectionBefore, sides.before.change, sides.before.before, sides.before.after, batchValue.selectionBeforeRoot ?? "main")
5228
5233
  });
5229
- if (!mapped.rest.empty) next = addMapping(next, {
5230
- after: mappedNextBase,
5231
- change: mapped.rest,
5232
- textOnly: false,
5233
- ...crossed ? { crossing: crossed.restFacts } : {}
5234
- });
5234
+ const propagated = buildPropagatedMapping(mappedNextBase, mapped.rest, mapping.supersededEffectKeys, void 0);
5235
+ if (propagated) next = addMapping(next, propagated);
5235
5236
  if (value.origin) outside = outside ? outside.compose(mapping.change, value.origin.base) : mapping.change;
5236
5237
  batchBase = mappedBatchBase;
5237
5238
  }
5238
5239
  const later = entries.slice(count);
5239
- const empty = batchValue.change.empty && batchValue.effects.length === 0;
5240
+ const empty = !(value.batch.change.empty && value.batch.effects.length === 0) && batchValue.change.empty && batchValue.effects.length === 0;
5240
5241
  if (empty) for (const mapping of later) next = addMapping(next, mapping);
5241
5242
  else countCoreWork("historyBranchRebuilds");
5242
5243
  return {
5243
5244
  head: empty ? next : branch(withHistoryFacts(batchValue, batchFacts), batchBase, replay, next, later.reduce((previous, entry) => Object.freeze({
5244
5245
  entry,
5245
5246
  previous
5246
- }), null), retainMappedCompositionGroup(value.group), recovery, value.anchorCeiling, value.identity, carets, null, value.origin ? Object.freeze({
5247
+ }), null), mappedDocument ? retainMappedCompositionGroup(value.group) : value.group, recovery, value.anchorCeiling, value.identity, carets, null, value.origin ? Object.freeze({
5247
5248
  ...value.origin,
5248
5249
  outside
5249
5250
  }) : null),
@@ -5303,13 +5304,8 @@ const resolveProgramHead = (editor, drops, value, readBack) => {
5303
5304
  readBack: mapped.readBack
5304
5305
  };
5305
5306
  };
5306
- const crossFirstMapping = (editor, drops, value) => mapHead(editor, drops, value, {
5307
- anchor: false,
5308
- readBack: false
5309
- }, 1).head;
5310
5307
  const resolveHead = (editor, drops, value) => {
5311
5308
  if (!value.mappings) return value;
5312
- if (journalEntries(value.mappings)[0]?.crossing) return crossFirstMapping(editor, drops, value);
5313
5309
  const earlier = value.kept?.kind === "fallback" ? value.kept.plain : null;
5314
5310
  const current = earlier ? Object.freeze({
5315
5311
  ...value,
@@ -5341,10 +5337,24 @@ const plainOf = (editor, value) => {
5341
5337
  const { head } = outsideFallbackCount(() => resolveByRules(editor, [], value, false));
5342
5338
  return head?.identity === value.identity ? head : value;
5343
5339
  };
5340
+ const sameInternalChange = (left, right) => {
5341
+ if (left === right) return true;
5342
+ if (left.createRoots.size !== right.createRoots.size || left.deleteRoots.size !== right.deleteRoots.size) return false;
5343
+ for (const root of left.createRoots) if (!right.createRoots.has(root)) return false;
5344
+ for (const root of left.deleteRoots) if (!right.deleteRoots.has(root)) return false;
5345
+ const leftEntries = new Map(getInternalDocumentChangeEntries(left));
5346
+ const rightEntries = new Map(getInternalDocumentChangeEntries(right));
5347
+ if (leftEntries.size !== rightEntries.size) return false;
5348
+ for (const [root, rootChange] of leftEntries) {
5349
+ const other = rightEntries.get(root);
5350
+ if (!other || !jsonEqual(rootChange.toJSON(), other.toJSON())) return false;
5351
+ }
5352
+ return jsonEqual(recordOpsToJson(getInternalDocumentChangeRecords(left)), recordOpsToJson(getInternalDocumentChangeRecords(right)));
5353
+ };
5344
5354
  const plainFallback = (editor, drops, shown) => {
5345
5355
  if (shown.kept?.kind !== "fallback") return null;
5346
5356
  const { head: plain } = resolveByRules(editor, drops, shown.kept.plain, false);
5347
- return plain && plain.identity === shown.identity && !jsonEqual(plain.replay.change.toJSON(), shown.replay.change.toJSON()) ? plain : null;
5357
+ return plain && plain.identity === shown.identity && !sameInternalChange(plain.replay.change, shown.replay.change) ? plain : null;
5348
5358
  };
5349
5359
  const resolveByRules = (editor, drops, value, readBack) => {
5350
5360
  if (!value.mappings) return {
@@ -5463,7 +5473,7 @@ const listBatches = (editor, drops, value, shows) => {
5463
5473
  let current = resolveTop(editor, drops, value);
5464
5474
  while (current) {
5465
5475
  const shown = shows === "program" && current.kept?.kind === "program" ? current.kept.branch : current;
5466
- if (shown !== current && !jsonEqual(current.replay.change.toJSON(), shown.replay.change.toJSON())) HISTORY_FALLBACKS.set(shown.batch, current.batch);
5476
+ if (shown !== current && !sameInternalChange(current.replay.change, shown.replay.change)) HISTORY_FALLBACKS.set(shown.batch, current.batch);
5467
5477
  if (shown.kept?.kind === "fallback") {
5468
5478
  const withFallback = shown;
5469
5479
  HISTORY_FALLBACKS.set(shown.batch, () => outsideFallbackCount(() => plainFallback(editor, [], withFallback))?.batch ?? null);
@@ -5755,7 +5765,7 @@ const peekHistoryEntry = (editor, stack, request) => peekResolvedEntry(editor, s
5755
5765
  const topJoinsNothingOnceMapped = (editor) => {
5756
5766
  const head = getStore(editor).undos;
5757
5767
  const mapping = head?.mappings;
5758
- return !!head && !!mapping && !mapping.previous && !mapping.entry.crossing && !head.kept && !retainMappedCompositionGroup(head.group) && keepsUndoThrough(historyReplaySchemaOf(editor), head.replay, head.base, mapping.entry);
5768
+ return !!head && !!mapping && !mapping.previous && !mapping.entry.crossing && !mapping.entry.supersededEffectKeys && !head.kept && !retainMappedCompositionGroup(head.group) && keepsUndoThrough(historyReplaySchemaOf(editor), head.replay, head.base, mapping.entry);
5759
5769
  };
5760
5770
  const peekJoinableUndoEntry = (editor) => {
5761
5771
  if (topJoinsNothingOnceMapped(editor)) return void 0;
@@ -5882,7 +5892,7 @@ const resolveDownTo = (editor, drops, value, id) => {
5882
5892
  } catch (error) {
5883
5893
  causes.push(error);
5884
5894
  onto = above.at(-1)?.replay.record().after ?? getEditorDocumentValue(editor);
5885
- entry = entry.next;
5895
+ entry = forwardSupersededEffectKeys(entry, entry.next);
5886
5896
  continue;
5887
5897
  }
5888
5898
  if (!current) break;
@@ -5922,20 +5932,12 @@ const replaceUndoStep = (editor, id, change, matches) => {
5922
5932
  for (const cause of found.causes) recordDroppedCause(editor, cause);
5923
5933
  return true;
5924
5934
  };
5925
- const DROPPED_HISTORY_CAUSES = /* @__PURE__ */ new WeakMap();
5926
- const recordDroppedCause = (editor, cause) => {
5927
- const causes = DROPPED_HISTORY_CAUSES.get(editor) ?? [];
5928
- causes.push(cause);
5929
- DROPPED_HISTORY_CAUSES.set(editor, causes);
5930
- countCoreWork("carriedFallbacks");
5931
- };
5932
- const takeDroppedHistoryCauses = (editor) => {
5933
- const causes = DROPPED_HISTORY_CAUSES.get(editor) ?? [];
5934
- DROPPED_HISTORY_CAUSES.delete(editor);
5935
- return causes;
5935
+ const forwardSupersededEffectKeys = (from, next) => {
5936
+ const entry = forwardedSupersededMapping(from, next);
5937
+ return entry ? addMapping(next, entry) : next;
5936
5938
  };
5937
5939
  const resolveSurvivingTop = (editor, drops, value) => {
5938
- for (let entry = value; entry; entry = entry.next) {
5940
+ for (let entry = value; entry;) {
5939
5941
  const attemptDrops = [];
5940
5942
  try {
5941
5943
  const head = resolveTop(editor, attemptDrops, entry);
@@ -5943,6 +5945,7 @@ const resolveSurvivingTop = (editor, drops, value) => {
5943
5945
  return head;
5944
5946
  } catch (error) {
5945
5947
  recordDroppedCause(editor, error);
5948
+ entry = forwardSupersededEffectKeys(entry, entry.next);
5946
5949
  }
5947
5950
  }
5948
5951
  return null;
@@ -5965,7 +5968,7 @@ const dropHistoryHead = (editor, stack, current) => {
5965
5968
  const value = store[stack];
5966
5969
  if (!value) return;
5967
5970
  const drops = [];
5968
- const result = rebaseOnto(editor, drops, value.next, current);
5971
+ const result = rebaseOnto(editor, drops, forwardSupersededEffectKeys(value, value.next), current);
5969
5972
  publish(editor, withDrops(store, drops), { [stack]: result });
5970
5973
  };
5971
5974
  const completeHistoryAction = (editor, source, destination, batchValue, current, olderStepsMapping, request, commit) => {
@@ -5977,7 +5980,7 @@ const completeHistoryAction = (editor, source, destination, batchValue, current,
5977
5980
  if (!resolved) throw new Error(`Missing ${source} history batch.`);
5978
5981
  const walkedNextSource = commit ? stepBranchTracks(resolved.next, commit, false) : resolved.next;
5979
5982
  const nextSource = rebaseOnto(editor, drops, walkedNextSource, current);
5980
- const empty = batchValue.change.empty && batchValue.effects.length === 0;
5983
+ const empty = !(resolved.batch.change.empty && resolved.batch.effects.length === 0) && batchValue.change.empty && batchValue.effects.length === 0;
5981
5984
  const thaws = destination === "redos" && !empty && !!store.redoFreeze;
5982
5985
  const listed = thaws ? null : store[destination];
5983
5986
  const walkedDest = commit ? stepBranchTracks(listed, commit, false) : listed;
@@ -5992,64 +5995,21 @@ const completeHistoryAction = (editor, source, destination, batchValue, current,
5992
5995
  [source]: nextSource
5993
5996
  });
5994
5997
  };
5995
- const isTextOnlyMapping = (change) => change.createRoots.size === 0 && change.deleteRoots.size === 0 && isInternalTextOnlyDocumentChange(change);
5996
- const ELEMENT_SCHEMAS = /* @__PURE__ */ new WeakMap();
5997
- const historyElementSchemaOf = (editor) => {
5998
- const read = getEditorSchema(editor);
5999
- const known = ELEMENT_SCHEMAS.get(read);
6000
- if (known) return known;
6001
- const owner = getEditorRuntimeOwner(editor);
6002
- const contentOf = (element) => typeof element.type === "string" ? read.getElementContent(element.type) : null;
6003
- const schema = {
6004
- content: (element) => contentOf(element) ?? "unknown",
6005
- isInline: (element) => ElementApi.isElement(element) && read.isInline(element),
6006
- ownsContentRoot: (element) => typeof element.type === "string" && (getCompiledEditorSchema(owner).elements.byType.get(element.type)?.contentRoots.size ?? 0) > 0,
6007
- propertiesReadParents: () => propertyTargetsReadParents(getCompiledEditorSchema(owner)),
6008
- rootContent: (document, root) => read.getRootContent(root, document) ?? "unknown"
6009
- };
6010
- ELEMENT_SCHEMAS.set(read, schema);
6011
- return schema;
6012
- };
6013
- const holdsCarry = (facts) => facts.kind === "recorded" && [...facts.roots.values()].some(({ carries }) => carries.length > 0);
6014
- const waitsOnNothing = ({ batch, kept, mappings, replay }) => !mappings && !kept && !replay.program && !replay.carried && !replay.parts && !replay.exact && !batch.unsettle;
6015
- const crossesEveryStep = (value, schema) => {
6016
- for (let entry = value; entry; entry = entry.next) {
6017
- const facts = historyFactsOf(entry.batch);
6018
- if (!facts || !waitsOnNothing(entry) || stepRejection(entry.base, {
6019
- change: entry.replay.change,
6020
- facts
6021
- }, schema) !== null) return false;
6022
- }
6023
- return true;
6024
- };
6025
- const admits = (editor, store, skipped, before) => {
6026
- if (!holdsCarry(skipped.facts) || store.pendingReplay) return false;
6027
- const schema = historyElementSchemaOf(editor);
6028
- return skippedRejection(before, skipped, schema) === null && crossesEveryStep(store.undos, schema) && crossesEveryStep(store.redos, schema);
6029
- };
5998
+ const isTextOnlyMapping = (change) => change.createRoots.size === 0 && change.deleteRoots.size === 0 && !hasInternalDocumentChangeStepFirstAt(change) && isInternalTextOnlyDocumentChange(change);
6030
5999
  const queueHistoryMapping = (editor, change, after, skipped) => {
6031
- if (change.empty) return;
6000
+ const supersededEffectKeys = skipped.supersededEffectKeys && skipped.supersededEffectKeys.size > 0 ? skipped.supersededEffectKeys : void 0;
6001
+ if (change.empty && !supersededEffectKeys) return;
6032
6002
  const store = getStore(editor);
6033
- const crosses = admits(editor, store, {
6034
- change,
6035
- facts: skipped.facts
6036
- }, skipped.before);
6037
- if (crosses) countCoreWork("admittedChanges");
6038
- const mapping = Object.freeze({
6039
- after,
6040
- anchors: true,
6041
- change,
6042
- textOnly: isTextOnlyMapping(change),
6043
- ...crosses ? { crossing: skipped.facts } : {}
6044
- });
6003
+ if (change.empty && !store.redos && !store.undos) return;
6004
+ const mapping = buildQueuedHistoryMapping(after, change, false, skipped.facts, supersededEffectKeys, isTextOnlyMapping(change));
6045
6005
  const commit = {
6046
6006
  after,
6047
6007
  before: skipped.before,
6048
6008
  change
6049
6009
  };
6050
6010
  const otherWriter = skipped.otherWriter ?? true;
6051
- const walkedRedos = stepBranchTracks(store.redos, commit, otherWriter);
6052
- const walkedUndos = stepBranchTracks(store.undos, commit, otherWriter);
6011
+ const walkedRedos = change.empty ? store.redos : stepBranchTracks(store.redos, commit, otherWriter);
6012
+ const walkedUndos = change.empty ? store.undos : stepBranchTracks(store.undos, commit, otherWriter);
6053
6013
  publish(editor, store, {
6054
6014
  redos: addMapping(walkedRedos, mapping),
6055
6015
  undos: addMapping(walkedUndos, mapping)
@@ -6348,24 +6308,37 @@ const decodeRecord = (input) => {
6348
6308
  roots: input.record
6349
6309
  });
6350
6310
  };
6351
- const encodeBatch = (editor, batch, fallback) => ({
6352
- change: batch.change.toJSON(),
6353
- effects: batch.effects.map(encodeEditorEffect),
6354
- selectionAfter: encodeEditorSelection(editor, batch.selectionAfter, { validateDocument: false }),
6355
- ...batch.selectionAfterRoot ? { selectionAfterRoot: batch.selectionAfterRoot } : {},
6356
- selectionBefore: encodeEditorSelection(editor, batch.selectionBefore, { validateDocument: false }),
6357
- ...batch.selectionBeforeRoot ? { selectionBeforeRoot: batch.selectionBeforeRoot } : {},
6358
- ...batch.unsettle ? { unsettle: batch.unsettle.toJSON() } : {},
6359
- ...batch.rest ? { rest: batch.rest.toJSON() } : {},
6360
- ...batch.carried ? { carried: batch.carried.map(({ landed, ...run }) => landed === run.length ? run : {
6361
- ...run,
6362
- landed
6363
- }) } : {},
6364
- ...encodeRecord(historyFactsOf(batch)),
6365
- ...fallback ? { fallback: encodeBatch(editor, fallback) } : {}
6366
- });
6367
- const encodeStep = (editor, batch, fallback) => ({
6368
- ...encodeBatch(editor, batch, fallback),
6311
+ const ensureV4ChangeJson = (editor, change, base) => {
6312
+ if (!change.empty && getV4Steps(change) === null && base !== void 0) {
6313
+ const compiled = getCompiledEditorSchema(editor);
6314
+ const isSetValued = compiled ? schemaSetValuedResolver(compiled) : void 0;
6315
+ const explicitRegisters = getV4RegisterSteps(change);
6316
+ const extracted = extractV4Between(base, change.apply(base), { isSetValued });
6317
+ attachV4Steps(change, explicitRegisters.length > 0 ? [...extracted.filter((step) => step.op !== "set_register"), ...explicitRegisters] : extracted);
6318
+ }
6319
+ return change.toJSON();
6320
+ };
6321
+ const encodeBatch = (editor, batch, fallback, base) => {
6322
+ const restBase = base && batch.unsettle ? batch.unsettle.apply(base) : base;
6323
+ return {
6324
+ change: ensureV4ChangeJson(editor, batch.change, base),
6325
+ effects: batch.effects.map(encodeEditorEffect),
6326
+ selectionAfter: encodeEditorSelection(editor, batch.selectionAfter, { validateDocument: false }),
6327
+ ...batch.selectionAfterRoot ? { selectionAfterRoot: batch.selectionAfterRoot } : {},
6328
+ selectionBefore: encodeEditorSelection(editor, batch.selectionBefore, { validateDocument: false }),
6329
+ ...batch.selectionBeforeRoot ? { selectionBeforeRoot: batch.selectionBeforeRoot } : {},
6330
+ ...batch.unsettle ? { unsettle: ensureV4ChangeJson(editor, batch.unsettle, base) } : {},
6331
+ ...batch.rest ? { rest: ensureV4ChangeJson(editor, batch.rest, restBase) } : {},
6332
+ ...batch.carried ? { carried: batch.carried.map(({ landed, ...run }) => landed === run.length ? run : {
6333
+ ...run,
6334
+ landed
6335
+ }) } : {},
6336
+ ...encodeRecord(historyFactsOf(batch)),
6337
+ ...fallback ? { fallback: encodeBatch(editor, fallback, void 0, base) } : {}
6338
+ };
6339
+ };
6340
+ const encodeStep = (editor, batch, fallback, base) => ({
6341
+ ...encodeBatch(editor, batch, fallback, base),
6369
6342
  id: historyBatchStepId(batch)
6370
6343
  });
6371
6344
  const isPosition = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -6376,7 +6349,7 @@ const decodeCarriedRuns = (value) => Array.isArray(value) && value.length > 0 &&
6376
6349
  root,
6377
6350
  source
6378
6351
  })) : null;
6379
- const isHistoryJSON = (value) => isObject(value) && (value.version === 4 || value.version === 5 || value.version === 6 || value.version === 7) && isHistorySchemaIdentity(value.schema) && Array.isArray(value.redos) && Array.isArray(value.undos);
6352
+ const isHistoryJSON = (value) => isObject(value) && value.version === 8 && isHistorySchemaIdentity(value.schema) && Array.isArray(value.redos) && Array.isArray(value.undos);
6380
6353
  const describeSchema = (identity) => identity.kind === "derived" ? `derived schema (${identity.fingerprint})` : `schema "${identity.id}" version ${identity.version}`;
6381
6354
  const assertSchemaIdentity = (editor, persisted) => {
6382
6355
  const current = editor.read.schema.identity();
@@ -6384,6 +6357,135 @@ const assertSchemaIdentity = (editor, persisted) => {
6384
6357
  if (current.kind === "named" && persisted.kind === "named" && current.id === persisted.id && current.version === persisted.version) throw new Error(`History schema mismatch for "${current.id}" version ${current.version}: fingerprints differ because schema semantics changed without a version bump.`);
6385
6358
  throw new Error(`History schema mismatch: history uses ${describeSchema(persisted)}, but the editor uses ${describeSchema(current)}.`);
6386
6359
  };
6360
+ const alignRootChangeToCarriedRuns = (change, baseRoot, afterRoot, runs) => {
6361
+ const kept = [];
6362
+ let cursorA = 0;
6363
+ let cursorB = 0;
6364
+ for (const section of change.toJSON()) if (section.replacement !== void 0) {
6365
+ cursorA += section.length;
6366
+ for (const token of section.replacement) cursorB += token.kind === "text" ? token.text.length : 1;
6367
+ } else if (section.properties !== void 0) {
6368
+ kept.push({
6369
+ a0: cursorA,
6370
+ a1: cursorA + section.length,
6371
+ b0: cursorB,
6372
+ b1: cursorB + section.length,
6373
+ properties: section.properties
6374
+ });
6375
+ cursorA += section.length;
6376
+ cursorB += section.length;
6377
+ } else {
6378
+ if (section.length > 0) kept.push({
6379
+ a0: cursorA,
6380
+ a1: cursorA + section.length,
6381
+ b0: cursorB,
6382
+ b1: cursorB + section.length
6383
+ });
6384
+ cursorA += section.length;
6385
+ cursorB += section.length;
6386
+ }
6387
+ let pieces = kept;
6388
+ for (const run of runs) {
6389
+ const nextPieces = [];
6390
+ for (const seg of pieces) {
6391
+ const srcFrom = Math.max(seg.a0, run.source);
6392
+ const srcTo = Math.min(seg.a1, run.source + run.length);
6393
+ const dstFrom = Math.max(seg.b0, run.at);
6394
+ const dstTo = Math.min(seg.b1, run.at + run.landed);
6395
+ const cuts = [];
6396
+ if (srcTo > srcFrom) {
6397
+ if (baseRoot.slice(srcFrom, srcTo).tokens.some((token) => token.kind === "text")) return null;
6398
+ cuts.push([srcFrom - seg.a0, srcTo - seg.a0]);
6399
+ }
6400
+ if (dstTo > dstFrom) {
6401
+ if (afterRoot.slice(dstFrom, dstTo).tokens.some((token) => token.kind === "text")) return null;
6402
+ cuts.push([dstFrom - seg.b0, dstTo - seg.b0]);
6403
+ }
6404
+ if (cuts.length === 0) {
6405
+ nextPieces.push(seg);
6406
+ continue;
6407
+ }
6408
+ if (seg.properties !== void 0) continue;
6409
+ cuts.sort((x, y) => x[0] - y[0]);
6410
+ let off = 0;
6411
+ const len = seg.a1 - seg.a0;
6412
+ for (const [cutStart, cutEnd] of cuts) {
6413
+ if (cutStart > off) nextPieces.push({
6414
+ a0: seg.a0 + off,
6415
+ a1: seg.a0 + cutStart,
6416
+ b0: seg.b0 + off,
6417
+ b1: seg.b0 + cutStart
6418
+ });
6419
+ if (cutEnd > off) off = cutEnd;
6420
+ }
6421
+ if (len > off) nextPieces.push({
6422
+ a0: seg.a0 + off,
6423
+ a1: seg.a1,
6424
+ b0: seg.b0 + off,
6425
+ b1: seg.b1
6426
+ });
6427
+ }
6428
+ pieces = nextPieces;
6429
+ }
6430
+ const sections = [];
6431
+ let posA = 0;
6432
+ let posB = 0;
6433
+ for (const seg of pieces) {
6434
+ if (seg.a0 > posA || seg.b0 > posB) sections.push({
6435
+ length: seg.a0 - posA,
6436
+ replacement: afterRoot.slice(posB, seg.b0).tokens
6437
+ });
6438
+ if (seg.properties !== void 0) sections.push({
6439
+ length: seg.a1 - seg.a0,
6440
+ properties: seg.properties
6441
+ });
6442
+ else if (seg.a1 > seg.a0) sections.push({ length: seg.a1 - seg.a0 });
6443
+ posA = seg.a1;
6444
+ posB = seg.b1;
6445
+ }
6446
+ if (baseRoot.length > posA || afterRoot.length > posB) sections.push({
6447
+ length: baseRoot.length - posA,
6448
+ replacement: afterRoot.slice(posB).tokens
6449
+ });
6450
+ return RootChange.fromJSON(sections);
6451
+ };
6452
+ const remintRestoredBatch = (batch, liveIds, currentScope, mint, renamed) => {
6453
+ const change = remintForeignRestoredV4Change(batch.change, liveIds, currentScope, mint, renamed);
6454
+ const unsettle = batch.unsettle ? remintForeignRestoredV4Change(batch.unsettle, liveIds, currentScope, mint, renamed) : void 0;
6455
+ const rest = batch.rest ? remintForeignRestoredV4Change(batch.rest, liveIds, currentScope, mint, renamed) : void 0;
6456
+ if (change === batch.change && unsettle === batch.unsettle && rest === batch.rest) return batch;
6457
+ const next = freezeHistoryBatch({
6458
+ ...batch,
6459
+ change,
6460
+ ...unsettle ? { unsettle } : {},
6461
+ ...rest ? { rest } : {}
6462
+ });
6463
+ withHistoryFacts(next, historyFactsOf(batch));
6464
+ withHistoryStepId(next, historyBatchStepId(batch));
6465
+ const fallback = historyFallbackOf(batch);
6466
+ if (fallback !== void 0) withHistoryFallback(next, fallback);
6467
+ return next;
6468
+ };
6469
+ const bindHistoryBatch = (batch, base) => {
6470
+ const change = bindV4DocumentChange(batch.change, base);
6471
+ const unsettle = batch.unsettle ? bindV4DocumentChange(batch.unsettle, base) : void 0;
6472
+ const restBase = unsettle ? unsettle.apply(base) : base;
6473
+ const rest = batch.rest ? bindV4DocumentChange(batch.rest, restBase) : void 0;
6474
+ if (change === batch.change && unsettle === batch.unsettle && rest === batch.rest) return batch;
6475
+ const rebound = freezeHistoryBatch({
6476
+ ...batch,
6477
+ change,
6478
+ ...unsettle ? { unsettle } : {},
6479
+ ...rest ? { rest } : {}
6480
+ });
6481
+ const facts = historyFactsOf(batch);
6482
+ const stepId = historyBatchStepId(batch);
6483
+ const fallback = historyFallbackOf(batch);
6484
+ withHistoryFacts(rebound, facts);
6485
+ withHistoryStepId(rebound, stepId);
6486
+ if (fallback !== void 0) withHistoryFallback(rebound, fallback);
6487
+ return rebound;
6488
+ };
6387
6489
  const checkBatch = (editor, batch, direction, document, recordPrograms) => {
6388
6490
  let value = document;
6389
6491
  const selectionAtBase = direction === "undo" ? batch.selectionAfter : batch.selectionBefore;
@@ -6392,20 +6494,64 @@ const checkBatch = (editor, batch, direction, document, recordPrograms) => {
6392
6494
  const selectionAfterChangeRoot = direction === "undo" ? batch.selectionBeforeRoot : batch.selectionAfterRoot;
6393
6495
  editor.read.schema.assertDocument(value);
6394
6496
  assertSelectionSupported(editor, selectionAtBase, value, selectionAtBaseRoot ?? "main");
6395
- if (batch.unsettle) {
6396
- if (!batch.rest && !documentChangeWritesOnlyElementProperties(batch.unsettle, value)) throw new Error("A history step can take back only element properties its settle stage wrote.");
6397
- editor.read.schema.assertDocument(batch.unsettle.apply(value));
6497
+ const bound = bindHistoryBatch(batch, value);
6498
+ if (bound.unsettle) {
6499
+ if (!bound.rest && !documentChangeWritesOnlyElementProperties(bound.unsettle, value)) throw new Error("A history step can take back only element properties its settle stage wrote.");
6500
+ editor.read.schema.assertDocument(bound.unsettle.apply(value));
6398
6501
  }
6399
6502
  const base = value;
6400
- value = batch.change.apply(value);
6401
- for (const run of batch.carried ?? []) {
6402
- const change = getInternalDocumentRootChange(batch.change, run.root);
6503
+ value = bound.change.apply(value);
6504
+ let finalBound = bound;
6505
+ const carriedRuns = bound.carried ?? [];
6506
+ if (carriedRuns.length > 0 && bound !== batch) {
6507
+ const runsByRoot = /* @__PURE__ */ new Map();
6508
+ for (const run of carriedRuns) {
6509
+ const list = runsByRoot.get(run.root);
6510
+ if (list) list.push(run);
6511
+ else runsByRoot.set(run.root, [run]);
6512
+ }
6513
+ let alignedRoots = null;
6514
+ for (const [root, rootRuns] of runsByRoot) {
6515
+ const change = getInternalDocumentRootChange(bound.change, root);
6516
+ if (!change) throw new Error("A history step carries a run its change does not.");
6517
+ const baseRoot = valueRootIndex(base, root);
6518
+ const afterRoot = valueRootIndex(value, root);
6519
+ const aligned = alignRootChangeToCarriedRuns(change, baseRoot, afterRoot, rootRuns);
6520
+ if (aligned) {
6521
+ if (!alignedRoots) alignedRoots = new Map(getInternalDocumentChangeEntries(bound.change));
6522
+ alignedRoots.set(root, aligned);
6523
+ }
6524
+ }
6525
+ if (alignedRoots) {
6526
+ const alignedDocChange = createInternalDocumentChange(alignedRoots, {
6527
+ classifications: new Map(getInternalDocumentChangeClassificationEntries(bound.change)),
6528
+ createRoots: bound.change.createRoots,
6529
+ deleteRoots: bound.change.deleteRoots,
6530
+ records: getInternalDocumentChangeRecords(bound.change)
6531
+ });
6532
+ copyV4StepsMetadata(bound.change, alignedDocChange);
6533
+ const reboundAligned = freezeHistoryBatch({
6534
+ ...bound,
6535
+ change: alignedDocChange
6536
+ });
6537
+ withHistoryFacts(reboundAligned, historyFactsOf(bound));
6538
+ withHistoryStepId(reboundAligned, historyBatchStepId(bound));
6539
+ const fallback = historyFallbackOf(bound);
6540
+ if (fallback !== void 0) withHistoryFallback(reboundAligned, fallback);
6541
+ finalBound = reboundAligned;
6542
+ }
6543
+ }
6544
+ for (const run of finalBound.carried ?? []) {
6545
+ const change = getInternalDocumentRootChange(finalBound.change, run.root);
6403
6546
  if (!change || !carriesRun(change, valueRootIndex(base, run.root), valueRootIndex(value, run.root), run)) throw new Error("A history step carries a run its change does not.");
6404
6547
  }
6405
- if (recordPrograms && batch.carried?.length === 1 && !batch.rest && !batch.unsettle) withHistoryProgram(batch, checkedCarryProgram(historyReplaySchemaOf(editor), base, batch.change, batch.carried[0])?.program);
6548
+ if (recordPrograms && finalBound.carried?.length === 1 && !finalBound.rest && !finalBound.unsettle) withHistoryProgram(finalBound, checkedCarryProgram(historyReplaySchemaOf(editor), base, finalBound.change, finalBound.carried[0])?.program);
6406
6549
  editor.read.schema.assertDocument(value);
6407
6550
  assertSelectionSupported(editor, selectionAfterChange, value, selectionAfterChangeRoot ?? "main");
6408
- return value;
6551
+ return {
6552
+ after: value,
6553
+ batch: finalBound
6554
+ };
6409
6555
  };
6410
6556
  const namesOf = (names, text) => {
6411
6557
  try {
@@ -6434,45 +6580,67 @@ const breaksNames = (sets, change, before, after) => {
6434
6580
  const ops = getInternalDocumentChangeRecords(change);
6435
6581
  return [...sets].some(([named, { namedBy }]) => namedBy !== void 0 && (addsMissingName(namedBy, named, ops, before, after) || dropsNamedRecord(namedBy, named, ops, before, after)));
6436
6582
  };
6437
- const validateBatches = (editor, batches, direction, document, recordPrograms, fallbacks, sets = null) => {
6583
+ const validateBatches = (editor, batches, direction, document, recordPrograms, fallbacks, sets = null, bases) => {
6438
6584
  let value = document;
6439
6585
  let keptFrom = 0;
6440
6586
  const breaks = (batch, from, to) => sets !== null && breaksNames(sets, batch.change, getValueRecords(from), getValueRecords(to));
6587
+ const rebound = new Array(batches.length);
6441
6588
  for (const [at, batch] of batches.toReversed().entries()) {
6589
+ const index = batches.length - 1 - at;
6442
6590
  const fallback = direction === "redo" ? historyFallbackOf(batch) : null;
6591
+ const checked = checkBatch(editor, batch, direction, value, recordPrograms);
6592
+ bases?.set(batch, value);
6593
+ bases?.set(checked.batch, value);
6594
+ rebound[index] = checked.batch;
6443
6595
  if (fallback) try {
6444
6596
  const landed = checkBatch(editor, fallback, direction, value, recordPrograms);
6445
- if (!breaks(fallback, value, landed)) fallbacks.set(batch, fallback);
6597
+ if (!breaks(landed.batch, value, landed.after)) {
6598
+ fallbacks.set(checked.batch, landed.batch);
6599
+ bases?.set(fallback, value);
6600
+ bases?.set(landed.batch, value);
6601
+ }
6446
6602
  } catch (error) {
6447
6603
  if (recordPrograms) throw error;
6448
6604
  }
6449
- const after = checkBatch(editor, batch, direction, value, recordPrograms);
6450
- if (keptFrom === 0 && breaks(batch, value, after)) keptFrom = batches.length - at;
6451
- value = after;
6605
+ if (keptFrom === 0 && breaks(checked.batch, value, checked.after)) keptFrom = batches.length - at;
6606
+ value = checked.after;
6452
6607
  }
6453
- return batches.slice(keptFrom);
6608
+ return rebound.slice(keptFrom);
6454
6609
  };
6455
6610
  const validateHistory = (editor, history, validateAgainst = editor.read.value(), recordPrograms = false, fallbacks = /* @__PURE__ */ new Map(), sets = null) => {
6611
+ const bases = /* @__PURE__ */ new Map();
6456
6612
  if (!validateAgainst) {
6457
6613
  for (const batch of history.redos) {
6458
6614
  const fallback = historyFallbackOf(batch);
6459
6615
  if (fallback) fallbacks.set(batch, fallback);
6460
6616
  }
6461
6617
  return {
6618
+ bases,
6462
6619
  fallbacks,
6463
6620
  redos: history.redos,
6464
6621
  undos: history.undos
6465
6622
  };
6466
6623
  }
6467
- const kept = (batches, direction) => validateBatches(editor, batches, direction, validateAgainst, recordPrograms, fallbacks, sets);
6624
+ const liveIds = recordPrograms && isBoundToSharedRoom(editor) ? collectLiveElementIds(validateAgainst) : null;
6625
+ const remint = (batches) => {
6626
+ if (!liveIds) return batches;
6627
+ const { elementIdMint } = getCompiledEditorSchema(editor);
6628
+ const currentScope = elementIdMint.scope;
6629
+ const renamed = /* @__PURE__ */ new Map();
6630
+ const out = new Array(batches.length);
6631
+ for (let index = batches.length - 1; index >= 0; index -= 1) out[index] = remintRestoredBatch(batches[index], liveIds, currentScope, elementIdMint.next, renamed);
6632
+ return out;
6633
+ };
6634
+ const kept = (batches, direction) => validateBatches(editor, remint(batches), direction, validateAgainst, recordPrograms, fallbacks, sets, bases);
6468
6635
  return {
6636
+ bases,
6469
6637
  fallbacks,
6470
6638
  redos: kept(history.redos, "redo"),
6471
6639
  undos: kept(history.undos, "undo")
6472
6640
  };
6473
6641
  };
6474
- const decodeBatch = (editor, input, effectTypes, direction, version, nested = false) => {
6475
- if (!isObject(input) || input.record !== void 0 && version < 7 || input.fallback !== void 0 && (version < 6 || direction !== "redo" || nested) || input.unsettle !== void 0 && direction === "redo" || input.rest !== void 0 && (version < 5 || input.unsettle === void 0) || input.carried !== void 0 && version < 5 || input.id !== void 0 && (nested || typeof input.id !== "string" || input.id.length === 0) || !Array.isArray(input.effects) || !Object.hasOwn(input, "change") || !Object.hasOwn(input, "selectionAfter") || !Object.hasOwn(input, "selectionBefore") || input.selectionAfterRoot !== void 0 && (typeof input.selectionAfterRoot !== "string" || input.selectionAfterRoot.length === 0 || input.selectionAfterRoot === "main") || input.selectionBeforeRoot !== void 0 && (typeof input.selectionBeforeRoot !== "string" || input.selectionBeforeRoot.length === 0 || input.selectionBeforeRoot === "main")) throw new Error("Invalid history batch JSON.");
6642
+ const decodeBatch = (editor, input, effectTypes, direction, nested = false) => {
6643
+ if (!isObject(input) || input.fallback !== void 0 && (direction !== "redo" || nested) || input.unsettle !== void 0 && direction === "redo" || input.rest !== void 0 && input.unsettle === void 0 || input.id !== void 0 && (nested || typeof input.id !== "string" || input.id.length === 0) || !Array.isArray(input.effects) || !Object.hasOwn(input, "change") || !Object.hasOwn(input, "selectionAfter") || !Object.hasOwn(input, "selectionBefore") || input.selectionAfterRoot !== void 0 && (typeof input.selectionAfterRoot !== "string" || input.selectionAfterRoot.length === 0 || input.selectionAfterRoot === "main") || input.selectionBeforeRoot !== void 0 && (typeof input.selectionBeforeRoot !== "string" || input.selectionBeforeRoot.length === 0 || input.selectionBeforeRoot === "main")) throw new Error("Invalid history batch JSON.");
6476
6644
  const carried = input.carried === void 0 ? void 0 : decodeCarriedRuns(input.carried);
6477
6645
  if (carried === null) throw new Error("Invalid history batch JSON.");
6478
6646
  const effects = input.effects.map((effect) => {
@@ -6497,25 +6665,25 @@ const decodeBatch = (editor, input, effectTypes, direction, version, nested = fa
6497
6665
  ...input.unsettle === void 0 ? {} : { unsettle: decode(input.unsettle) },
6498
6666
  ...input.rest === void 0 ? {} : { rest: decode(input.rest) },
6499
6667
  ...carried ? { carried } : {}
6500
- }, version === 7 ? decodeRecord(input) : void 0), typeof input.id === "string" ? input.id : void 0);
6501
- return input.fallback === void 0 ? recorded : withHistoryFallback(recorded, freezeHistoryBatch(decodeBatch(editor, input.fallback, effectTypes, direction, version, true)));
6668
+ }, decodeRecord(input)), typeof input.id === "string" ? input.id : void 0);
6669
+ return input.fallback === void 0 ? recorded : withHistoryFallback(recorded, freezeHistoryBatch(decodeBatch(editor, input.fallback, effectTypes, direction, true)));
6502
6670
  };
6503
6671
  const decodeHistoryValue = (editor, json, options = {}) => {
6504
- if (!isHistoryJSON(json)) throw new Error("Invalid history JSON or unsupported history version; expected version 4, 5, 6 or 7.");
6672
+ if (!isHistoryJSON(json)) throw new Error("Invalid history JSON or unsupported history version; expected version 8.");
6505
6673
  const schema = copyHistorySchemaIdentity(json.schema);
6506
6674
  assertSchemaIdentity(editor, schema);
6507
6675
  const ids = [...json.redos, ...json.undos].flatMap((step) => isObject(step) && typeof step.id === "string" ? [step.id] : []);
6508
6676
  if (new Set(ids).size !== ids.length) throw new Error("Invalid history JSON: two steps share one id.");
6509
6677
  const { effectTypes } = getPluginRegistry(editor);
6510
6678
  const decodeStack = (direction) => json[direction === "redo" ? "redos" : "undos"].flatMap((input) => {
6511
- const batch = freezeHistoryBatch(decodeBatch(editor, input, effectTypes, direction, json.version));
6512
- return options.restore && batch.change.empty && batch.effects.length === 0 ? [] : [batch];
6679
+ const batch = freezeHistoryBatch(decodeBatch(editor, input, effectTypes, direction));
6680
+ return options.restore && batch.change.empty && batch.effects.length === 0 && jsonEqual(batch.selectionBefore, batch.selectionAfter) ? [] : [batch];
6513
6681
  });
6514
6682
  const { fallbacks, redos, undos } = validateHistory(editor, {
6515
6683
  redos: decodeStack("redo"),
6516
6684
  undos: decodeStack("undo")
6517
6685
  }, options.validateAgainst, true, void 0, options.restore ? getCompiledEditorSchema(editor).recordSets : null);
6518
- for (const batch of redos) if (!fallbacks.has(batch)) withHistoryFallback(batch, null);
6686
+ for (const batch of redos) withHistoryFallback(batch, fallbacks.get(batch) ?? null);
6519
6687
  return Object.freeze({
6520
6688
  redos: Object.freeze(redos),
6521
6689
  revision: 0,
@@ -6532,10 +6700,10 @@ const encodeHistoryValue = (editor, value, options = {}) => {
6532
6700
  const redos = persistent(history.redos);
6533
6701
  const undos = persistent(history.undos);
6534
6702
  return {
6535
- redos: redos.map((batch) => encodeStep(editor, batch, checked.fallbacks.get(batch))),
6703
+ redos: redos.map((batch) => encodeStep(editor, batch, checked.fallbacks.get(batch), checked.bases.get(batch))),
6536
6704
  schema,
6537
- undos: undos.map((batch) => encodeStep(editor, batch)),
6538
- version: 7
6705
+ undos: undos.map((batch) => encodeStep(editor, batch, void 0, checked.bases.get(batch))),
6706
+ version: 8
6539
6707
  };
6540
6708
  };
6541
6709
  //#endregion
@@ -6635,7 +6803,7 @@ const getHistoricSelectionRoot = (batch, target = "before") => {
6635
6803
  const batchHasRoot = (batch, root) => getBatchRoots(batch).has(root);
6636
6804
  const shouldPreserveHistoricDOMSelection = (root, batch) => !batch.change.empty && !batchHasRoot(batch, root);
6637
6805
  const shouldRestoreHistoricSelection = (root, caretRoot, batch, target) => {
6638
- if (batch.change.empty) return false;
6806
+ if (batch.change.empty) return batch.effects.length === 0 && (getHistoricSelectionRoot(batch, target) ?? "main") === root;
6639
6807
  const historicRoot = getHistoricSelectionRoot(batch, target);
6640
6808
  if (historicRoot === root && batchHasRoot(batch, root)) return true;
6641
6809
  if (historicRoot === void 0 || caretRoot === void 0 || batch.change.deleteRoots.has(historicRoot)) return false;
@@ -6852,7 +7020,7 @@ const survivingSessionRecordChange = (base, current, outside, change) => {
6852
7020
  return kept.size === 0 ? DocumentChange.empty : createInternalDocumentChange(/* @__PURE__ */ new Map(), { records: kept });
6853
7021
  };
6854
7022
  const runHistoricUpdate = (editor, root, tx, batch, fn) => {
6855
- const preserveSelection = isRecordOnlyChange(batch.change) && batch.effects.length > 0 || shouldPreserveHistoricDOMSelection(root, batch);
7023
+ const preserveSelection = isRecordOnlyChange(batch.change) && (batch.effects.length > 0 || hasV4RegisterSteps(batch.change)) || shouldPreserveHistoricDOMSelection(root, batch);
6856
7024
  tx.tags.add("semantic-command");
6857
7025
  tx.tags.add("history-skip");
6858
7026
  tx.tags.add("historic");
@@ -7065,7 +7233,26 @@ const recordHistoryStep = (editor, effect, value, options, writeRecords) => {
7065
7233
  if (blocked && "reason" in blocked) return blocked;
7066
7234
  throw new Error("History did not record the session step.");
7067
7235
  };
7068
- const shouldSaveCommit = (commit, effects) => !commit.tags.includes("history-skip") && !commit.tags.includes("historic") && !commit.annotations[documentReplacement.key] && (!commit.changes.empty || effects.length > 0);
7236
+ const collectSupersededEffectKeys = (editor, commit) => {
7237
+ let keys;
7238
+ const add = (key) => {
7239
+ keys ??= /* @__PURE__ */ new Set();
7240
+ keys.add(key);
7241
+ };
7242
+ if (commit.dirtyStateKeys.length > 0) {
7243
+ const { stateFields } = getPluginRegistry(editor);
7244
+ for (const fieldKey of commit.dirtyStateKeys) {
7245
+ const registration = stateFields.get(fieldKey);
7246
+ if (registration && registration.field.effect.history !== "skip") add(registration.field.effect.key);
7247
+ }
7248
+ }
7249
+ for (const effect of commit.effects) {
7250
+ if (effect.type.history === "skip") continue;
7251
+ if (isStateFieldEffect(effect.type) || effect.type.collabReplay === "latest") add(effect.type.key);
7252
+ }
7253
+ return keys;
7254
+ };
7255
+ const shouldSaveCommit = (editor, before, commit, effects, hasRecovery = false) => !commit.tags.includes("history-skip") && !commit.tags.includes("historic") && !commit.annotations[documentReplacement.key] && !shouldSkipHistoryForOnlyProperties(editor, before, commit, effects, hasRecovery) && (!commit.changes.empty || effects.length > 0);
7069
7256
  const createHistoryPlugin = (options = {}) => {
7070
7257
  const reduceHistory = ({ after, before, commit, editor, schema }) => {
7071
7258
  const anchorCapture = consumeAnchorHistoryCapture(commit);
@@ -7087,12 +7274,19 @@ const createHistoryPlugin = (options = {}) => {
7087
7274
  return;
7088
7275
  }
7089
7276
  const { recordSets } = getCompiledEditorSchema(editor);
7090
- const kept = (change) => withoutRetainedRecordSets(change, recordSets);
7277
+ const { stateFields } = getPluginRegistry(editor);
7278
+ const keepSharedRegisterKey = (key) => stateFields.get(key)?.field.history !== "skip";
7279
+ const kept = (change) => filterDocumentChangeRegisterKeys(withoutRetainedRecordSets(change, recordSets), keepSharedRegisterKey);
7091
7280
  const changes = kept(commit.changes);
7092
7281
  const inverse = kept(commit.inverseChanges);
7093
7282
  const facts = getEditorCommitFacts(commit);
7094
7283
  const inverseFacts = (change) => change === inverse ? flipFacts(facts) : void 0;
7095
- const effects = commit.effects.filter((effect) => effect.type.history !== "skip");
7284
+ const registerFieldEffects = /* @__PURE__ */ new Set();
7285
+ for (const step of getV4RegisterSteps(changes)) {
7286
+ const entry = stateFields.get(step.id);
7287
+ if (entry?.field.collab === "shared") registerFieldEffects.add(entry.field.effect);
7288
+ }
7289
+ const effects = commit.effects.filter((effect) => effect.type.history !== "skip" && !registerFieldEffects.has(effect.type));
7096
7290
  const action = commit.annotations[historyAction.key];
7097
7291
  const dropped = commit.annotations[historyReplayDrop.key];
7098
7292
  const replayRequest = commit.annotations[historyReplayRequest.key];
@@ -7145,10 +7339,11 @@ const createHistoryPlugin = (options = {}) => {
7145
7339
  validateAgainst: after
7146
7340
  }), after);
7147
7341
  LAST_AUTOMATIC_HISTORY_GROUP_TIME.delete(editor);
7342
+ return;
7148
7343
  }
7149
7344
  if (commit.annotations[documentReplacement.key]) {
7150
7345
  dropPendingHistoryReplayEntry(editor);
7151
- if (!restoredHistoryJSON) replaceHistoryState(editor, {
7346
+ replaceHistoryState(editor, {
7152
7347
  redos: [],
7153
7348
  schema: captureHistoryState(editor)?.schema ?? schema,
7154
7349
  undos: []
@@ -7209,19 +7404,32 @@ const createHistoryPlugin = (options = {}) => {
7209
7404
  request: replayRequest
7210
7405
  });
7211
7406
  }
7212
- if (!shouldSaveCommit(commit, effects)) {
7407
+ if (!shouldSaveCommit(editor, before, commit, effects, Boolean(anchorCapture?.recovery))) {
7213
7408
  if (commit.changed.hasAny("snapshot")) LAST_AUTOMATIC_HISTORY_GROUP_TIME.delete(editor);
7214
- if (!commit.tags.includes("historic") && !changes.empty) {
7215
- queuePendingHistoryReplayMapping(editor, changes, after);
7216
- queueHistoryMapping(editor, changes, after, {
7409
+ if (!commit.tags.includes("historic")) {
7410
+ const supersededEffectKeys = collectSupersededEffectKeys(editor, commit);
7411
+ if (!changes.empty) queuePendingHistoryReplayMapping(editor, changes, after);
7412
+ if (!changes.empty || supersededEffectKeys) queueHistoryMapping(editor, changes, after, {
7413
+ before,
7414
+ facts,
7415
+ otherWriter: commit.tags.includes("collaboration"),
7416
+ supersededEffectKeys
7417
+ });
7418
+ }
7419
+ return;
7420
+ }
7421
+ if (effects.length === 0 && !anchorCapture?.recovery && isInternalDocumentChangeNoop(changes, before)) {
7422
+ if (!commit.tags.includes("historic")) {
7423
+ const supersededEffectKeys = collectSupersededEffectKeys(editor, commit);
7424
+ if (supersededEffectKeys) queueHistoryMapping(editor, DocumentChange.empty, after, {
7217
7425
  before,
7218
7426
  facts,
7219
- otherWriter: commit.tags.includes("collaboration")
7427
+ otherWriter: commit.tags.includes("collaboration"),
7428
+ supersededEffectKeys
7220
7429
  });
7221
7430
  }
7222
7431
  return;
7223
7432
  }
7224
- if (effects.length === 0 && !anchorCapture?.recovery && isInternalDocumentChangeNoop(changes, before)) return;
7225
7433
  const sessionEffects = effects.filter((effect) => typeof effect.type.history === "object");
7226
7434
  if (sessionEffects.length > 0 && (!isRecordOnlyChange(changes) || effects.length !== 1 || sessionEffects.length !== 1)) throw new Error("A session history effect must own one effect-only or record-only history batch.");
7227
7435
  const prepared = prepareHistoryBatch(inverse, commit, effects);