@portabletext/editor 1.31.2 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/lib/_chunks-cjs/behavior.core.cjs +4 -4
  2. package/lib/_chunks-cjs/behavior.core.cjs.map +1 -1
  3. package/lib/_chunks-cjs/behavior.markdown.cjs +19 -11
  4. package/lib/_chunks-cjs/behavior.markdown.cjs.map +1 -1
  5. package/lib/_chunks-cjs/plugin.event-listener.cjs +1839 -1724
  6. package/lib/_chunks-cjs/plugin.event-listener.cjs.map +1 -1
  7. package/lib/_chunks-cjs/selector.get-trimmed-selection.cjs +97 -0
  8. package/lib/_chunks-cjs/selector.get-trimmed-selection.cjs.map +1 -0
  9. package/lib/_chunks-cjs/{parse-blocks.cjs → util.block-offsets-to-selection.cjs} +21 -2
  10. package/lib/_chunks-cjs/util.block-offsets-to-selection.cjs.map +1 -0
  11. package/lib/_chunks-cjs/util.reverse-selection.cjs +11 -0
  12. package/lib/_chunks-cjs/util.reverse-selection.cjs.map +1 -1
  13. package/lib/_chunks-es/behavior.core.js +1 -1
  14. package/lib/_chunks-es/behavior.core.js.map +1 -1
  15. package/lib/_chunks-es/behavior.markdown.js +18 -11
  16. package/lib/_chunks-es/behavior.markdown.js.map +1 -1
  17. package/lib/_chunks-es/plugin.event-listener.js +1842 -1726
  18. package/lib/_chunks-es/plugin.event-listener.js.map +1 -1
  19. package/lib/_chunks-es/selector.get-trimmed-selection.js +100 -0
  20. package/lib/_chunks-es/selector.get-trimmed-selection.js.map +1 -0
  21. package/lib/_chunks-es/{parse-blocks.js → util.block-offsets-to-selection.js} +21 -1
  22. package/lib/_chunks-es/util.block-offsets-to-selection.js.map +1 -0
  23. package/lib/_chunks-es/util.reverse-selection.js +11 -0
  24. package/lib/_chunks-es/util.reverse-selection.js.map +1 -1
  25. package/lib/behaviors/index.d.cts +27 -0
  26. package/lib/behaviors/index.d.ts +27 -0
  27. package/lib/index.d.cts +1128 -66
  28. package/lib/index.d.ts +1128 -66
  29. package/lib/plugins/index.cjs +295 -3
  30. package/lib/plugins/index.cjs.map +1 -1
  31. package/lib/plugins/index.d.cts +1142 -67
  32. package/lib/plugins/index.d.ts +1142 -67
  33. package/lib/plugins/index.js +300 -4
  34. package/lib/plugins/index.js.map +1 -1
  35. package/lib/selectors/index.cjs +51 -1
  36. package/lib/selectors/index.cjs.map +1 -1
  37. package/lib/selectors/index.d.cts +67 -0
  38. package/lib/selectors/index.d.ts +67 -0
  39. package/lib/selectors/index.js +53 -2
  40. package/lib/selectors/index.js.map +1 -1
  41. package/lib/utils/index.cjs +5 -4
  42. package/lib/utils/index.cjs.map +1 -1
  43. package/lib/utils/index.d.cts +16 -0
  44. package/lib/utils/index.d.ts +16 -0
  45. package/lib/utils/index.js +4 -3
  46. package/package.json +2 -2
  47. package/src/behavior-actions/behavior.action.decorator.add.ts +161 -0
  48. package/src/behavior-actions/behavior.action.delete.text.ts +54 -0
  49. package/src/behavior-actions/behavior.actions.ts +25 -43
  50. package/src/behaviors/behavior.markdown-emphasis.ts +395 -0
  51. package/src/behaviors/behavior.markdown.ts +11 -4
  52. package/src/behaviors/behavior.types.ts +7 -0
  53. package/src/editor/editor-machine.ts +80 -85
  54. package/src/editor/plugins/create-with-event-listeners.ts +51 -0
  55. package/src/editor/plugins/createWithEditableAPI.ts +18 -2
  56. package/src/editor/plugins/createWithPortableTextMarkModel.ts +2 -97
  57. package/src/editor/plugins/createWithUndoRedo.ts +132 -107
  58. package/src/editor/with-applying-behavior-actions.ts +27 -3
  59. package/src/plugins/plugin.markdown.tsx +11 -1
  60. package/src/selectors/index.ts +5 -0
  61. package/src/selectors/selector.get-anchor-block.ts +22 -0
  62. package/src/selectors/selector.get-anchor-child.ts +36 -0
  63. package/src/selectors/selector.get-anchor-span.ts +18 -0
  64. package/src/selectors/selector.get-anchor-text-block.ts +20 -0
  65. package/src/selectors/selector.get-trimmed-selection.test.ts +658 -0
  66. package/src/selectors/selector.get-trimmed-selection.ts +175 -0
  67. package/src/utils/index.ts +1 -0
  68. package/src/utils/util.block-offsets-to-selection.ts +36 -0
  69. package/lib/_chunks-cjs/parse-blocks.cjs.map +0 -1
  70. package/lib/_chunks-cjs/util.is-empty-text-block.cjs +0 -14
  71. package/lib/_chunks-cjs/util.is-empty-text-block.cjs.map +0 -1
  72. package/lib/_chunks-es/parse-blocks.js.map +0 -1
  73. package/lib/_chunks-es/util.is-empty-text-block.js +0 -15
  74. package/lib/_chunks-es/util.is-empty-text-block.js.map +0 -1
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
- var reactCompilerRuntime = require("react-compiler-runtime"), React = require("react"), useEffectEvent = require("use-effect-event"), jsxRuntime = require("react/jsx-runtime"), slateReact = require("slate-react"), react = require("@xstate/react"), debug$e = require("debug"), slate = require("slate"), xstate = require("xstate"), isEqual = require("lodash/isEqual.js"), patches = require("@portabletext/patches"), types = require("@sanity/types"), flatten = require("lodash/flatten.js"), isPlainObject = require("lodash/isPlainObject.js"), uniq = require("lodash/uniq.js"), parseBlocks = require("./parse-blocks.cjs"), util_sliceBlocks = require("./util.slice-blocks.cjs"), blockTools = require("@portabletext/block-tools"), toHtml = require("@portabletext/to-html"), schema = require("@sanity/schema"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), startCase = require("lodash.startcase"), selector_isAtTheStartOfBlock = require("./selector.is-at-the-start-of-block.cjs"), util_reverseSelection = require("./util.reverse-selection.cjs"), behavior_core = require("./behavior.core.cjs"), getRandomValues = require("get-random-values-esm"), rxjs = require("rxjs");
2
+ var reactCompilerRuntime = require("react-compiler-runtime"), React = require("react"), useEffectEvent = require("use-effect-event"), jsxRuntime = require("react/jsx-runtime"), slateReact = require("slate-react"), react = require("@xstate/react"), debug$e = require("debug"), slate = require("slate"), xstate = require("xstate"), isEqual = require("lodash/isEqual.js"), patches = require("@portabletext/patches"), types = require("@sanity/types"), flatten = require("lodash/flatten.js"), isPlainObject = require("lodash/isPlainObject.js"), uniq = require("lodash/uniq.js"), getRandomValues = require("get-random-values-esm"), util_blockOffsetsToSelection = require("./util.block-offsets-to-selection.cjs"), util_sliceBlocks = require("./util.slice-blocks.cjs"), blockTools = require("@portabletext/block-tools"), toHtml = require("@portabletext/to-html"), schema = require("@sanity/schema"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), selector_isAtTheStartOfBlock = require("./selector.is-at-the-start-of-block.cjs"), util_reverseSelection = require("./util.reverse-selection.cjs"), selector_getTrimmedSelection = require("./selector.get-trimmed-selection.cjs"), startCase = require("lodash.startcase"), behavior_core = require("./behavior.core.cjs"), rxjs = require("rxjs");
3
3
  function _interopDefaultCompat(e) {
4
4
  return e && typeof e == "object" && "default" in e ? e : { default: e };
5
5
  }
6
- var React__default = /* @__PURE__ */ _interopDefaultCompat(React), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$e), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), startCase__default = /* @__PURE__ */ _interopDefaultCompat(startCase), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues);
6
+ var React__default = /* @__PURE__ */ _interopDefaultCompat(React), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$e), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), startCase__default = /* @__PURE__ */ _interopDefaultCompat(startCase);
7
7
  function createEditorSchema(portableTextType) {
8
8
  if (!portableTextType)
9
9
  throw new Error("Parameter 'portabletextType' missing (required)");
@@ -1391,6 +1391,43 @@ function isRedoing(editor) {
1391
1391
  function setIsRedoing(editor, isRedoing2) {
1392
1392
  IS_REDOING.set(editor, isRedoing2);
1393
1393
  }
1394
+ const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
1395
+ let table;
1396
+ return () => {
1397
+ if (table)
1398
+ return table;
1399
+ table = [];
1400
+ for (let i = 0; i < 256; ++i)
1401
+ table[i] = (i + 256).toString(16).slice(1);
1402
+ return table;
1403
+ };
1404
+ })();
1405
+ function whatwgRNG(length = 16) {
1406
+ const rnds8 = new Uint8Array(length);
1407
+ return getRandomValues__default.default(rnds8), rnds8;
1408
+ }
1409
+ function randomKey(length) {
1410
+ const table = getByteHexTable();
1411
+ return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
1412
+ }
1413
+ const IS_APPLYING_BEHAVIOR_ACTIONS = /* @__PURE__ */ new WeakMap();
1414
+ function withApplyingBehaviorActions(editor, fn) {
1415
+ const prev = IS_APPLYING_BEHAVIOR_ACTIONS.get(editor);
1416
+ IS_APPLYING_BEHAVIOR_ACTIONS.set(editor, !0), slate.Editor.withoutNormalizing(editor, fn), IS_APPLYING_BEHAVIOR_ACTIONS.set(editor, prev);
1417
+ }
1418
+ function isApplyingBehaviorActions(editor) {
1419
+ return IS_APPLYING_BEHAVIOR_ACTIONS.get(editor) ?? !1;
1420
+ }
1421
+ const CURRENT_BEHAVIOR_ACTION_INTEND_SET = /* @__PURE__ */ new WeakMap();
1422
+ function withApplyingBehaviorActionIntendSet(editor, fn) {
1423
+ const current = CURRENT_BEHAVIOR_ACTION_INTEND_SET.get(editor);
1424
+ CURRENT_BEHAVIOR_ACTION_INTEND_SET.set(editor, {
1425
+ actionSetId: defaultKeyGenerator()
1426
+ }), withApplyingBehaviorActions(editor, fn), CURRENT_BEHAVIOR_ACTION_INTEND_SET.set(editor, current);
1427
+ }
1428
+ function getCurrentBehaviorActionSetId(editor) {
1429
+ return CURRENT_BEHAVIOR_ACTION_INTEND_SET.get(editor)?.actionSetId;
1430
+ }
1394
1431
  const debug$d = debugWithName("plugin:withUndoRedo"), SAVING = /* @__PURE__ */ new WeakMap(), REMOTE_PATCHES = /* @__PURE__ */ new WeakMap(), UNDO_STEP_LIMIT = 1e3, isSaving = (editor) => {
1395
1432
  const state = SAVING.get(editor);
1396
1433
  return state === void 0 ? !0 : state;
@@ -1403,6 +1440,7 @@ function createWithUndoRedo(options) {
1403
1440
  return (editor) => {
1404
1441
  let previousSnapshot = fromSlateValue(editor.children, blockSchemaType.name);
1405
1442
  const remotePatches = getRemotePatches(editor);
1443
+ let previousBehaviorActionIntendSetId = getCurrentBehaviorActionSetId(editor);
1406
1444
  options.subscriptions.push(() => {
1407
1445
  debug$d("Subscribing to patches");
1408
1446
  const sub = editorActor.on("patches", ({
@@ -1458,10 +1496,10 @@ function createWithUndoRedo(options) {
1458
1496
  history
1459
1497
  } = editor, {
1460
1498
  undos
1461
- } = history, step = undos[undos.length - 1], lastOp = step && step.operations && step.operations[step.operations.length - 1], overwrite = shouldOverwrite(op, lastOp), save = isSaving(editor);
1462
- let merge = !0;
1499
+ } = history, step = undos[undos.length - 1], lastOp = step && step.operations && step.operations[step.operations.length - 1], overwrite = shouldOverwrite(op, lastOp), save = isSaving(editor), currentBehaviorActionIntendSetId = getCurrentBehaviorActionSetId(editor);
1500
+ let merge = currentBehaviorActionIntendSetId !== void 0 && previousBehaviorActionIntendSetId === void 0 ? !1 : currentBehaviorActionIntendSetId !== void 0 && previousBehaviorActionIntendSetId !== void 0 ? currentBehaviorActionIntendSetId === previousBehaviorActionIntendSetId : !0;
1463
1501
  if (save) {
1464
- if (step ? operations.length === 0 && (merge = shouldMerge(op, lastOp) || overwrite) : merge = !1, step && merge)
1502
+ if (step ? operations.length === 0 && (merge = currentBehaviorActionIntendSetId === void 0 && previousBehaviorActionIntendSetId === void 0 ? shouldMerge(op, lastOp) || overwrite : merge) : merge = !1, step && merge)
1465
1503
  step.operations.push(op);
1466
1504
  else {
1467
1505
  const newStep = {
@@ -1474,83 +1512,80 @@ function createWithUndoRedo(options) {
1474
1512
  undos.shift();
1475
1513
  shouldClear(op) && (history.redos = []);
1476
1514
  }
1477
- apply2(op);
1478
- }, editor.undo = () => {
1479
- if (editorActor.getSnapshot().matches({
1480
- "edit mode": "read only"
1481
- }))
1482
- return;
1483
- const {
1484
- undos
1485
- } = editor.history;
1486
- if (undos.length > 0) {
1487
- const step = undos[undos.length - 1];
1488
- if (debug$d("Undoing", step), step.operations.length > 0) {
1489
- const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
1490
- let transformedOperations = step.operations;
1491
- otherPatches.forEach((item) => {
1492
- transformedOperations = flatten__default.default(transformedOperations.map((op) => transformOperation(editor, item.patch, op, item.snapshot, item.previousSnapshot)));
1493
- });
1494
- const reversedOperations = transformedOperations.map(slate.Operation.inverse).reverse();
1495
- try {
1496
- slate.Editor.withoutNormalizing(editor, () => {
1497
- withUndoing(editor, () => {
1498
- withoutSaving(editor, () => {
1499
- reversedOperations.forEach((op) => {
1500
- editor.apply(op);
1501
- });
1502
- });
1515
+ previousBehaviorActionIntendSetId = currentBehaviorActionIntendSetId, apply2(op);
1516
+ }, editor;
1517
+ };
1518
+ }
1519
+ const historyUndoActionImplementation = ({
1520
+ action
1521
+ }) => {
1522
+ const editor = action.editor, {
1523
+ undos
1524
+ } = editor.history, remotePatches = getRemotePatches(editor);
1525
+ if (undos.length > 0) {
1526
+ const step = undos[undos.length - 1];
1527
+ if (debug$d("Undoing", step), step.operations.length > 0) {
1528
+ const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
1529
+ let transformedOperations = step.operations;
1530
+ otherPatches.forEach((item) => {
1531
+ transformedOperations = flatten__default.default(transformedOperations.map((op) => transformOperation(editor, item.patch, op, item.snapshot, item.previousSnapshot)));
1532
+ });
1533
+ const reversedOperations = transformedOperations.map(slate.Operation.inverse).reverse();
1534
+ try {
1535
+ slate.Editor.withoutNormalizing(editor, () => {
1536
+ withUndoing(editor, () => {
1537
+ withoutSaving(editor, () => {
1538
+ reversedOperations.forEach((op) => {
1539
+ editor.apply(op);
1503
1540
  });
1504
- }), editor.normalize(), editor.onChange();
1505
- } catch (err) {
1506
- debug$d("Could not perform undo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
1507
- undos: [],
1508
- redos: []
1509
- }, SAVING.set(editor, !0), setIsUndoing(editor, !1), editor.onChange();
1510
- return;
1511
- }
1512
- editor.history.redos.push(step), editor.history.undos.pop();
1513
- }
1514
- }
1515
- }, editor.redo = () => {
1516
- if (editorActor.getSnapshot().matches({
1517
- "edit mode": "read only"
1518
- }))
1519
- return;
1520
- const {
1521
- redos
1522
- } = editor.history;
1523
- if (redos.length > 0) {
1524
- const step = redos[redos.length - 1];
1525
- if (debug$d("Redoing", step), step.operations.length > 0) {
1526
- const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
1527
- let transformedOperations = step.operations;
1528
- otherPatches.forEach((item) => {
1529
- transformedOperations = flatten__default.default(transformedOperations.map((op) => transformOperation(editor, item.patch, op, item.snapshot, item.previousSnapshot)));
1541
+ });
1530
1542
  });
1531
- try {
1532
- slate.Editor.withoutNormalizing(editor, () => {
1533
- withRedoing(editor, () => {
1534
- withoutSaving(editor, () => {
1535
- transformedOperations.forEach((op) => {
1536
- editor.apply(op);
1537
- });
1538
- });
1543
+ });
1544
+ } catch (err) {
1545
+ debug$d("Could not perform undo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
1546
+ undos: [],
1547
+ redos: []
1548
+ }, SAVING.set(editor, !0), setIsUndoing(editor, !1), editor.onChange();
1549
+ return;
1550
+ }
1551
+ editor.history.redos.push(step), editor.history.undos.pop();
1552
+ }
1553
+ }
1554
+ }, historyRedoActionImplementation = ({
1555
+ action
1556
+ }) => {
1557
+ const editor = action.editor, {
1558
+ redos
1559
+ } = editor.history, remotePatches = getRemotePatches(editor);
1560
+ if (redos.length > 0) {
1561
+ const step = redos[redos.length - 1];
1562
+ if (debug$d("Redoing", step), step.operations.length > 0) {
1563
+ const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
1564
+ let transformedOperations = step.operations;
1565
+ otherPatches.forEach((item) => {
1566
+ transformedOperations = flatten__default.default(transformedOperations.map((op) => transformOperation(editor, item.patch, op, item.snapshot, item.previousSnapshot)));
1567
+ });
1568
+ try {
1569
+ slate.Editor.withoutNormalizing(editor, () => {
1570
+ withRedoing(editor, () => {
1571
+ withoutSaving(editor, () => {
1572
+ transformedOperations.forEach((op) => {
1573
+ editor.apply(op);
1539
1574
  });
1540
- }), editor.normalize(), editor.onChange();
1541
- } catch (err) {
1542
- debug$d("Could not perform redo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
1543
- undos: [],
1544
- redos: []
1545
- }, SAVING.set(editor, !0), setIsRedoing(editor, !1), editor.onChange();
1546
- return;
1547
- }
1548
- editor.history.undos.push(step), editor.history.redos.pop();
1549
- }
1575
+ });
1576
+ });
1577
+ });
1578
+ } catch (err) {
1579
+ debug$d("Could not perform redo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
1580
+ undos: [],
1581
+ redos: []
1582
+ }, SAVING.set(editor, !0), setIsRedoing(editor, !1), editor.onChange();
1583
+ return;
1550
1584
  }
1551
- }, editor;
1552
- };
1553
- }
1585
+ editor.history.undos.push(step), editor.history.redos.pop();
1586
+ }
1587
+ }
1588
+ };
1554
1589
  function transformOperation(editor, patch, operation, snapshot, previousSnapshot) {
1555
1590
  const transformedOperation = {
1556
1591
  ...operation
@@ -2291,7 +2326,7 @@ const converterJson = {
2291
2326
  reason: "Data is not an array"
2292
2327
  };
2293
2328
  const parsedBlocks = blocks.flatMap((block) => {
2294
- const parsedBlock = parseBlocks.parseBlock({
2329
+ const parsedBlock = util_blockOffsetsToSelection.parseBlock({
2295
2330
  context,
2296
2331
  block,
2297
2332
  options: {
@@ -2693,265 +2728,393 @@ const insertBreakActionImplementation = ({
2693
2728
  }) => {
2694
2729
  slate.insertText(action.editor, `
2695
2730
  `);
2696
- }, IS_APPLYING_BEHAVIOR_ACTIONS = /* @__PURE__ */ new WeakMap();
2697
- function withApplyingBehaviorActions(editor, fn) {
2698
- const prev = isApplyingBehaviorActions(editor);
2699
- IS_APPLYING_BEHAVIOR_ACTIONS.set(editor, !0), fn(), IS_APPLYING_BEHAVIOR_ACTIONS.set(editor, prev);
2700
- }
2701
- function isApplyingBehaviorActions(editor) {
2702
- return IS_APPLYING_BEHAVIOR_ACTIONS.get(editor) ?? !1;
2731
+ }, toggleListItemActionImplementation = ({
2732
+ context,
2733
+ action
2734
+ }) => {
2735
+ isListItemActive({
2736
+ editor: action.editor,
2737
+ listItem: action.listItem
2738
+ }) ? removeListItemActionImplementation({
2739
+ context,
2740
+ action: {
2741
+ ...action,
2742
+ type: "list item.remove"
2743
+ }
2744
+ }) : addListItemActionImplementation({
2745
+ context,
2746
+ action: {
2747
+ ...action,
2748
+ type: "list item.add"
2749
+ }
2750
+ });
2751
+ }, removeListItemActionImplementation = ({
2752
+ context,
2753
+ action
2754
+ }) => {
2755
+ if (!action.editor.selection)
2756
+ return;
2757
+ const guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
2758
+ at: action.editor.selection,
2759
+ match: (node) => guards.isListBlock(node)
2760
+ })];
2761
+ for (const [, at] of selectedBlocks)
2762
+ slate.Transforms.unsetNodes(action.editor, ["listItem", "level"], {
2763
+ at
2764
+ });
2765
+ }, addListItemActionImplementation = ({
2766
+ context,
2767
+ action
2768
+ }) => {
2769
+ if (!action.editor.selection)
2770
+ return;
2771
+ const guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
2772
+ at: action.editor.selection,
2773
+ match: (node) => guards.isTextBlock(node)
2774
+ })];
2775
+ for (const [, at] of selectedBlocks)
2776
+ slate.Transforms.setNodes(action.editor, {
2777
+ level: 1,
2778
+ listItem: action.listItem
2779
+ }, {
2780
+ at
2781
+ });
2782
+ };
2783
+ function isListItemActive({
2784
+ editor,
2785
+ listItem
2786
+ }) {
2787
+ if (!editor.selection)
2788
+ return !1;
2789
+ const selectedBlocks = [...slate.Editor.nodes(editor, {
2790
+ at: editor.selection,
2791
+ match: (node) => editor.isTextBlock(node)
2792
+ })];
2793
+ return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => editor.isListBlock(node) && node.listItem === listItem) : !1;
2703
2794
  }
2704
- function createWithEventListeners(editorActor, subscriptions) {
2705
- return function(editor) {
2706
- if (editorActor.getSnapshot().context.maxBlocks !== void 0)
2707
- return editor;
2708
- subscriptions.push(() => {
2709
- const subscription = editorActor.on("*", (event) => {
2710
- switch (event.type) {
2711
- // These events are not relevant for Behaviors
2712
- case "blurred":
2713
- case "done loading":
2714
- case "editable":
2715
- case "error":
2716
- case "focused":
2717
- case "invalid value":
2718
- case "loading":
2719
- case "mutation":
2720
- case "patch":
2721
- case "patches":
2722
- case "read only":
2723
- case "ready":
2724
- case "selection":
2725
- case "value changed":
2726
- case "unset":
2727
- break;
2728
- case "custom.*":
2729
- editorActor.send({
2730
- type: "custom behavior event",
2731
- behaviorEvent: event.event,
2732
- editor
2733
- });
2734
- break;
2735
- default:
2736
- editorActor.send({
2737
- type: "behavior event",
2738
- behaviorEvent: event,
2739
- editor
2740
- });
2741
- break;
2742
- }
2743
- });
2744
- return () => {
2745
- subscription.unsubscribe();
2746
- };
2795
+ const toggleStyleActionImplementation = ({
2796
+ context,
2797
+ action
2798
+ }) => {
2799
+ isStyleActive({
2800
+ editor: action.editor,
2801
+ style: action.style
2802
+ }) ? removeStyleActionImplementation({
2803
+ context,
2804
+ action: {
2805
+ ...action,
2806
+ type: "style.remove"
2807
+ }
2808
+ }) : addStyleActionImplementation({
2809
+ context,
2810
+ action: {
2811
+ ...action,
2812
+ type: "style.add"
2813
+ }
2814
+ });
2815
+ }, removeStyleActionImplementation = ({
2816
+ context,
2817
+ action
2818
+ }) => {
2819
+ if (!action.editor.selection)
2820
+ return;
2821
+ const defaultStyle = context.schema.styles[0].value, guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
2822
+ at: action.editor.selection,
2823
+ match: (node) => guards.isTextBlock(node)
2824
+ })];
2825
+ for (const [, at] of selectedBlocks)
2826
+ slate.Transforms.setNodes(action.editor, {
2827
+ style: defaultStyle
2828
+ }, {
2829
+ at
2747
2830
  });
2748
- const {
2749
- deleteBackward,
2750
- deleteForward,
2751
- insertBreak,
2752
- insertData,
2753
- insertText,
2754
- select,
2755
- setFragmentData
2756
- } = editor;
2757
- return editor.deleteBackward = (unit) => {
2758
- if (isApplyingBehaviorActions(editor)) {
2759
- deleteBackward(unit);
2760
- return;
2761
- }
2762
- editorActor.send({
2763
- type: "behavior event",
2764
- behaviorEvent: {
2765
- type: "delete.backward",
2766
- unit
2767
- },
2768
- editor
2769
- });
2770
- }, editor.deleteForward = (unit) => {
2771
- if (isApplyingBehaviorActions(editor)) {
2772
- deleteForward(unit);
2773
- return;
2774
- }
2775
- editorActor.send({
2776
- type: "behavior event",
2777
- behaviorEvent: {
2778
- type: "delete.forward",
2779
- unit
2780
- },
2781
- editor
2782
- });
2783
- }, editor.insertBreak = () => {
2784
- if (isApplyingBehaviorActions(editor)) {
2785
- insertBreak();
2786
- return;
2831
+ }, addStyleActionImplementation = ({
2832
+ context,
2833
+ action
2834
+ }) => {
2835
+ if (!action.editor.selection)
2836
+ return;
2837
+ const guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
2838
+ at: action.editor.selection,
2839
+ match: (node) => guards.isTextBlock(node)
2840
+ })];
2841
+ for (const [, at] of selectedBlocks)
2842
+ slate.Transforms.setNodes(action.editor, {
2843
+ style: action.style
2844
+ }, {
2845
+ at
2846
+ });
2847
+ };
2848
+ function isStyleActive({
2849
+ editor,
2850
+ style
2851
+ }) {
2852
+ if (!editor.selection)
2853
+ return !1;
2854
+ const selectedBlocks = [...slate.Editor.nodes(editor, {
2855
+ at: editor.selection,
2856
+ match: (node) => editor.isTextBlock(node)
2857
+ })];
2858
+ return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => node.style === style) : !1;
2859
+ }
2860
+ function isPortableTextSpan(node) {
2861
+ return node._type === "span" && "text" in node && typeof node.text == "string" && (typeof node.marks > "u" || Array.isArray(node.marks) && node.marks.every((mark) => typeof mark == "string"));
2862
+ }
2863
+ function isPortableTextBlock(node) {
2864
+ return (
2865
+ // A block doesn't _have_ to be named 'block' - to differentiate between
2866
+ // allowed child types and marks, one might name them differently
2867
+ typeof node._type == "string" && // Toolkit-types like nested spans are @-prefixed
2868
+ node._type[0] !== "@" && // `markDefs` isn't _required_ per say, but if it's there, it needs to be an array
2869
+ (!("markDefs" in node) || !node.markDefs || Array.isArray(node.markDefs) && // Every mark definition needs to have an `_key` to be mappable in child spans
2870
+ node.markDefs.every((def) => typeof def._key == "string")) && // `children` is required and needs to be an array
2871
+ "children" in node && Array.isArray(node.children) && // All children are objects with `_type` (usually spans, but can contain other stuff)
2872
+ node.children.every((child) => typeof child == "object" && "_type" in child)
2873
+ );
2874
+ }
2875
+ const decoratorAddActionImplementation = ({
2876
+ context,
2877
+ action
2878
+ }) => {
2879
+ const editor = action.editor, mark = action.decorator, selection = action.selection ? toSlateRange(action.selection, action.editor) ?? editor.selection : editor.selection;
2880
+ if (!selection)
2881
+ return;
2882
+ const value = fromSlateValue(editor.children, context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(editor)), editorSelection = toPortableTextRange(value, selection, context.schema), anchorOffset = editorSelection ? util_reverseSelection.spanSelectionPointToBlockOffset({
2883
+ value,
2884
+ selectionPoint: editorSelection.anchor
2885
+ }) : void 0, focusOffset = editorSelection ? util_reverseSelection.spanSelectionPointToBlockOffset({
2886
+ value,
2887
+ selectionPoint: editorSelection.focus
2888
+ }) : void 0;
2889
+ if (!anchorOffset || !focusOffset)
2890
+ throw new Error("Unable to find anchor or focus offset");
2891
+ if (slate.Range.isExpanded(selection)) {
2892
+ slate.Transforms.setNodes(editor, {}, {
2893
+ at: selection,
2894
+ match: slate.Text.isText,
2895
+ split: !0,
2896
+ hanging: !0
2897
+ });
2898
+ const newValue = fromSlateValue(editor.children, context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(editor)), newSelection = util_blockOffsetsToSelection.blockOffsetsToSelection({
2899
+ value: newValue,
2900
+ offsets: {
2901
+ anchor: anchorOffset,
2902
+ focus: focusOffset
2903
+ },
2904
+ backward: editorSelection?.backward
2905
+ }), trimmedSelection = selector_getTrimmedSelection.getTrimmedSelection({
2906
+ context: {
2907
+ activeDecorators: [],
2908
+ converters: [],
2909
+ keyGenerator: context.keyGenerator,
2910
+ schema: context.schema,
2911
+ selection: newSelection,
2912
+ value: newValue
2787
2913
  }
2788
- editorActor.send({
2789
- type: "behavior event",
2790
- behaviorEvent: {
2791
- type: "insert.break"
2792
- },
2793
- editor
2914
+ });
2915
+ if (!trimmedSelection)
2916
+ throw new Error("Unable to find trimmed selection");
2917
+ const newRange = toSlateRange(trimmedSelection, editor);
2918
+ if (!newRange)
2919
+ throw new Error("Unable to find new selection");
2920
+ const splitTextNodes = slate.Range.isRange(newRange) ? [...slate.Editor.nodes(editor, {
2921
+ at: newRange,
2922
+ match: (node) => slate.Text.isText(node)
2923
+ })] : [];
2924
+ for (const [node, path] of splitTextNodes) {
2925
+ const marks = [...(Array.isArray(node.marks) ? node.marks : []).filter((eMark) => eMark !== mark), mark];
2926
+ slate.Transforms.setNodes(editor, {
2927
+ marks
2928
+ }, {
2929
+ at: path,
2930
+ match: slate.Text.isText,
2931
+ split: !0,
2932
+ hanging: !0
2794
2933
  });
2795
- }, editor.insertData = (dataTransfer) => {
2796
- if (isApplyingBehaviorActions(editor)) {
2797
- insertData(dataTransfer);
2798
- return;
2799
- }
2800
- editorActor.send({
2801
- type: "behavior event",
2802
- behaviorEvent: {
2803
- type: "deserialize",
2804
- dataTransfer
2805
- },
2806
- editor
2934
+ }
2935
+ } else {
2936
+ const [block, blockPath] = slate.Editor.node(editor, selection, {
2937
+ depth: 1
2938
+ }), lonelyEmptySpan = editor.isTextBlock(block) && block.children.length === 1 && editor.isTextSpan(block.children[0]) && block.children[0].text === "" ? block.children[0] : void 0;
2939
+ if (lonelyEmptySpan) {
2940
+ const existingMarks = lonelyEmptySpan.marks ?? [], existingMarksWithoutDecorator = existingMarks.filter((existingMark) => existingMark !== mark);
2941
+ slate.Transforms.setNodes(editor, {
2942
+ marks: existingMarks.length === existingMarksWithoutDecorator.length ? [...existingMarks, mark] : existingMarksWithoutDecorator
2943
+ }, {
2944
+ at: blockPath,
2945
+ match: (node) => editor.isTextSpan(node)
2807
2946
  });
2808
- }, editor.insertSoftBreak = () => {
2809
- if (isApplyingBehaviorActions(editor)) {
2810
- insertSoftBreakActionImplementation({
2811
- context: {
2812
- keyGenerator: editorActor.getSnapshot().context.keyGenerator,
2813
- schema: editorActor.getSnapshot().context.schema
2814
- },
2815
- action: {
2816
- type: "insert.soft break",
2817
- editor
2947
+ } else {
2948
+ const existingMarks = {
2949
+ ...slate.Editor.marks(editor) || {}
2950
+ }.marks || [], marks = {
2951
+ ...slate.Editor.marks(editor) || {},
2952
+ marks: [...existingMarks, mark]
2953
+ };
2954
+ editor.marks = marks;
2955
+ }
2956
+ }
2957
+ if (editor.selection) {
2958
+ const selection2 = editor.selection;
2959
+ editor.selection = {
2960
+ ...selection2
2961
+ };
2962
+ }
2963
+ };
2964
+ function getPreviousSpan({
2965
+ editor,
2966
+ blockPath,
2967
+ spanPath
2968
+ }) {
2969
+ let previousSpan;
2970
+ for (const [child, childPath] of slate.Node.children(editor, blockPath, {
2971
+ reverse: !0
2972
+ }))
2973
+ if (editor.isTextSpan(child) && slate.Path.isBefore(childPath, spanPath)) {
2974
+ previousSpan = child;
2975
+ break;
2976
+ }
2977
+ return previousSpan;
2978
+ }
2979
+ function getNextSpan({
2980
+ editor,
2981
+ blockPath,
2982
+ spanPath
2983
+ }) {
2984
+ let nextSpan;
2985
+ for (const [child, childPath] of slate.Node.children(editor, blockPath))
2986
+ if (editor.isTextSpan(child) && slate.Path.isAfter(childPath, spanPath)) {
2987
+ nextSpan = child;
2988
+ break;
2989
+ }
2990
+ return nextSpan;
2991
+ }
2992
+ const debug$9 = debugWithName("plugin:withPortableTextMarkModel");
2993
+ function createWithPortableTextMarkModel(editorActor, types2) {
2994
+ return function(editor) {
2995
+ const {
2996
+ apply: apply2,
2997
+ normalizeNode
2998
+ } = editor, decorators = types2.decorators.map((t) => t.value);
2999
+ return editor.normalizeNode = (nodeEntry) => {
3000
+ const [node, path] = nodeEntry;
3001
+ if (editor.isTextBlock(node)) {
3002
+ const children = slate.Node.children(editor, path);
3003
+ for (const [child, childPath] of children) {
3004
+ const nextNode = node.children[childPath[1] + 1];
3005
+ if (editor.isTextSpan(child) && editor.isTextSpan(nextNode) && child.marks?.every((mark) => nextNode.marks?.includes(mark)) && nextNode.marks?.every((mark) => child.marks?.includes(mark))) {
3006
+ debug$9("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
3007
+ type: "normalizing"
3008
+ }), slate.Transforms.mergeNodes(editor, {
3009
+ at: [childPath[0], childPath[1] + 1],
3010
+ voids: !0
3011
+ }), editorActor.send({
3012
+ type: "done normalizing"
3013
+ });
3014
+ return;
2818
3015
  }
2819
- });
2820
- return;
3016
+ }
2821
3017
  }
2822
- editorActor.send({
2823
- type: "behavior event",
2824
- behaviorEvent: {
2825
- type: "insert.soft break"
2826
- },
2827
- editor
2828
- });
2829
- }, editor.insertText = (text, options) => {
2830
- if (isApplyingBehaviorActions(editor)) {
2831
- insertText(text, options);
3018
+ if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {
3019
+ debug$9("Adding .markDefs to block node"), editorActor.send({
3020
+ type: "normalizing"
3021
+ }), slate.Transforms.setNodes(editor, {
3022
+ markDefs: []
3023
+ }, {
3024
+ at: path
3025
+ }), editorActor.send({
3026
+ type: "done normalizing"
3027
+ });
2832
3028
  return;
2833
3029
  }
2834
- editorActor.send({
2835
- type: "behavior event",
2836
- behaviorEvent: {
2837
- type: "insert.text",
2838
- text,
2839
- options
2840
- },
2841
- editor,
2842
- defaultActionCallback: () => {
2843
- insertText(text, options);
2844
- }
2845
- });
2846
- }, editor.select = (location) => {
2847
- if (isApplyingBehaviorActions(editor)) {
2848
- select(location);
3030
+ if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {
3031
+ debug$9("Adding .marks to span node"), editorActor.send({
3032
+ type: "normalizing"
3033
+ }), slate.Transforms.setNodes(editor, {
3034
+ marks: []
3035
+ }, {
3036
+ at: path
3037
+ }), editorActor.send({
3038
+ type: "done normalizing"
3039
+ });
2849
3040
  return;
2850
3041
  }
2851
- const range = slate.Editor.range(editor, location);
2852
- editorActor.send({
2853
- type: "behavior event",
2854
- behaviorEvent: {
2855
- type: "select",
2856
- selection: toPortableTextRange(fromSlateValue(editor.children, editorActor.getSnapshot().context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(editor)), range, editorActor.getSnapshot().context.schema)
2857
- },
2858
- editor,
2859
- defaultActionCallback: () => {
2860
- select(location);
3042
+ if (editor.isTextSpan(node)) {
3043
+ const blockPath = slate.Path.parent(path), [block] = slate.Editor.node(editor, blockPath), decorators2 = types2.decorators.map((decorator) => decorator.value), annotations = node.marks?.filter((mark) => !decorators2.includes(mark));
3044
+ if (editor.isTextBlock(block) && node.text === "" && annotations && annotations.length > 0) {
3045
+ debug$9("Removing annotations from empty span node"), editorActor.send({
3046
+ type: "normalizing"
3047
+ }), slate.Transforms.setNodes(editor, {
3048
+ marks: node.marks?.filter((mark) => decorators2.includes(mark))
3049
+ }, {
3050
+ at: path
3051
+ }), editorActor.send({
3052
+ type: "done normalizing"
3053
+ });
3054
+ return;
2861
3055
  }
2862
- });
2863
- }, editor.setFragmentData = (dataTransfer, originEvent) => {
2864
- if (originEvent === "drag") {
2865
- setFragmentData(dataTransfer);
2866
- return;
2867
3056
  }
2868
- if (isApplyingBehaviorActions(editor)) {
2869
- setFragmentData(dataTransfer);
2870
- return;
3057
+ if (editor.isTextBlock(node)) {
3058
+ const decorators2 = types2.decorators.map((decorator) => decorator.value);
3059
+ for (const [child, childPath] of slate.Node.children(editor, path))
3060
+ if (editor.isTextSpan(child)) {
3061
+ const marks = child.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !node.markDefs?.find((def) => def._key === mark));
3062
+ if (orphanedAnnotations.length > 0) {
3063
+ debug$9("Removing orphaned annotations from span node"), editorActor.send({
3064
+ type: "normalizing"
3065
+ }), slate.Transforms.setNodes(editor, {
3066
+ marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
3067
+ }, {
3068
+ at: childPath
3069
+ }), editorActor.send({
3070
+ type: "done normalizing"
3071
+ });
3072
+ return;
3073
+ }
3074
+ }
2871
3075
  }
2872
- dataTransfer.clearData(), editorActor.send({
2873
- type: "behavior event",
2874
- behaviorEvent: {
2875
- type: "serialize",
2876
- dataTransfer,
2877
- originEvent: originEvent ?? "unknown"
2878
- },
2879
- editor
2880
- });
2881
- }, editor;
2882
- };
2883
- }
2884
- function createWithMaxBlocks(editorActor) {
2885
- return function(editor) {
2886
- const {
2887
- apply: apply2
2888
- } = editor;
2889
- return editor.apply = (operation) => {
2890
- if (editorActor.getSnapshot().matches({
2891
- "edit mode": "read only"
2892
- })) {
2893
- apply2(operation);
2894
- return;
2895
- }
2896
- if (isChangingRemotely(editor)) {
2897
- apply2(operation);
2898
- return;
2899
- }
2900
- if (isUndoing(editor) || isRedoing(editor)) {
2901
- apply2(operation);
2902
- return;
2903
- }
2904
- const rows = editorActor.getSnapshot().context.maxBlocks ?? -1;
2905
- rows > 0 && editor.children.length >= rows && (operation.type === "insert_node" || operation.type === "split_node") && operation.path.length === 1 || apply2(operation);
2906
- }, editor;
2907
- };
2908
- }
2909
- function createWithObjectKeys(editorActor, schemaTypes) {
2910
- return function(editor) {
2911
- const {
2912
- apply: apply2,
2913
- normalizeNode
2914
- } = editor;
2915
- return editor.apply = (operation) => {
2916
- if (isChangingRemotely(editor)) {
2917
- apply2(operation);
2918
- return;
2919
- }
2920
- if (isUndoing(editor) || isRedoing(editor)) {
2921
- apply2(operation);
2922
- return;
2923
- }
2924
- if (operation.type === "split_node") {
2925
- const existingKeys = [...slate.Node.descendants(editor)].map(([node]) => node._key);
2926
- apply2({
2927
- ...operation,
2928
- properties: {
2929
- ...operation.properties,
2930
- _key: operation.properties._key === void 0 || existingKeys.includes(operation.properties._key) ? editorActor.getSnapshot().context.keyGenerator() : operation.properties._key
3076
+ if (editor.isTextSpan(node)) {
3077
+ const blockPath = slate.Path.parent(path), [block] = slate.Editor.node(editor, blockPath);
3078
+ if (editor.isTextBlock(block)) {
3079
+ const decorators2 = types2.decorators.map((decorator) => decorator.value), marks = node.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !block.markDefs?.find((def) => def._key === mark));
3080
+ if (orphanedAnnotations.length > 0) {
3081
+ debug$9("Removing orphaned annotations from span node"), editorActor.send({
3082
+ type: "normalizing"
3083
+ }), slate.Transforms.setNodes(editor, {
3084
+ marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
3085
+ }, {
3086
+ at: path
3087
+ }), editorActor.send({
3088
+ type: "done normalizing"
3089
+ });
3090
+ return;
2931
3091
  }
2932
- });
2933
- return;
3092
+ }
2934
3093
  }
2935
- if (operation.type === "insert_node" && !slate.Editor.isEditor(operation.node)) {
2936
- const existingKeys = [...slate.Node.descendants(editor)].map(([node]) => node._key);
2937
- apply2({
2938
- ...operation,
2939
- node: {
2940
- ...operation.node,
2941
- _key: operation.node._key === void 0 || existingKeys.includes(operation.node._key) ? editorActor.getSnapshot().context.keyGenerator() : operation.node._key
2942
- }
2943
- });
2944
- return;
3094
+ if (editor.isTextBlock(node)) {
3095
+ const markDefs = node.markDefs ?? [], markDefKeys = /* @__PURE__ */ new Set(), newMarkDefs = [];
3096
+ for (const markDef of markDefs)
3097
+ markDefKeys.has(markDef._key) || (markDefKeys.add(markDef._key), newMarkDefs.push(markDef));
3098
+ if (markDefs.length !== newMarkDefs.length) {
3099
+ debug$9("Removing duplicate markDefs"), editorActor.send({
3100
+ type: "normalizing"
3101
+ }), slate.Transforms.setNodes(editor, {
3102
+ markDefs: newMarkDefs
3103
+ }, {
3104
+ at: path
3105
+ }), editorActor.send({
3106
+ type: "done normalizing"
3107
+ });
3108
+ return;
3109
+ }
2945
3110
  }
2946
- apply2(operation);
2947
- }, editor.normalizeNode = (entry) => {
2948
- const [node, path] = entry;
2949
- if (slate.Element.isElement(node) && node._type === schemaTypes.block.name) {
2950
- if (!node._key) {
2951
- editorActor.send({
3111
+ if (editor.isTextBlock(node) && !editor.operations.some((op) => op.type === "merge_node" && "markDefs" in op.properties && op.path.length === 1)) {
3112
+ const newMarkDefs = (node.markDefs || []).filter((def) => node.children.find((child) => slate.Text.isText(child) && Array.isArray(child.marks) && child.marks.includes(def._key)));
3113
+ if (node.markDefs && !isEqual__default.default(newMarkDefs, node.markDefs)) {
3114
+ debug$9("Removing markDef not in use"), editorActor.send({
2952
3115
  type: "normalizing"
2953
3116
  }), slate.Transforms.setNodes(editor, {
2954
- _key: editorActor.getSnapshot().context.keyGenerator()
3117
+ markDefs: newMarkDefs
2955
3118
  }, {
2956
3119
  at: path
2957
3120
  }), editorActor.send({
@@ -2959,1279 +3122,325 @@ function createWithObjectKeys(editorActor, schemaTypes) {
2959
3122
  });
2960
3123
  return;
2961
3124
  }
2962
- for (const [child, childPath] of slate.Node.children(editor, path))
2963
- if (!child._key) {
2964
- editorActor.send({
2965
- type: "normalizing"
2966
- }), slate.Transforms.setNodes(editor, {
2967
- _key: editorActor.getSnapshot().context.keyGenerator()
2968
- }, {
2969
- at: childPath
2970
- }), editorActor.send({
2971
- type: "done normalizing"
3125
+ }
3126
+ normalizeNode(nodeEntry);
3127
+ }, editor.apply = (op) => {
3128
+ if (isChangingRemotely(editor)) {
3129
+ apply2(op);
3130
+ return;
3131
+ }
3132
+ if (isUndoing(editor) || isRedoing(editor)) {
3133
+ apply2(op);
3134
+ return;
3135
+ }
3136
+ if (op.type === "set_selection" && slate.Editor.marks(editor) && op.properties && op.newProperties && op.properties.anchor && op.properties.focus && op.newProperties.anchor && op.newProperties.focus) {
3137
+ const previousSelectionIsCollapsed = slate.Range.isCollapsed({
3138
+ anchor: op.properties.anchor,
3139
+ focus: op.properties.focus
3140
+ }), newSelectionIsCollapsed = slate.Range.isCollapsed({
3141
+ anchor: op.newProperties.anchor,
3142
+ focus: op.newProperties.focus
3143
+ });
3144
+ if (previousSelectionIsCollapsed && newSelectionIsCollapsed) {
3145
+ const focusSpan = Array.from(slate.Editor.nodes(editor, {
3146
+ mode: "lowest",
3147
+ at: op.properties.focus,
3148
+ match: (n) => editor.isTextSpan(n),
3149
+ voids: !1
3150
+ }))[0]?.[0], newFocusSpan = Array.from(slate.Editor.nodes(editor, {
3151
+ mode: "lowest",
3152
+ at: op.newProperties.focus,
3153
+ match: (n) => editor.isTextSpan(n),
3154
+ voids: !1
3155
+ }))[0]?.[0], movedToNextSpan = focusSpan && newFocusSpan && op.newProperties.focus.path[0] === op.properties.focus.path[0] && op.newProperties.focus.path[1] === op.properties.focus.path[1] + 1 && focusSpan.text.length === op.properties.focus.offset && op.newProperties.focus.offset === 0, movedToPreviousSpan = focusSpan && newFocusSpan && op.newProperties.focus.path[0] === op.properties.focus.path[0] && op.newProperties.focus.path[1] === op.properties.focus.path[1] - 1 && op.properties.focus.offset === 0 && newFocusSpan.text.length === op.newProperties.focus.offset;
3156
+ if (movedToNextSpan || movedToPreviousSpan)
3157
+ return;
3158
+ }
3159
+ }
3160
+ if (op.type === "insert_node") {
3161
+ const {
3162
+ selection
3163
+ } = editor;
3164
+ if (selection) {
3165
+ const [_block, blockPath] = slate.Editor.node(editor, selection, {
3166
+ depth: 1
3167
+ }), previousSpan = getPreviousSpan({
3168
+ editor,
3169
+ blockPath,
3170
+ spanPath: op.path
3171
+ }), previousSpanAnnotations = previousSpan ? previousSpan.marks?.filter((mark) => !decorators.includes(mark)) : [], nextSpan = getNextSpan({
3172
+ editor,
3173
+ blockPath,
3174
+ spanPath: [op.path[0], op.path[1] - 1]
3175
+ }), nextSpanAnnotations = nextSpan ? nextSpan.marks?.filter((mark) => !decorators.includes(mark)) : [], annotationsEnding = previousSpanAnnotations?.filter((annotation) => !nextSpanAnnotations?.includes(annotation)) ?? [], atTheEndOfAnnotation = annotationsEnding.length > 0;
3176
+ if (atTheEndOfAnnotation && isPortableTextSpan(op.node) && op.node.marks?.some((mark) => annotationsEnding.includes(mark))) {
3177
+ slate.Transforms.insertNodes(editor, {
3178
+ ...op.node,
3179
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3180
+ marks: op.node.marks?.filter((mark) => !annotationsEnding.includes(mark)) ?? []
2972
3181
  });
2973
3182
  return;
2974
3183
  }
3184
+ const annotationsStarting = nextSpanAnnotations?.filter((annotation) => !previousSpanAnnotations?.includes(annotation)) ?? [], atTheStartOfAnnotation = annotationsStarting.length > 0;
3185
+ if (atTheStartOfAnnotation && isPortableTextSpan(op.node) && op.node.marks?.some((mark) => annotationsStarting.includes(mark))) {
3186
+ slate.Transforms.insertNodes(editor, {
3187
+ ...op.node,
3188
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3189
+ marks: op.node.marks?.filter((mark) => !annotationsStarting.includes(mark)) ?? []
3190
+ });
3191
+ return;
3192
+ }
3193
+ const nextSpanDecorators = nextSpan?.marks?.filter((mark) => decorators.includes(mark)) ?? [];
3194
+ if (nextSpanDecorators.length > 0 && atTheEndOfAnnotation && !atTheStartOfAnnotation && isPortableTextSpan(op.node) && op.node.marks?.length === 0) {
3195
+ slate.Transforms.insertNodes(editor, {
3196
+ ...op.node,
3197
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3198
+ marks: nextSpanDecorators
3199
+ });
3200
+ return;
3201
+ }
3202
+ }
2975
3203
  }
2976
- normalizeNode(entry);
2977
- }, editor;
2978
- };
2979
- }
2980
- const debug$9 = debugWithName("applyPatches"), debugVerbose = debug$9.enabled && !0;
2981
- function createApplyPatch(schemaTypes) {
2982
- return (editor, patch) => {
2983
- let changed = !1;
2984
- debugVerbose && (debug$9(`
2985
-
2986
- NEW PATCH =============================================================`), debug$9(JSON.stringify(patch, null, 2)));
2987
- try {
2988
- switch (patch.type) {
2989
- case "insert":
2990
- changed = insertPatch(editor, patch, schemaTypes);
2991
- break;
2992
- case "unset":
2993
- changed = unsetPatch(editor, patch);
2994
- break;
2995
- case "set":
2996
- changed = setPatch(editor, patch);
2997
- break;
2998
- case "diffMatchPatch":
2999
- changed = diffMatchPatch(editor, patch);
3000
- break;
3001
- default:
3002
- debug$9("Unhandled patch", patch.type);
3003
- }
3004
- } catch (err) {
3005
- console.error(err);
3006
- }
3007
- return changed;
3008
- };
3009
- }
3010
- function diffMatchPatch(editor, patch) {
3011
- const {
3012
- block,
3013
- child,
3014
- childPath
3015
- } = findBlockAndChildFromPath(editor, patch.path);
3016
- if (!block)
3017
- return debug$9("Block not found"), !1;
3018
- if (!child || !childPath)
3019
- return debug$9("Child not found"), !1;
3020
- if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
3021
- return !1;
3022
- const patches2 = parse(patch.value), [newValue] = apply(patches2, child.text, {
3023
- allowExceedingIndices: !0
3024
- }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
3025
- debugState(editor, "before");
3026
- let offset = 0;
3027
- for (const [op, text] of diff$1)
3028
- op === DIFF_INSERT ? (editor.apply({
3029
- type: "insert_text",
3030
- path: childPath,
3031
- offset,
3032
- text
3033
- }), offset += text.length) : op === DIFF_DELETE ? editor.apply({
3034
- type: "remove_text",
3035
- path: childPath,
3036
- offset,
3037
- text
3038
- }) : op === DIFF_EQUAL && (offset += text.length);
3039
- return debugState(editor, "after"), !0;
3040
- }
3041
- function insertPatch(editor, patch, schemaTypes) {
3042
- const {
3043
- block: targetBlock,
3044
- child: targetChild,
3045
- blockPath: targetBlockPath,
3046
- childPath: targetChildPath
3047
- } = findBlockAndChildFromPath(editor, patch.path);
3048
- if (!targetBlock || !targetBlockPath)
3049
- return debug$9("Block not found"), !1;
3050
- if (patch.path.length > 1 && patch.path[1] !== "children")
3051
- return debug$9("Ignoring patch targeting void value"), !1;
3052
- if (patch.path.length === 1) {
3053
- const {
3054
- items: items2,
3055
- position: position2
3056
- } = patch, blocksToInsert = toSlateValue(items2, {
3057
- schemaTypes
3058
- }, KEY_TO_SLATE_ELEMENT.get(editor)), targetBlockIndex = targetBlockPath[0], normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex;
3059
- return debug$9(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
3060
- at: [normalizedIdx2]
3061
- }), debugState(editor, "after"), !0;
3062
- }
3063
- const {
3064
- items,
3065
- position
3066
- } = patch;
3067
- if (!targetChild || !targetChildPath)
3068
- return debug$9("Child not found"), !1;
3069
- const childrenToInsert = targetBlock && toSlateValue([{
3070
- ...targetBlock,
3071
- children: items
3072
- }], {
3073
- schemaTypes
3074
- }, KEY_TO_SLATE_ELEMENT.get(editor)), targetChildIndex = targetChildPath[1], normalizedIdx = position === "after" ? targetChildIndex + 1 : targetChildIndex, childInsertPath = [targetChildPath[0], normalizedIdx];
3075
- return debug$9(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
3076
- at: childInsertPath
3077
- }), debugState(editor, "after"), !0;
3078
- }
3079
- function setPatch(editor, patch) {
3080
- let value = patch.value;
3081
- typeof patch.path[3] == "string" && (value = {}, value[patch.path[3]] = patch.value);
3082
- const {
3083
- block,
3084
- blockPath,
3085
- child,
3086
- childPath
3087
- } = findBlockAndChildFromPath(editor, patch.path);
3088
- if (!block)
3089
- return debug$9("Block not found"), !1;
3090
- const isTextBlock = editor.isTextBlock(block);
3091
- if (isTextBlock && patch.path.length > 1 && patch.path[1] !== "children")
3092
- return debug$9("Ignoring setting void value"), !1;
3093
- if (debugState(editor, "before"), isTextBlock && child && childPath) {
3094
- if (slate.Text.isText(value) && slate.Text.isText(child)) {
3095
- const newText = child.text;
3096
- value.text !== newText && (debug$9("Setting text property"), editor.apply({
3097
- type: "remove_text",
3098
- path: childPath,
3099
- offset: 0,
3100
- text: newText
3101
- }), editor.apply({
3102
- type: "insert_text",
3103
- path: childPath,
3104
- offset: 0,
3105
- text: value.text
3106
- }), editor.onChange());
3107
- } else
3108
- debug$9("Setting non-text property"), editor.apply({
3109
- type: "set_node",
3110
- path: childPath,
3111
- properties: {},
3112
- newProperties: value
3113
- });
3114
- return !0;
3115
- } else if (slate.Element.isElement(block) && patch.path.length === 1 && blockPath) {
3116
- debug$9("Setting block property");
3117
- const {
3118
- children,
3119
- ...nextRest
3120
- } = value, {
3121
- children: prevChildren,
3122
- ...prevRest
3123
- } = block || {
3124
- children: void 0
3125
- };
3126
- editor.apply({
3127
- type: "set_node",
3128
- path: blockPath,
3129
- properties: {
3130
- ...prevRest
3131
- },
3132
- newProperties: nextRest
3133
- }), debug$9("Setting children"), block.children.forEach((c, cIndex) => {
3134
- editor.apply({
3135
- type: "remove_node",
3136
- path: blockPath.concat(block.children.length - 1 - cIndex),
3137
- node: c
3138
- });
3139
- }), Array.isArray(children) && children.forEach((c, cIndex) => {
3140
- editor.apply({
3141
- type: "insert_node",
3142
- path: blockPath.concat(cIndex),
3143
- node: c
3144
- });
3145
- });
3146
- } else if (block && "value" in block)
3147
- if (patch.path.length > 1 && patch.path[1] !== "children") {
3148
- const newVal = patches.applyAll(block.value, [{
3149
- ...patch,
3150
- path: patch.path.slice(1)
3151
- }]);
3152
- slate.Transforms.setNodes(editor, {
3153
- ...block,
3154
- value: newVal
3155
- }, {
3156
- at: blockPath
3157
- });
3158
- } else
3159
- return !1;
3160
- return debugState(editor, "after"), !0;
3161
- }
3162
- function unsetPatch(editor, patch) {
3163
- if (patch.path.length === 0) {
3164
- debug$9("Removing everything"), debugState(editor, "before");
3165
- const previousSelection = editor.selection;
3166
- return slate.Transforms.deselect(editor), editor.children.forEach((_child, i) => {
3167
- slate.Transforms.removeNodes(editor, {
3168
- at: [i]
3169
- });
3170
- }), slate.Transforms.insertNodes(editor, editor.pteCreateTextBlock({
3171
- decorators: []
3172
- })), previousSelection && slate.Transforms.select(editor, {
3173
- anchor: {
3174
- path: [0, 0],
3175
- offset: 0
3176
- },
3177
- focus: {
3178
- path: [0, 0],
3179
- offset: 0
3180
- }
3181
- }), editor.onChange(), debugState(editor, "after"), !0;
3182
- }
3183
- const {
3184
- block,
3185
- blockPath,
3186
- child,
3187
- childPath
3188
- } = findBlockAndChildFromPath(editor, patch.path);
3189
- if (patch.path.length === 1) {
3190
- if (!block || !blockPath)
3191
- return debug$9("Block not found"), !1;
3192
- const blockIndex = blockPath[0];
3193
- return debug$9(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
3194
- at: [blockIndex]
3195
- }), debugState(editor, "after"), !0;
3196
- }
3197
- return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$9("Child not found"), !1) : (debug$9(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose && debug$9(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
3198
- at: childPath
3199
- }), debugState(editor, "after"), !0) : !1;
3200
- }
3201
- function isKeyedSegment(segment) {
3202
- return typeof segment == "object" && "_key" in segment;
3203
- }
3204
- function debugState(editor, stateName) {
3205
- debugVerbose && (debug$9(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$9(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3206
- }
3207
- function findBlockFromPath(editor, path) {
3208
- let blockIndex = -1;
3209
- const block = editor.children.find((node, index) => {
3210
- const isMatch = isKeyedSegment(path[0]) ? node._key === path[0]._key : index === path[0];
3211
- return isMatch && (blockIndex = index), isMatch;
3212
- });
3213
- return block ? {
3214
- block,
3215
- path: [blockIndex]
3216
- } : {};
3217
- }
3218
- function findBlockAndChildFromPath(editor, path) {
3219
- const {
3220
- block,
3221
- path: blockPath
3222
- } = findBlockFromPath(editor, path);
3223
- if (!(slate.Element.isElement(block) && path[1] === "children"))
3224
- return {
3225
- block,
3226
- blockPath,
3227
- child: void 0,
3228
- childPath: void 0
3229
- };
3230
- let childIndex = -1;
3231
- const child = block.children.find((node, index) => {
3232
- const isMatch = isKeyedSegment(path[2]) ? node._key === path[2]._key : index === path[2];
3233
- return isMatch && (childIndex = index), isMatch;
3234
- });
3235
- return child ? {
3236
- block,
3237
- child,
3238
- blockPath,
3239
- childPath: blockPath?.concat(childIndex)
3240
- } : {
3241
- block,
3242
- blockPath,
3243
- child: void 0,
3244
- childPath: void 0
3245
- };
3246
- }
3247
- const debug$8 = debugWithName("plugin:withPatches");
3248
- function createWithPatches({
3249
- editorActor,
3250
- patchFunctions,
3251
- schemaTypes,
3252
- subscriptions
3253
- }) {
3254
- let previousChildren;
3255
- const applyPatch = createApplyPatch(schemaTypes);
3256
- return function(editor) {
3257
- IS_PROCESSING_REMOTE_CHANGES.set(editor, !1), PATCHING.set(editor, !0), previousChildren = [...editor.children];
3258
- const {
3259
- apply: apply2
3260
- } = editor;
3261
- let bufferedPatches = [];
3262
- const handleBufferedRemotePatches = () => {
3263
- if (bufferedPatches.length === 0)
3264
- return;
3265
- const patches2 = bufferedPatches;
3266
- bufferedPatches = [];
3267
- let changed = !1;
3268
- withRemoteChanges(editor, () => {
3269
- slate.Editor.withoutNormalizing(editor, () => {
3270
- withoutPatching(editor, () => {
3271
- withoutSaving(editor, () => {
3272
- patches2.forEach((patch) => {
3273
- debug$8.enabled && debug$8(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3274
- });
3275
- });
3276
- });
3277
- }), changed && (editor.normalize(), editor.onChange());
3278
- });
3279
- }, handlePatches = ({
3280
- patches: patches2
3281
- }) => {
3282
- const remotePatches = patches2.filter((p) => p.origin !== "local");
3283
- remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
3284
- };
3285
- return subscriptions.push(() => {
3286
- debug$8("Subscribing to remote patches");
3287
- const sub = editorActor.on("patches", handlePatches);
3288
- return () => {
3289
- debug$8("Unsubscribing to remote patches"), sub.unsubscribe();
3290
- };
3291
- }), editor.apply = (operation) => {
3292
- let patches$1 = [];
3293
- previousChildren = editor.children;
3294
- const editorWasEmpty = isEqualToEmptyEditor(previousChildren, schemaTypes);
3295
- apply2(operation);
3296
- const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes);
3297
- if (!isPatching(editor))
3298
- return editor;
3299
- switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches$1.push(patches.insert(previousChildren, "before", [0])), operation.type) {
3300
- case "insert_text":
3301
- patches$1 = [...patches$1, ...patchFunctions.insertTextPatch(editor, operation, previousChildren)];
3302
- break;
3303
- case "remove_text":
3304
- patches$1 = [...patches$1, ...patchFunctions.removeTextPatch(editor, operation, previousChildren)];
3305
- break;
3306
- case "remove_node":
3307
- patches$1 = [...patches$1, ...patchFunctions.removeNodePatch(editor, operation, previousChildren)];
3308
- break;
3309
- case "split_node":
3310
- patches$1 = [...patches$1, ...patchFunctions.splitNodePatch(editor, operation, previousChildren)];
3311
- break;
3312
- case "insert_node":
3313
- patches$1 = [...patches$1, ...patchFunctions.insertNodePatch(editor, operation, previousChildren)];
3314
- break;
3315
- case "set_node":
3316
- patches$1 = [...patches$1, ...patchFunctions.setNodePatch(editor, operation, previousChildren)];
3317
- break;
3318
- case "merge_node":
3319
- patches$1 = [...patches$1, ...patchFunctions.mergeNodePatch(editor, operation, previousChildren)];
3320
- break;
3321
- case "move_node":
3322
- patches$1 = [...patches$1, ...patchFunctions.moveNodePatch(editor, operation, previousChildren)];
3323
- break;
3324
- }
3325
- return !editorWasEmpty && editorIsEmpty && ["merge_node", "set_node", "remove_text", "remove_node"].includes(operation.type) && (patches$1 = [...patches$1, patches.unset([])], editorActor.send({
3326
- type: "notify.unset",
3327
- previousValue: fromSlateValue(previousChildren, schemaTypes.block.name, KEY_TO_VALUE_ELEMENT.get(editor))
3328
- })), editorWasEmpty && patches$1.length > 0 && (patches$1 = [patches.setIfMissing([], []), ...patches$1]), patches$1.length > 0 && patches$1.forEach((patch) => {
3329
- editorActor.send({
3330
- type: "patch",
3331
- patch: {
3332
- ...patch,
3333
- origin: "local"
3334
- }
3335
- });
3336
- }), editor;
3337
- }, editor;
3338
- };
3339
- }
3340
- const debug$7 = debugWithName("plugin:withPlaceholderBlock");
3341
- function createWithPlaceholderBlock(editorActor) {
3342
- return function(editor) {
3343
- const {
3344
- apply: apply2
3345
- } = editor;
3346
- return editor.apply = (op) => {
3347
- if (editorActor.getSnapshot().matches({
3348
- "edit mode": "read only"
3349
- })) {
3350
- apply2(op);
3351
- return;
3352
- }
3353
- if (isChangingRemotely(editor)) {
3354
- apply2(op);
3355
- return;
3356
- }
3357
- if (isUndoing(editor) || isRedoing(editor)) {
3358
- apply2(op);
3359
- return;
3360
- }
3361
- if (op.type === "remove_node") {
3362
- const node = op.node;
3363
- if (op.path[0] === 0 && slate.Editor.isVoid(editor, node)) {
3364
- const nextPath = slate.Path.next(op.path);
3365
- editor.children[nextPath[0]] || (debug$7("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
3366
- decorators: []
3367
- })));
3368
- }
3369
- }
3370
- apply2(op);
3371
- }, editor;
3372
- };
3373
- }
3374
- const debug$6 = debugWithName("plugin:withPortableTextBlockStyle");
3375
- function createWithPortableTextBlockStyle(editorActor, types2) {
3376
- const defaultStyle = types2.styles[0].value;
3377
- return function(editor) {
3378
- const {
3379
- normalizeNode
3380
- } = editor;
3381
- return editor.normalizeNode = (nodeEntry) => {
3382
- const [, path] = nodeEntry;
3383
- for (const op of editor.operations)
3384
- if (op.type === "split_node" && op.path.length === 1 && editor.isTextBlock(op.properties) && op.properties.style !== defaultStyle && op.path[0] === path[0] && !slate.Path.equals(path, op.path)) {
3385
- const [child] = slate.Editor.node(editor, [op.path[0] + 1, 0]);
3386
- if (slate.Text.isText(child) && child.text === "") {
3387
- debug$6(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3388
- type: "normalizing"
3389
- }), slate.Transforms.setNodes(editor, {
3390
- style: defaultStyle
3391
- }, {
3392
- at: [op.path[0] + 1],
3393
- voids: !1
3394
- }), editorActor.send({
3395
- type: "done normalizing"
3396
- });
3397
- return;
3398
- }
3399
- }
3400
- normalizeNode(nodeEntry);
3401
- }, editor;
3402
- };
3403
- }
3404
- function isPortableTextSpan(node) {
3405
- return node._type === "span" && "text" in node && typeof node.text == "string" && (typeof node.marks > "u" || Array.isArray(node.marks) && node.marks.every((mark) => typeof mark == "string"));
3406
- }
3407
- function isPortableTextBlock(node) {
3408
- return (
3409
- // A block doesn't _have_ to be named 'block' - to differentiate between
3410
- // allowed child types and marks, one might name them differently
3411
- typeof node._type == "string" && // Toolkit-types like nested spans are @-prefixed
3412
- node._type[0] !== "@" && // `markDefs` isn't _required_ per say, but if it's there, it needs to be an array
3413
- (!("markDefs" in node) || !node.markDefs || Array.isArray(node.markDefs) && // Every mark definition needs to have an `_key` to be mappable in child spans
3414
- node.markDefs.every((def) => typeof def._key == "string")) && // `children` is required and needs to be an array
3415
- "children" in node && Array.isArray(node.children) && // All children are objects with `_type` (usually spans, but can contain other stuff)
3416
- node.children.every((child) => typeof child == "object" && "_type" in child)
3417
- );
3418
- }
3419
- function getPreviousSpan({
3420
- editor,
3421
- blockPath,
3422
- spanPath
3423
- }) {
3424
- let previousSpan;
3425
- for (const [child, childPath] of slate.Node.children(editor, blockPath, {
3426
- reverse: !0
3427
- }))
3428
- if (editor.isTextSpan(child) && slate.Path.isBefore(childPath, spanPath)) {
3429
- previousSpan = child;
3430
- break;
3431
- }
3432
- return previousSpan;
3433
- }
3434
- function getNextSpan({
3435
- editor,
3436
- blockPath,
3437
- spanPath
3438
- }) {
3439
- let nextSpan;
3440
- for (const [child, childPath] of slate.Node.children(editor, blockPath))
3441
- if (editor.isTextSpan(child) && slate.Path.isAfter(childPath, spanPath)) {
3442
- nextSpan = child;
3443
- break;
3444
- }
3445
- return nextSpan;
3446
- }
3447
- const debug$5 = debugWithName("plugin:withPortableTextMarkModel");
3448
- function createWithPortableTextMarkModel(editorActor, types2) {
3449
- return function(editor) {
3450
- const {
3451
- apply: apply2,
3452
- normalizeNode
3453
- } = editor, decorators = types2.decorators.map((t) => t.value);
3454
- return editor.normalizeNode = (nodeEntry) => {
3455
- const [node, path] = nodeEntry;
3456
- if (editor.isTextBlock(node)) {
3457
- const children = slate.Node.children(editor, path);
3458
- for (const [child, childPath] of children) {
3459
- const nextNode = node.children[childPath[1] + 1];
3460
- if (editor.isTextSpan(child) && editor.isTextSpan(nextNode) && child.marks?.every((mark) => nextNode.marks?.includes(mark)) && nextNode.marks?.every((mark) => child.marks?.includes(mark))) {
3461
- debug$5("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
3462
- type: "normalizing"
3463
- }), slate.Transforms.mergeNodes(editor, {
3464
- at: [childPath[0], childPath[1] + 1],
3465
- voids: !0
3466
- }), editorActor.send({
3467
- type: "done normalizing"
3468
- });
3469
- return;
3470
- }
3471
- }
3472
- }
3473
- if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {
3474
- debug$5("Adding .markDefs to block node"), editorActor.send({
3475
- type: "normalizing"
3476
- }), slate.Transforms.setNodes(editor, {
3477
- markDefs: []
3478
- }, {
3479
- at: path
3480
- }), editorActor.send({
3481
- type: "done normalizing"
3482
- });
3483
- return;
3484
- }
3485
- if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {
3486
- debug$5("Adding .marks to span node"), editorActor.send({
3487
- type: "normalizing"
3488
- }), slate.Transforms.setNodes(editor, {
3489
- marks: []
3490
- }, {
3491
- at: path
3492
- }), editorActor.send({
3493
- type: "done normalizing"
3494
- });
3495
- return;
3496
- }
3497
- if (editor.isTextSpan(node)) {
3498
- const blockPath = slate.Path.parent(path), [block] = slate.Editor.node(editor, blockPath), decorators2 = types2.decorators.map((decorator) => decorator.value), annotations = node.marks?.filter((mark) => !decorators2.includes(mark));
3499
- if (editor.isTextBlock(block) && node.text === "" && annotations && annotations.length > 0) {
3500
- debug$5("Removing annotations from empty span node"), editorActor.send({
3501
- type: "normalizing"
3502
- }), slate.Transforms.setNodes(editor, {
3503
- marks: node.marks?.filter((mark) => decorators2.includes(mark))
3504
- }, {
3505
- at: path
3506
- }), editorActor.send({
3507
- type: "done normalizing"
3508
- });
3509
- return;
3510
- }
3511
- }
3512
- if (editor.isTextBlock(node)) {
3513
- const decorators2 = types2.decorators.map((decorator) => decorator.value);
3514
- for (const [child, childPath] of slate.Node.children(editor, path))
3515
- if (editor.isTextSpan(child)) {
3516
- const marks = child.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !node.markDefs?.find((def) => def._key === mark));
3517
- if (orphanedAnnotations.length > 0) {
3518
- debug$5("Removing orphaned annotations from span node"), editorActor.send({
3519
- type: "normalizing"
3520
- }), slate.Transforms.setNodes(editor, {
3521
- marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
3522
- }, {
3523
- at: childPath
3524
- }), editorActor.send({
3525
- type: "done normalizing"
3526
- });
3527
- return;
3528
- }
3529
- }
3530
- }
3531
- if (editor.isTextSpan(node)) {
3532
- const blockPath = slate.Path.parent(path), [block] = slate.Editor.node(editor, blockPath);
3533
- if (editor.isTextBlock(block)) {
3534
- const decorators2 = types2.decorators.map((decorator) => decorator.value), marks = node.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !block.markDefs?.find((def) => def._key === mark));
3535
- if (orphanedAnnotations.length > 0) {
3536
- debug$5("Removing orphaned annotations from span node"), editorActor.send({
3537
- type: "normalizing"
3538
- }), slate.Transforms.setNodes(editor, {
3539
- marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
3540
- }, {
3541
- at: path
3542
- }), editorActor.send({
3543
- type: "done normalizing"
3544
- });
3545
- return;
3546
- }
3547
- }
3548
- }
3549
- if (editor.isTextBlock(node)) {
3550
- const markDefs = node.markDefs ?? [], markDefKeys = /* @__PURE__ */ new Set(), newMarkDefs = [];
3551
- for (const markDef of markDefs)
3552
- markDefKeys.has(markDef._key) || (markDefKeys.add(markDef._key), newMarkDefs.push(markDef));
3553
- if (markDefs.length !== newMarkDefs.length) {
3554
- debug$5("Removing duplicate markDefs"), editorActor.send({
3555
- type: "normalizing"
3556
- }), slate.Transforms.setNodes(editor, {
3557
- markDefs: newMarkDefs
3558
- }, {
3559
- at: path
3560
- }), editorActor.send({
3561
- type: "done normalizing"
3562
- });
3563
- return;
3564
- }
3565
- }
3566
- if (editor.isTextBlock(node) && !editor.operations.some((op) => op.type === "merge_node" && "markDefs" in op.properties && op.path.length === 1)) {
3567
- const newMarkDefs = (node.markDefs || []).filter((def) => node.children.find((child) => slate.Text.isText(child) && Array.isArray(child.marks) && child.marks.includes(def._key)));
3568
- if (node.markDefs && !isEqual__default.default(newMarkDefs, node.markDefs)) {
3569
- debug$5("Removing markDef not in use"), editorActor.send({
3570
- type: "normalizing"
3571
- }), slate.Transforms.setNodes(editor, {
3572
- markDefs: newMarkDefs
3573
- }, {
3574
- at: path
3575
- }), editorActor.send({
3576
- type: "done normalizing"
3577
- });
3578
- return;
3579
- }
3580
- }
3581
- normalizeNode(nodeEntry);
3582
- }, editor.apply = (op) => {
3583
- if (isChangingRemotely(editor)) {
3584
- apply2(op);
3585
- return;
3586
- }
3587
- if (isUndoing(editor) || isRedoing(editor)) {
3588
- apply2(op);
3589
- return;
3590
- }
3591
- if (op.type === "set_selection" && slate.Editor.marks(editor) && op.properties && op.newProperties && op.properties.anchor && op.properties.focus && op.newProperties.anchor && op.newProperties.focus) {
3592
- const previousSelectionIsCollapsed = slate.Range.isCollapsed({
3593
- anchor: op.properties.anchor,
3594
- focus: op.properties.focus
3595
- }), newSelectionIsCollapsed = slate.Range.isCollapsed({
3596
- anchor: op.newProperties.anchor,
3597
- focus: op.newProperties.focus
3598
- });
3599
- if (previousSelectionIsCollapsed && newSelectionIsCollapsed) {
3600
- const focusSpan = Array.from(slate.Editor.nodes(editor, {
3601
- mode: "lowest",
3602
- at: op.properties.focus,
3603
- match: (n) => editor.isTextSpan(n),
3604
- voids: !1
3605
- }))[0]?.[0], newFocusSpan = Array.from(slate.Editor.nodes(editor, {
3606
- mode: "lowest",
3607
- at: op.newProperties.focus,
3608
- match: (n) => editor.isTextSpan(n),
3609
- voids: !1
3610
- }))[0]?.[0], movedToNextSpan = focusSpan && newFocusSpan && op.newProperties.focus.path[0] === op.properties.focus.path[0] && op.newProperties.focus.path[1] === op.properties.focus.path[1] + 1 && focusSpan.text.length === op.properties.focus.offset && op.newProperties.focus.offset === 0, movedToPreviousSpan = focusSpan && newFocusSpan && op.newProperties.focus.path[0] === op.properties.focus.path[0] && op.newProperties.focus.path[1] === op.properties.focus.path[1] - 1 && op.properties.focus.offset === 0 && newFocusSpan.text.length === op.newProperties.focus.offset;
3611
- if (movedToNextSpan || movedToPreviousSpan)
3612
- return;
3613
- }
3614
- }
3615
- if (op.type === "insert_node") {
3616
- const {
3617
- selection
3618
- } = editor;
3619
- if (selection) {
3620
- const [_block, blockPath] = slate.Editor.node(editor, selection, {
3621
- depth: 1
3622
- }), previousSpan = getPreviousSpan({
3623
- editor,
3624
- blockPath,
3625
- spanPath: op.path
3626
- }), previousSpanAnnotations = previousSpan ? previousSpan.marks?.filter((mark) => !decorators.includes(mark)) : [], nextSpan = getNextSpan({
3627
- editor,
3628
- blockPath,
3629
- spanPath: [op.path[0], op.path[1] - 1]
3630
- }), nextSpanAnnotations = nextSpan ? nextSpan.marks?.filter((mark) => !decorators.includes(mark)) : [], annotationsEnding = previousSpanAnnotations?.filter((annotation) => !nextSpanAnnotations?.includes(annotation)) ?? [], atTheEndOfAnnotation = annotationsEnding.length > 0;
3631
- if (atTheEndOfAnnotation && isPortableTextSpan(op.node) && op.node.marks?.some((mark) => annotationsEnding.includes(mark))) {
3632
- slate.Transforms.insertNodes(editor, {
3633
- ...op.node,
3634
- _key: editorActor.getSnapshot().context.keyGenerator(),
3635
- marks: op.node.marks?.filter((mark) => !annotationsEnding.includes(mark)) ?? []
3636
- });
3637
- return;
3638
- }
3639
- const annotationsStarting = nextSpanAnnotations?.filter((annotation) => !previousSpanAnnotations?.includes(annotation)) ?? [], atTheStartOfAnnotation = annotationsStarting.length > 0;
3640
- if (atTheStartOfAnnotation && isPortableTextSpan(op.node) && op.node.marks?.some((mark) => annotationsStarting.includes(mark))) {
3641
- slate.Transforms.insertNodes(editor, {
3642
- ...op.node,
3643
- _key: editorActor.getSnapshot().context.keyGenerator(),
3644
- marks: op.node.marks?.filter((mark) => !annotationsStarting.includes(mark)) ?? []
3645
- });
3646
- return;
3647
- }
3648
- const nextSpanDecorators = nextSpan?.marks?.filter((mark) => decorators.includes(mark)) ?? [];
3649
- if (nextSpanDecorators.length > 0 && atTheEndOfAnnotation && !atTheStartOfAnnotation && isPortableTextSpan(op.node) && op.node.marks?.length === 0) {
3650
- slate.Transforms.insertNodes(editor, {
3651
- ...op.node,
3652
- _key: editorActor.getSnapshot().context.keyGenerator(),
3653
- marks: nextSpanDecorators
3654
- });
3655
- return;
3656
- }
3657
- }
3658
- }
3659
- if (op.type === "insert_text") {
3660
- const {
3661
- selection
3662
- } = editor, collapsedSelection = selection ? slate.Range.isCollapsed(selection) : !1;
3663
- if (selection && collapsedSelection) {
3664
- const [_block, blockPath] = slate.Editor.node(editor, selection, {
3665
- depth: 1
3666
- }), [span, spanPath] = Array.from(slate.Editor.nodes(editor, {
3667
- mode: "lowest",
3668
- at: selection.focus,
3669
- match: (n) => editor.isTextSpan(n),
3670
- voids: !1
3671
- }))[0] ?? [void 0, void 0], marks = span.marks ?? [], marksWithoutAnnotations = marks.filter((mark) => decorators.includes(mark)), spanHasAnnotations = marks.length > marksWithoutAnnotations.length, spanIsEmpty = span.text.length === 0, atTheBeginningOfSpan = selection.anchor.offset === 0, atTheEndOfSpan = selection.anchor.offset === span.text.length, previousSpan = getPreviousSpan({
3672
- editor,
3673
- blockPath,
3674
- spanPath
3675
- }), nextSpan = getNextSpan({
3676
- editor,
3677
- blockPath,
3678
- spanPath
3679
- }), nextSpanAnnotations = nextSpan?.marks?.filter((mark) => !decorators.includes(mark)) ?? [], spanAnnotations = marks.filter((mark) => !decorators.includes(mark)), previousSpanHasAnnotations = previousSpan ? previousSpan.marks?.some((mark) => !decorators.includes(mark)) : !1, previousSpanHasSameAnnotations = previousSpan ? previousSpan.marks?.filter((mark) => !decorators.includes(mark)).every((mark) => marks.includes(mark)) : !1, previousSpanHasSameAnnotation = previousSpan ? previousSpan.marks?.some((mark) => !decorators.includes(mark) && marks.includes(mark)) : !1, previousSpanHasSameMarks = previousSpan ? previousSpan.marks?.every((mark) => marks.includes(mark)) : !1, nextSpanSharesSomeAnnotations = spanAnnotations.some((mark) => nextSpanAnnotations?.includes(mark));
3680
- if (spanHasAnnotations && !spanIsEmpty) {
3681
- if (atTheBeginningOfSpan) {
3682
- if (previousSpanHasSameMarks) {
3683
- slate.Transforms.insertNodes(editor, {
3684
- _type: "span",
3685
- _key: editorActor.getSnapshot().context.keyGenerator(),
3686
- text: op.text,
3687
- marks: previousSpan?.marks ?? []
3688
- });
3689
- return;
3690
- } else if (previousSpanHasSameAnnotations) {
3691
- slate.Transforms.insertNodes(editor, {
3692
- _type: "span",
3693
- _key: editorActor.getSnapshot().context.keyGenerator(),
3694
- text: op.text,
3695
- marks: previousSpan?.marks ?? []
3696
- });
3697
- return;
3698
- } else if (previousSpanHasSameAnnotation) {
3699
- apply2(op);
3700
- return;
3701
- } else if (!previousSpan) {
3702
- slate.Transforms.insertNodes(editor, {
3703
- _type: "span",
3704
- _key: editorActor.getSnapshot().context.keyGenerator(),
3705
- text: op.text,
3706
- marks: []
3707
- });
3708
- return;
3709
- }
3710
- }
3711
- if (atTheEndOfSpan) {
3712
- if (nextSpan && nextSpanSharesSomeAnnotations && nextSpanAnnotations.length < spanAnnotations.length || !nextSpanSharesSomeAnnotations) {
3713
- slate.Transforms.insertNodes(editor, {
3714
- _type: "span",
3715
- _key: editorActor.getSnapshot().context.keyGenerator(),
3716
- text: op.text,
3717
- marks: nextSpan?.marks ?? []
3718
- });
3719
- return;
3720
- }
3721
- if (!nextSpan) {
3722
- slate.Transforms.insertNodes(editor, {
3723
- _type: "span",
3724
- _key: editorActor.getSnapshot().context.keyGenerator(),
3725
- text: op.text,
3726
- marks: []
3727
- });
3728
- return;
3729
- }
3730
- }
3731
- }
3732
- if (atTheBeginningOfSpan && !spanIsEmpty && previousSpan) {
3733
- slate.Transforms.insertNodes(editor, {
3734
- _type: "span",
3735
- _key: editorActor.getSnapshot().context.keyGenerator(),
3736
- text: op.text,
3737
- marks: previousSpanHasAnnotations ? [] : (previousSpan.marks ?? []).filter((mark) => decorators.includes(mark))
3738
- });
3739
- return;
3740
- }
3741
- }
3742
- }
3743
- if (op.type === "remove_text") {
3744
- const {
3745
- selection
3746
- } = editor;
3747
- if (selection && slate.Range.isExpanded(selection)) {
3748
- const [block, blockPath] = slate.Editor.node(editor, selection, {
3749
- depth: 1
3750
- }), [span, spanPath] = Array.from(slate.Editor.nodes(editor, {
3751
- mode: "lowest",
3752
- at: {
3753
- path: op.path,
3754
- offset: op.offset
3755
- },
3756
- match: (n) => editor.isTextSpan(n),
3757
- voids: !1
3758
- }))[0] ?? [void 0, void 0];
3759
- if (span && block && isPortableTextBlock(block)) {
3760
- const markDefs = block.markDefs ?? [], marks = span.marks ?? [], spanHasAnnotations = marks.some((mark) => markDefs.find((markDef) => markDef._key === mark)), deletingFromTheEnd = op.offset + op.text.length === span.text.length, deletingAllText = op.offset === 0 && deletingFromTheEnd, previousSpan = getPreviousSpan({
3761
- editor,
3762
- blockPath,
3763
- spanPath
3764
- }), nextSpan = getNextSpan({
3765
- editor,
3766
- blockPath,
3767
- spanPath
3768
- }), previousSpanHasSameAnnotation = previousSpan ? previousSpan.marks?.some((mark) => !decorators.includes(mark) && marks.includes(mark)) : !1, nextSpanHasSameAnnotation = nextSpan ? nextSpan.marks?.some((mark) => !decorators.includes(mark) && marks.includes(mark)) : !1;
3769
- if (spanHasAnnotations && deletingAllText && !previousSpanHasSameAnnotation && !nextSpanHasSameAnnotation) {
3770
- const marksWithoutAnnotationMarks = ({
3771
- ...slate.Editor.marks(editor) || {}
3772
- }.marks || []).filter((mark) => decorators.includes(mark));
3773
- slate.Editor.withoutNormalizing(editor, () => {
3774
- apply2(op), slate.Transforms.setNodes(editor, {
3775
- marks: marksWithoutAnnotationMarks
3776
- }, {
3777
- at: op.path
3778
- });
3779
- }), editor.onChange();
3780
- return;
3781
- }
3782
- }
3783
- }
3784
- }
3785
- if (op.type === "merge_node" && op.path.length === 1 && "markDefs" in op.properties && op.properties._type === types2.block.name && Array.isArray(op.properties.markDefs) && op.properties.markDefs.length > 0 && op.path[0] - 1 >= 0) {
3786
- const [targetBlock, targetPath] = slate.Editor.node(editor, [op.path[0] - 1]);
3787
- if (editor.isTextBlock(targetBlock)) {
3788
- const oldDefs = Array.isArray(targetBlock.markDefs) && targetBlock.markDefs || [], newMarkDefs = uniq__default.default([...oldDefs, ...op.properties.markDefs]);
3789
- debug$5("Copying markDefs over to merged block", op), slate.Transforms.setNodes(editor, {
3790
- markDefs: newMarkDefs
3791
- }, {
3792
- at: targetPath,
3793
- voids: !1
3794
- }), apply2(op);
3795
- return;
3796
- }
3797
- }
3798
- apply2(op);
3799
- }, editor;
3800
- };
3801
- }
3802
- const addDecoratorActionImplementation = ({
3803
- action
3804
- }) => {
3805
- const editor = action.editor, mark = action.decorator;
3806
- if (editor.selection) {
3807
- if (slate.Range.isExpanded(editor.selection)) {
3808
- slate.Transforms.setNodes(editor, {}, {
3809
- match: slate.Text.isText,
3810
- split: !0,
3811
- hanging: !0
3812
- });
3813
- const splitTextNodes = slate.Range.isRange(editor.selection) ? [...slate.Editor.nodes(editor, {
3814
- at: editor.selection,
3815
- match: slate.Text.isText
3816
- })] : [];
3817
- splitTextNodes.length > 1 && splitTextNodes.every((node) => node[0].marks?.includes(mark)) ? editor.removeMark(mark) : splitTextNodes.forEach(([node, path]) => {
3818
- const marks = [...(Array.isArray(node.marks) ? node.marks : []).filter((eMark) => eMark !== mark), mark];
3819
- slate.Transforms.setNodes(editor, {
3820
- marks
3821
- }, {
3822
- at: path,
3823
- match: slate.Text.isText,
3824
- split: !0,
3825
- hanging: !0
3826
- });
3827
- });
3828
- } else {
3829
- const [block, blockPath] = slate.Editor.node(editor, editor.selection, {
3830
- depth: 1
3831
- }), lonelyEmptySpan = editor.isTextBlock(block) && block.children.length === 1 && editor.isTextSpan(block.children[0]) && block.children[0].text === "" ? block.children[0] : void 0;
3832
- if (lonelyEmptySpan) {
3833
- const existingMarks = lonelyEmptySpan.marks ?? [], existingMarksWithoutDecorator = existingMarks.filter((existingMark) => existingMark !== mark);
3834
- slate.Transforms.setNodes(editor, {
3835
- marks: existingMarks.length === existingMarksWithoutDecorator.length ? [...existingMarks, mark] : existingMarksWithoutDecorator
3836
- }, {
3837
- at: blockPath,
3838
- match: (node) => editor.isTextSpan(node)
3839
- });
3840
- } else {
3841
- const existingMarks = {
3842
- ...slate.Editor.marks(editor) || {}
3843
- }.marks || [], marks = {
3844
- ...slate.Editor.marks(editor) || {},
3845
- marks: [...existingMarks, mark]
3846
- };
3847
- editor.marks = marks;
3848
- }
3849
- }
3850
- if (editor.selection) {
3851
- const selection = editor.selection;
3852
- editor.selection = {
3853
- ...selection
3854
- };
3855
- }
3856
- }
3857
- }, removeDecoratorActionImplementation = ({
3858
- action
3859
- }) => {
3860
- const editor = action.editor, mark = action.decorator, {
3861
- selection
3862
- } = editor;
3863
- if (selection) {
3864
- if (slate.Range.isExpanded(selection))
3865
- slate.Transforms.setNodes(editor, {}, {
3866
- match: slate.Text.isText,
3867
- split: !0,
3868
- hanging: !0
3869
- }), editor.selection && [...slate.Editor.nodes(editor, {
3870
- at: editor.selection,
3871
- match: slate.Text.isText
3872
- })].forEach(([node, path]) => {
3873
- const block = editor.children[path[0]];
3874
- slate.Element.isElement(block) && block.children.includes(node) && slate.Transforms.setNodes(editor, {
3875
- marks: (Array.isArray(node.marks) ? node.marks : []).filter((eMark) => eMark !== mark),
3876
- _type: "span"
3877
- }, {
3878
- at: path
3879
- });
3880
- });
3881
- else {
3882
- const [block, blockPath] = slate.Editor.node(editor, selection, {
3883
- depth: 1
3884
- }), lonelyEmptySpan = editor.isTextBlock(block) && block.children.length === 1 && editor.isTextSpan(block.children[0]) && block.children[0].text === "" ? block.children[0] : void 0;
3885
- if (lonelyEmptySpan) {
3886
- const existingMarksWithoutDecorator = (lonelyEmptySpan.marks ?? []).filter((existingMark) => existingMark !== mark);
3887
- slate.Transforms.setNodes(editor, {
3888
- marks: existingMarksWithoutDecorator
3889
- }, {
3890
- at: blockPath,
3891
- match: (node) => editor.isTextSpan(node)
3892
- });
3893
- } else {
3894
- const existingMarks = {
3895
- ...slate.Editor.marks(editor) || {}
3896
- }.marks || [], marks = {
3897
- ...slate.Editor.marks(editor) || {},
3898
- marks: existingMarks.filter((eMark) => eMark !== mark)
3899
- };
3900
- editor.marks = {
3901
- marks: marks.marks,
3902
- _type: "span"
3903
- };
3904
- }
3905
- }
3906
- if (editor.selection) {
3907
- const selection2 = editor.selection;
3908
- editor.selection = {
3909
- ...selection2
3910
- };
3911
- }
3912
- }
3913
- };
3914
- function isDecoratorActive({
3915
- editor,
3916
- decorator
3917
- }) {
3918
- if (!editor.selection)
3919
- return !1;
3920
- const selectedTextNodes = Array.from(slate.Editor.nodes(editor, {
3921
- match: slate.Text.isText,
3922
- at: editor.selection
3923
- }));
3924
- return selectedTextNodes.length === 0 ? !1 : slate.Range.isExpanded(editor.selection) ? selectedTextNodes.every((n) => {
3925
- const [node] = n;
3926
- return node.marks?.includes(decorator);
3927
- }) : ({
3928
- ...slate.Editor.marks(editor) || {}
3929
- }.marks || []).includes(decorator);
3930
- }
3931
- const toggleDecoratorActionImplementation = ({
3932
- context,
3933
- action
3934
- }) => {
3935
- isDecoratorActive({
3936
- editor: action.editor,
3937
- decorator: action.decorator
3938
- }) ? removeDecoratorActionImplementation({
3939
- context,
3940
- action: {
3941
- type: "decorator.remove",
3942
- editor: action.editor,
3943
- decorator: action.decorator
3944
- }
3945
- }) : addDecoratorActionImplementation({
3946
- context,
3947
- action: {
3948
- type: "decorator.add",
3949
- editor: action.editor,
3950
- decorator: action.decorator
3951
- }
3952
- });
3953
- };
3954
- debugWithName("plugin:withPortableTextSelections");
3955
- function createWithPortableTextSelections(editorActor, types2) {
3956
- let prevSelection = null;
3957
- return function(editor) {
3958
- const emitPortableTextSelection = () => {
3959
- if (prevSelection !== editor.selection) {
3960
- let ptRange = null;
3961
- if (editor.selection) {
3962
- const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
3963
- if (existing)
3964
- ptRange = existing;
3965
- else {
3966
- const value = editor.children;
3967
- ptRange = toPortableTextRange(value, editor.selection, types2), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
3204
+ if (op.type === "insert_text") {
3205
+ const {
3206
+ selection
3207
+ } = editor, collapsedSelection = selection ? slate.Range.isCollapsed(selection) : !1;
3208
+ if (selection && collapsedSelection) {
3209
+ const [_block, blockPath] = slate.Editor.node(editor, selection, {
3210
+ depth: 1
3211
+ }), [span, spanPath] = Array.from(slate.Editor.nodes(editor, {
3212
+ mode: "lowest",
3213
+ at: selection.focus,
3214
+ match: (n) => editor.isTextSpan(n),
3215
+ voids: !1
3216
+ }))[0] ?? [void 0, void 0], marks = span.marks ?? [], marksWithoutAnnotations = marks.filter((mark) => decorators.includes(mark)), spanHasAnnotations = marks.length > marksWithoutAnnotations.length, spanIsEmpty = span.text.length === 0, atTheBeginningOfSpan = selection.anchor.offset === 0, atTheEndOfSpan = selection.anchor.offset === span.text.length, previousSpan = getPreviousSpan({
3217
+ editor,
3218
+ blockPath,
3219
+ spanPath
3220
+ }), nextSpan = getNextSpan({
3221
+ editor,
3222
+ blockPath,
3223
+ spanPath
3224
+ }), nextSpanAnnotations = nextSpan?.marks?.filter((mark) => !decorators.includes(mark)) ?? [], spanAnnotations = marks.filter((mark) => !decorators.includes(mark)), previousSpanHasAnnotations = previousSpan ? previousSpan.marks?.some((mark) => !decorators.includes(mark)) : !1, previousSpanHasSameAnnotations = previousSpan ? previousSpan.marks?.filter((mark) => !decorators.includes(mark)).every((mark) => marks.includes(mark)) : !1, previousSpanHasSameAnnotation = previousSpan ? previousSpan.marks?.some((mark) => !decorators.includes(mark) && marks.includes(mark)) : !1, previousSpanHasSameMarks = previousSpan ? previousSpan.marks?.every((mark) => marks.includes(mark)) : !1, nextSpanSharesSomeAnnotations = spanAnnotations.some((mark) => nextSpanAnnotations?.includes(mark));
3225
+ if (spanHasAnnotations && !spanIsEmpty) {
3226
+ if (atTheBeginningOfSpan) {
3227
+ if (previousSpanHasSameMarks) {
3228
+ slate.Transforms.insertNodes(editor, {
3229
+ _type: "span",
3230
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3231
+ text: op.text,
3232
+ marks: previousSpan?.marks ?? []
3233
+ });
3234
+ return;
3235
+ } else if (previousSpanHasSameAnnotations) {
3236
+ slate.Transforms.insertNodes(editor, {
3237
+ _type: "span",
3238
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3239
+ text: op.text,
3240
+ marks: previousSpan?.marks ?? []
3241
+ });
3242
+ return;
3243
+ } else if (previousSpanHasSameAnnotation) {
3244
+ apply2(op);
3245
+ return;
3246
+ } else if (!previousSpan) {
3247
+ slate.Transforms.insertNodes(editor, {
3248
+ _type: "span",
3249
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3250
+ text: op.text,
3251
+ marks: []
3252
+ });
3253
+ return;
3254
+ }
3255
+ }
3256
+ if (atTheEndOfSpan) {
3257
+ if (nextSpan && nextSpanSharesSomeAnnotations && nextSpanAnnotations.length < spanAnnotations.length || !nextSpanSharesSomeAnnotations) {
3258
+ slate.Transforms.insertNodes(editor, {
3259
+ _type: "span",
3260
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3261
+ text: op.text,
3262
+ marks: nextSpan?.marks ?? []
3263
+ });
3264
+ return;
3265
+ }
3266
+ if (!nextSpan) {
3267
+ slate.Transforms.insertNodes(editor, {
3268
+ _type: "span",
3269
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3270
+ text: op.text,
3271
+ marks: []
3272
+ });
3273
+ return;
3274
+ }
3275
+ }
3276
+ }
3277
+ if (atTheBeginningOfSpan && !spanIsEmpty && previousSpan) {
3278
+ slate.Transforms.insertNodes(editor, {
3279
+ _type: "span",
3280
+ _key: editorActor.getSnapshot().context.keyGenerator(),
3281
+ text: op.text,
3282
+ marks: previousSpanHasAnnotations ? [] : (previousSpan.marks ?? []).filter((mark) => decorators.includes(mark))
3283
+ });
3284
+ return;
3968
3285
  }
3969
3286
  }
3970
- ptRange ? editorActor.send({
3971
- type: "notify.selection",
3972
- selection: ptRange
3973
- }) : editorActor.send({
3974
- type: "notify.selection",
3975
- selection: null
3976
- });
3977
- }
3978
- prevSelection = editor.selection;
3979
- }, {
3980
- onChange
3981
- } = editor;
3982
- return editor.onChange = () => {
3983
- onChange(), editorActor.getSnapshot().matches({
3984
- setup: "setting up"
3985
- }) || emitPortableTextSelection();
3986
- }, editor;
3987
- };
3988
- }
3989
- const debug$4 = debugWithName("plugin:withSchemaTypes");
3990
- function createWithSchemaTypes({
3991
- editorActor,
3992
- schemaTypes
3993
- }) {
3994
- return function(editor) {
3995
- editor.isTextBlock = (value) => types.isPortableTextTextBlock(value) && value._type === schemaTypes.block.name, editor.isTextSpan = (value) => types.isPortableTextSpan(value) && value._type === schemaTypes.span.name, editor.isListBlock = (value) => types.isPortableTextListBlock(value) && value._type === schemaTypes.block.name, editor.isVoid = (element) => schemaTypes.block.name !== element._type && (schemaTypes.blockObjects.map((obj) => obj.name).includes(element._type) || schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type)), editor.isInline = (element) => schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type) && "__inline" in element && element.__inline === !0;
3996
- const {
3997
- normalizeNode
3998
- } = editor;
3999
- return editor.normalizeNode = (entry) => {
4000
- const [node, path] = entry;
4001
- if (node._type === void 0 && path.length === 2) {
4002
- debug$4("Setting span type on text node without a type");
4003
- const span = node, key = span._key || editorActor.getSnapshot().context.keyGenerator();
4004
- editorActor.send({
4005
- type: "normalizing"
4006
- }), slate.Transforms.setNodes(editor, {
4007
- ...span,
4008
- _type: schemaTypes.span.name,
4009
- _key: key
4010
- }, {
4011
- at: path
4012
- }), editorActor.send({
4013
- type: "done normalizing"
4014
- });
4015
- return;
4016
- }
4017
- if (node._key === void 0 && (path.length === 1 || path.length === 2)) {
4018
- debug$4("Setting missing key on child node without a key");
4019
- const key = editorActor.getSnapshot().context.keyGenerator();
4020
- editorActor.send({
4021
- type: "normalizing"
4022
- }), slate.Transforms.setNodes(editor, {
4023
- _key: key
4024
- }, {
4025
- at: path
4026
- }), editorActor.send({
4027
- type: "done normalizing"
4028
- });
4029
- return;
4030
3287
  }
4031
- normalizeNode(entry);
4032
- }, editor;
4033
- };
4034
- }
4035
- function createWithUtils({
4036
- editorActor,
4037
- schemaTypes
4038
- }) {
4039
- return function(editor) {
4040
- return editor.pteCreateTextBlock = (options) => toSlateValue([{
4041
- _type: schemaTypes.block.name,
4042
- _key: editorActor.getSnapshot().context.keyGenerator(),
4043
- style: schemaTypes.styles[0].value || "normal",
4044
- ...options.listItem ? {
4045
- listItem: options.listItem
4046
- } : {},
4047
- ...options.level ? {
4048
- level: options.level
4049
- } : {},
4050
- markDefs: [],
4051
- children: [{
4052
- _type: "span",
4053
- _key: editorActor.getSnapshot().context.keyGenerator(),
4054
- text: "",
4055
- marks: options.decorators.filter((decorator) => schemaTypes.decorators.find(({
4056
- value
4057
- }) => value === decorator))
4058
- }]
4059
- }], {
4060
- schemaTypes
4061
- })[0], editor;
4062
- };
4063
- }
4064
- const withPlugins = (editor, options) => {
4065
- const e = editor, {
4066
- editorActor
4067
- } = options, schemaTypes = editorActor.getSnapshot().context.schema, operationToPatches = createOperationToPatches(schemaTypes), withObjectKeys = createWithObjectKeys(editorActor, schemaTypes), withSchemaTypes = createWithSchemaTypes({
4068
- editorActor,
4069
- schemaTypes
4070
- }), withPatches = createWithPatches({
4071
- editorActor,
4072
- patchFunctions: operationToPatches,
4073
- schemaTypes,
4074
- subscriptions: options.subscriptions
4075
- }), withMaxBlocks = createWithMaxBlocks(editorActor), withUndoRedo = createWithUndoRedo({
4076
- editorActor,
4077
- blockSchemaType: schemaTypes.block,
4078
- subscriptions: options.subscriptions
4079
- }), withPortableTextMarkModel = createWithPortableTextMarkModel(editorActor, schemaTypes), withPortableTextBlockStyle = createWithPortableTextBlockStyle(editorActor, schemaTypes), withPlaceholderBlock = createWithPlaceholderBlock(editorActor), withUtils = createWithUtils({
4080
- editorActor,
4081
- schemaTypes
4082
- }), withPortableTextSelections = createWithPortableTextSelections(editorActor, schemaTypes);
4083
- return createWithEventListeners(editorActor, options.subscriptions)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e)))))))))));
4084
- }, debug$3 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
4085
- function createSlateEditor(config) {
4086
- const existingSlateEditor = slateEditors.get(config.editorActor);
4087
- if (existingSlateEditor)
4088
- return debug$3("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
4089
- debug$3("Creating new Slate editor instance", config.editorActor.id);
4090
- const unsubscriptions = [], subscriptions = [], instance = withPlugins(slateReact.withReact(slate.createEditor()), {
4091
- editorActor: config.editorActor,
4092
- subscriptions
4093
- });
4094
- KEY_TO_VALUE_ELEMENT.set(instance, {}), KEY_TO_SLATE_ELEMENT.set(instance, {});
4095
- for (const subscription of subscriptions)
4096
- unsubscriptions.push(subscription());
4097
- const initialValue = [instance.pteCreateTextBlock({
4098
- decorators: []
4099
- })], slateEditor = {
4100
- instance,
4101
- initialValue
3288
+ if (op.type === "remove_text") {
3289
+ const {
3290
+ selection
3291
+ } = editor;
3292
+ if (selection && slate.Range.isExpanded(selection)) {
3293
+ const [block, blockPath] = slate.Editor.node(editor, selection, {
3294
+ depth: 1
3295
+ }), [span, spanPath] = Array.from(slate.Editor.nodes(editor, {
3296
+ mode: "lowest",
3297
+ at: {
3298
+ path: op.path,
3299
+ offset: op.offset
3300
+ },
3301
+ match: (n) => editor.isTextSpan(n),
3302
+ voids: !1
3303
+ }))[0] ?? [void 0, void 0];
3304
+ if (span && block && isPortableTextBlock(block)) {
3305
+ const markDefs = block.markDefs ?? [], marks = span.marks ?? [], spanHasAnnotations = marks.some((mark) => markDefs.find((markDef) => markDef._key === mark)), deletingFromTheEnd = op.offset + op.text.length === span.text.length, deletingAllText = op.offset === 0 && deletingFromTheEnd, previousSpan = getPreviousSpan({
3306
+ editor,
3307
+ blockPath,
3308
+ spanPath
3309
+ }), nextSpan = getNextSpan({
3310
+ editor,
3311
+ blockPath,
3312
+ spanPath
3313
+ }), previousSpanHasSameAnnotation = previousSpan ? previousSpan.marks?.some((mark) => !decorators.includes(mark) && marks.includes(mark)) : !1, nextSpanHasSameAnnotation = nextSpan ? nextSpan.marks?.some((mark) => !decorators.includes(mark) && marks.includes(mark)) : !1;
3314
+ if (spanHasAnnotations && deletingAllText && !previousSpanHasSameAnnotation && !nextSpanHasSameAnnotation) {
3315
+ const marksWithoutAnnotationMarks = ({
3316
+ ...slate.Editor.marks(editor) || {}
3317
+ }.marks || []).filter((mark) => decorators.includes(mark));
3318
+ slate.Editor.withoutNormalizing(editor, () => {
3319
+ apply2(op), slate.Transforms.setNodes(editor, {
3320
+ marks: marksWithoutAnnotationMarks
3321
+ }, {
3322
+ at: op.path
3323
+ });
3324
+ }), editor.onChange();
3325
+ return;
3326
+ }
3327
+ }
3328
+ }
3329
+ }
3330
+ if (op.type === "merge_node" && op.path.length === 1 && "markDefs" in op.properties && op.properties._type === types2.block.name && Array.isArray(op.properties.markDefs) && op.properties.markDefs.length > 0 && op.path[0] - 1 >= 0) {
3331
+ const [targetBlock, targetPath] = slate.Editor.node(editor, [op.path[0] - 1]);
3332
+ if (editor.isTextBlock(targetBlock)) {
3333
+ const oldDefs = Array.isArray(targetBlock.markDefs) && targetBlock.markDefs || [], newMarkDefs = uniq__default.default([...oldDefs, ...op.properties.markDefs]);
3334
+ debug$9("Copying markDefs over to merged block", op), slate.Transforms.setNodes(editor, {
3335
+ markDefs: newMarkDefs
3336
+ }, {
3337
+ at: targetPath,
3338
+ voids: !1
3339
+ }), apply2(op);
3340
+ return;
3341
+ }
3342
+ }
3343
+ apply2(op);
3344
+ }, editor;
4102
3345
  };
4103
- return slateEditors.set(config.editorActor, slateEditor), slateEditor;
4104
3346
  }
4105
- const toggleListItemActionImplementation = ({
4106
- context,
3347
+ const removeDecoratorActionImplementation = ({
4107
3348
  action
4108
3349
  }) => {
4109
- isListItemActive({
4110
- editor: action.editor,
4111
- listItem: action.listItem
4112
- }) ? removeListItemActionImplementation({
4113
- context,
4114
- action: {
4115
- ...action,
4116
- type: "list item.remove"
3350
+ const editor = action.editor, mark = action.decorator, {
3351
+ selection
3352
+ } = editor;
3353
+ if (selection) {
3354
+ if (slate.Range.isExpanded(selection))
3355
+ slate.Transforms.setNodes(editor, {}, {
3356
+ match: slate.Text.isText,
3357
+ split: !0,
3358
+ hanging: !0
3359
+ }), editor.selection && [...slate.Editor.nodes(editor, {
3360
+ at: editor.selection,
3361
+ match: slate.Text.isText
3362
+ })].forEach(([node, path]) => {
3363
+ const block = editor.children[path[0]];
3364
+ slate.Element.isElement(block) && block.children.includes(node) && slate.Transforms.setNodes(editor, {
3365
+ marks: (Array.isArray(node.marks) ? node.marks : []).filter((eMark) => eMark !== mark),
3366
+ _type: "span"
3367
+ }, {
3368
+ at: path
3369
+ });
3370
+ });
3371
+ else {
3372
+ const [block, blockPath] = slate.Editor.node(editor, selection, {
3373
+ depth: 1
3374
+ }), lonelyEmptySpan = editor.isTextBlock(block) && block.children.length === 1 && editor.isTextSpan(block.children[0]) && block.children[0].text === "" ? block.children[0] : void 0;
3375
+ if (lonelyEmptySpan) {
3376
+ const existingMarksWithoutDecorator = (lonelyEmptySpan.marks ?? []).filter((existingMark) => existingMark !== mark);
3377
+ slate.Transforms.setNodes(editor, {
3378
+ marks: existingMarksWithoutDecorator
3379
+ }, {
3380
+ at: blockPath,
3381
+ match: (node) => editor.isTextSpan(node)
3382
+ });
3383
+ } else {
3384
+ const existingMarks = {
3385
+ ...slate.Editor.marks(editor) || {}
3386
+ }.marks || [], marks = {
3387
+ ...slate.Editor.marks(editor) || {},
3388
+ marks: existingMarks.filter((eMark) => eMark !== mark)
3389
+ };
3390
+ editor.marks = {
3391
+ marks: marks.marks,
3392
+ _type: "span"
3393
+ };
3394
+ }
4117
3395
  }
4118
- }) : addListItemActionImplementation({
4119
- context,
4120
- action: {
4121
- ...action,
4122
- type: "list item.add"
3396
+ if (editor.selection) {
3397
+ const selection2 = editor.selection;
3398
+ editor.selection = {
3399
+ ...selection2
3400
+ };
4123
3401
  }
4124
- });
4125
- }, removeListItemActionImplementation = ({
4126
- context,
4127
- action
4128
- }) => {
4129
- if (!action.editor.selection)
4130
- return;
4131
- const guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
4132
- at: action.editor.selection,
4133
- match: (node) => guards.isListBlock(node)
4134
- })];
4135
- for (const [, at] of selectedBlocks)
4136
- slate.Transforms.unsetNodes(action.editor, ["listItem", "level"], {
4137
- at
4138
- });
4139
- }, addListItemActionImplementation = ({
4140
- context,
4141
- action
4142
- }) => {
4143
- if (!action.editor.selection)
4144
- return;
4145
- const guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
4146
- at: action.editor.selection,
4147
- match: (node) => guards.isTextBlock(node)
4148
- })];
4149
- for (const [, at] of selectedBlocks)
4150
- slate.Transforms.setNodes(action.editor, {
4151
- level: 1,
4152
- listItem: action.listItem
4153
- }, {
4154
- at
4155
- });
3402
+ }
4156
3403
  };
4157
- function isListItemActive({
3404
+ function isDecoratorActive({
4158
3405
  editor,
4159
- listItem
3406
+ decorator
4160
3407
  }) {
4161
3408
  if (!editor.selection)
4162
3409
  return !1;
4163
- const selectedBlocks = [...slate.Editor.nodes(editor, {
4164
- at: editor.selection,
4165
- match: (node) => editor.isTextBlock(node)
4166
- })];
4167
- return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => editor.isListBlock(node) && node.listItem === listItem) : !1;
3410
+ const selectedTextNodes = Array.from(slate.Editor.nodes(editor, {
3411
+ match: slate.Text.isText,
3412
+ at: editor.selection
3413
+ }));
3414
+ return selectedTextNodes.length === 0 ? !1 : slate.Range.isExpanded(editor.selection) ? selectedTextNodes.every((n) => {
3415
+ const [node] = n;
3416
+ return node.marks?.includes(decorator);
3417
+ }) : ({
3418
+ ...slate.Editor.marks(editor) || {}
3419
+ }.marks || []).includes(decorator);
4168
3420
  }
4169
- const toggleStyleActionImplementation = ({
3421
+ const toggleDecoratorActionImplementation = ({
4170
3422
  context,
4171
3423
  action
4172
3424
  }) => {
4173
- isStyleActive({
3425
+ isDecoratorActive({
4174
3426
  editor: action.editor,
4175
- style: action.style
4176
- }) ? removeStyleActionImplementation({
3427
+ decorator: action.decorator
3428
+ }) ? removeDecoratorActionImplementation({
4177
3429
  context,
4178
3430
  action: {
4179
- ...action,
4180
- type: "style.remove"
3431
+ type: "decorator.remove",
3432
+ editor: action.editor,
3433
+ decorator: action.decorator
4181
3434
  }
4182
- }) : addStyleActionImplementation({
3435
+ }) : decoratorAddActionImplementation({
4183
3436
  context,
4184
3437
  action: {
4185
- ...action,
4186
- type: "style.add"
3438
+ type: "decorator.add",
3439
+ editor: action.editor,
3440
+ decorator: action.decorator
4187
3441
  }
4188
3442
  });
4189
- }, removeStyleActionImplementation = ({
4190
- context,
4191
- action
4192
- }) => {
4193
- if (!action.editor.selection)
4194
- return;
4195
- const defaultStyle = context.schema.styles[0].value, guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
4196
- at: action.editor.selection,
4197
- match: (node) => guards.isTextBlock(node)
4198
- })];
4199
- for (const [, at] of selectedBlocks)
4200
- slate.Transforms.setNodes(action.editor, {
4201
- style: defaultStyle
4202
- }, {
4203
- at
4204
- });
4205
- }, addStyleActionImplementation = ({
4206
- context,
4207
- action
4208
- }) => {
4209
- if (!action.editor.selection)
4210
- return;
4211
- const guards = selector_isAtTheStartOfBlock.createGuards(context), selectedBlocks = [...slate.Editor.nodes(action.editor, {
4212
- at: action.editor.selection,
4213
- match: (node) => guards.isTextBlock(node)
4214
- })];
4215
- for (const [, at] of selectedBlocks)
4216
- slate.Transforms.setNodes(action.editor, {
4217
- style: action.style
4218
- }, {
4219
- at
4220
- });
4221
- };
4222
- function isStyleActive({
4223
- editor,
4224
- style
4225
- }) {
4226
- if (!editor.selection)
4227
- return !1;
4228
- const selectedBlocks = [...slate.Editor.nodes(editor, {
4229
- at: editor.selection,
4230
- match: (node) => editor.isTextBlock(node)
4231
- })];
4232
- return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => node.style === style) : !1;
4233
- }
4234
- const debug$2 = debugWithName("API:editable");
3443
+ }, debug$8 = debugWithName("API:editable");
4235
3444
  function createEditableAPI(editor, editorActor) {
4236
3445
  const types2 = editorActor.getSnapshot().context.schema;
4237
3446
  return {
@@ -4296,8 +3505,24 @@ function createEditableAPI(editor, editorActor) {
4296
3505
  marks: () => ({
4297
3506
  ...slate.Editor.marks(editor) || {}
4298
3507
  }).marks || [],
4299
- undo: () => editor.undo(),
4300
- redo: () => editor.redo(),
3508
+ undo: () => {
3509
+ editorActor.send({
3510
+ type: "behavior event",
3511
+ behaviorEvent: {
3512
+ type: "history.undo"
3513
+ },
3514
+ editor
3515
+ });
3516
+ },
3517
+ redo: () => {
3518
+ editorActor.send({
3519
+ type: "behavior event",
3520
+ behaviorEvent: {
3521
+ type: "history.redo"
3522
+ },
3523
+ editor
3524
+ });
3525
+ },
4301
3526
  select: (selection) => {
4302
3527
  const slateSelection = toSlateRange(selection, editor);
4303
3528
  slateSelection ? slate.Transforms.select(editor, slateSelection) : slate.Transforms.deselect(editor), editor.onChange();
@@ -4350,7 +3575,7 @@ function createEditableAPI(editor, editorActor) {
4350
3575
  }], {
4351
3576
  schemaTypes: editorActor.getSnapshot().context.schema
4352
3577
  })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types2.span.name, focusNode = slate.Node.get(editor, focusChildPath);
4353
- return isSpanNode && focusNode._type !== types2.span.name && (debug$2("Inserting span child next to inline object child, moving selection + 1"), editor.move({
3578
+ return isSpanNode && focusNode._type !== types2.span.name && (debug$8("Inserting span child next to inline object child, moving selection + 1"), editor.move({
4354
3579
  distance: 1,
4355
3580
  unit: "character"
4356
3581
  })), slate.Transforms.insertNodes(editor, child, {
@@ -4488,18 +3713,18 @@ function createEditableAPI(editor, editorActor) {
4488
3713
  throw new Error("Invalid range");
4489
3714
  if (range) {
4490
3715
  if (!options?.mode || options?.mode === "selected") {
4491
- debug$2("Deleting content in selection"), slate.Transforms.delete(editor, {
3716
+ debug$8("Deleting content in selection"), slate.Transforms.delete(editor, {
4492
3717
  at: range,
4493
3718
  hanging: !0,
4494
3719
  voids: !0
4495
3720
  }), editor.onChange();
4496
3721
  return;
4497
3722
  }
4498
- options?.mode === "blocks" && (debug$2("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
3723
+ options?.mode === "blocks" && (debug$8("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
4499
3724
  at: range,
4500
3725
  voids: !0,
4501
3726
  match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && slate.Element.isElement(node)
4502
- })), options?.mode === "children" && (debug$2("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
3727
+ })), options?.mode === "children" && (debug$8("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
4503
3728
  at: range,
4504
3729
  voids: !0,
4505
3730
  match: (node) => node._type === types2.span.name || // Text children
@@ -4626,7 +3851,7 @@ const addAnnotationActionImplementation = ({
4626
3851
  action
4627
3852
  }) => {
4628
3853
  const editor = action.editor;
4629
- if (debug$2("Removing annotation", action.annotation.name), !!editor.selection)
3854
+ if (debug$8("Removing annotation", action.annotation.name), !!editor.selection)
4630
3855
  if (slate.Range.isCollapsed(editor.selection)) {
4631
3856
  const [block, blockPath] = slate.Editor.node(editor, editor.selection, {
4632
3857
  depth: 1
@@ -4796,17 +4021,48 @@ const blockSetBehaviorActionImplementation = ({
4796
4021
  location && slate.Transforms.unsetNodes(action.editor, action.props, {
4797
4022
  at: location
4798
4023
  });
4799
- }, dataTransferSetActionImplementation = ({
4800
- action
4801
- }) => {
4802
- action.dataTransfer.setData(action.mimeType, action.data);
4803
- }, deleteActionImplementation = ({
4804
- action
4805
- }) => {
4806
- const range = toSlateRange(action.selection, action.editor);
4024
+ }, dataTransferSetActionImplementation = ({
4025
+ action
4026
+ }) => {
4027
+ action.dataTransfer.setData(action.mimeType, action.data);
4028
+ }, deleteActionImplementation = ({
4029
+ action
4030
+ }) => {
4031
+ const range = toSlateRange(action.selection, action.editor);
4032
+ if (!range)
4033
+ throw new Error(`Failed to get Slate Range for selection ${JSON.stringify(action.selection)}`);
4034
+ slate.select(action.editor, range), slate.deleteFragment(action.editor);
4035
+ }, deleteTextActionImplementation = ({
4036
+ context,
4037
+ action
4038
+ }) => {
4039
+ const value = fromSlateValue(action.editor.children, context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(action.editor)), selection = util_blockOffsetsToSelection.blockOffsetsToSelection({
4040
+ value,
4041
+ offsets: {
4042
+ anchor: action.anchor,
4043
+ focus: action.focus
4044
+ }
4045
+ });
4046
+ if (!selection)
4047
+ throw new Error("Unable to find selection from block offsets");
4048
+ const trimmedSelection = selector_getTrimmedSelection.getTrimmedSelection({
4049
+ context: {
4050
+ converters: [],
4051
+ schema: context.schema,
4052
+ keyGenerator: context.keyGenerator,
4053
+ activeDecorators: [],
4054
+ value,
4055
+ selection
4056
+ }
4057
+ });
4058
+ if (!trimmedSelection)
4059
+ throw new Error("Unable to find trimmed selection");
4060
+ const range = toSlateRange(trimmedSelection, action.editor);
4807
4061
  if (!range)
4808
- throw new Error(`Failed to get Slate Range for selection ${JSON.stringify(action.selection)}`);
4809
- slate.select(action.editor, range), slate.deleteFragment(action.editor);
4062
+ throw new Error("Unable to find Slate range from trimmed selection");
4063
+ slate.Transforms.delete(action.editor, {
4064
+ at: range
4065
+ });
4810
4066
  }, insertBlockObjectActionImplementation = ({
4811
4067
  context,
4812
4068
  action
@@ -4922,7 +4178,7 @@ const blockSetBehaviorActionImplementation = ({
4922
4178
  context,
4923
4179
  action
4924
4180
  }) => {
4925
- const parsedBlock = parseBlocks.parseBlock({
4181
+ const parsedBlock = util_blockOffsetsToSelection.parseBlock({
4926
4182
  block: action.block,
4927
4183
  context,
4928
4184
  options: {
@@ -4996,7 +4252,7 @@ const blockSetBehaviorActionImplementation = ({
4996
4252
  slateReact.ReactEditor.blur(action.editor);
4997
4253
  },
4998
4254
  "data transfer.set": dataTransferSetActionImplementation,
4999
- "decorator.add": addDecoratorActionImplementation,
4255
+ "decorator.add": decoratorAddActionImplementation,
5000
4256
  "decorator.remove": removeDecoratorActionImplementation,
5001
4257
  "decorator.toggle": toggleDecoratorActionImplementation,
5002
4258
  focus: ({
@@ -5036,33 +4292,7 @@ const blockSetBehaviorActionImplementation = ({
5036
4292
  at: range
5037
4293
  });
5038
4294
  },
5039
- "delete.text": ({
5040
- context,
5041
- action
5042
- }) => {
5043
- const value = fromSlateValue(action.editor.children, context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(action.editor)), anchor = util_reverseSelection.blockOffsetToSpanSelectionPoint({
5044
- value,
5045
- blockOffset: action.anchor
5046
- }), focus = util_reverseSelection.blockOffsetToSpanSelectionPoint({
5047
- value,
5048
- blockOffset: action.focus
5049
- });
5050
- if (!anchor || !focus) {
5051
- console.error("Unable to find anchor or focus selection point");
5052
- return;
5053
- }
5054
- const range = toSlateRange({
5055
- anchor,
5056
- focus
5057
- }, action.editor);
5058
- if (!range) {
5059
- console.error("Unable to find Slate range from selection points");
5060
- return;
5061
- }
5062
- slate.Transforms.delete(action.editor, {
5063
- at: range
5064
- });
5065
- },
4295
+ "delete.text": deleteTextActionImplementation,
5066
4296
  "deserialization.failure": ({
5067
4297
  action
5068
4298
  }) => {
@@ -5081,6 +4311,8 @@ const blockSetBehaviorActionImplementation = ({
5081
4311
  }
5082
4312
  });
5083
4313
  },
4314
+ "history.redo": historyRedoActionImplementation,
4315
+ "history.undo": historyUndoActionImplementation,
5084
4316
  "insert.block": insertBlockActionImplementation,
5085
4317
  "insert.blocks": insertBlocksActionImplementation,
5086
4318
  "insert.block object": insertBlockObjectActionImplementation,
@@ -5369,6 +4601,20 @@ function performDefaultAction({
5369
4601
  });
5370
4602
  break;
5371
4603
  }
4604
+ case "history.redo": {
4605
+ behaviorActionImplementations["history.redo"]({
4606
+ context,
4607
+ action
4608
+ });
4609
+ break;
4610
+ }
4611
+ case "history.undo": {
4612
+ behaviorActionImplementations["history.undo"]({
4613
+ context,
4614
+ action
4615
+ });
4616
+ break;
4617
+ }
5372
4618
  case "insert.block": {
5373
4619
  behaviorActionImplementations["insert.block"]({
5374
4620
  context,
@@ -5500,49 +4746,942 @@ function performDefaultAction({
5500
4746
  context,
5501
4747
  action
5502
4748
  });
5503
- break;
5504
- }
5505
- case "serialization.success": {
5506
- behaviorActionImplementations["serialization.success"]({
5507
- context,
5508
- action
4749
+ break;
4750
+ }
4751
+ case "serialization.success": {
4752
+ behaviorActionImplementations["serialization.success"]({
4753
+ context,
4754
+ action
4755
+ });
4756
+ break;
4757
+ }
4758
+ case "style.add": {
4759
+ behaviorActionImplementations["style.add"]({
4760
+ context,
4761
+ action
4762
+ });
4763
+ break;
4764
+ }
4765
+ case "style.remove": {
4766
+ behaviorActionImplementations["style.remove"]({
4767
+ context,
4768
+ action
4769
+ });
4770
+ break;
4771
+ }
4772
+ case "style.toggle": {
4773
+ behaviorActionImplementations["style.toggle"]({
4774
+ context,
4775
+ action
4776
+ });
4777
+ break;
4778
+ }
4779
+ case "text block.set": {
4780
+ behaviorActionImplementations["text block.set"]({
4781
+ context,
4782
+ action
4783
+ });
4784
+ break;
4785
+ }
4786
+ default:
4787
+ behaviorActionImplementations["text block.unset"]({
4788
+ context,
4789
+ action
4790
+ });
4791
+ }
4792
+ }
4793
+ function createWithEventListeners(editorActor, subscriptions) {
4794
+ return function(editor) {
4795
+ if (editorActor.getSnapshot().context.maxBlocks !== void 0)
4796
+ return editor;
4797
+ subscriptions.push(() => {
4798
+ const subscription = editorActor.on("*", (event) => {
4799
+ switch (event.type) {
4800
+ // These events are not relevant for Behaviors
4801
+ case "blurred":
4802
+ case "done loading":
4803
+ case "editable":
4804
+ case "error":
4805
+ case "focused":
4806
+ case "invalid value":
4807
+ case "loading":
4808
+ case "mutation":
4809
+ case "patch":
4810
+ case "patches":
4811
+ case "read only":
4812
+ case "ready":
4813
+ case "selection":
4814
+ case "value changed":
4815
+ case "unset":
4816
+ break;
4817
+ case "custom.*":
4818
+ editorActor.send({
4819
+ type: "custom behavior event",
4820
+ behaviorEvent: event.event,
4821
+ editor
4822
+ });
4823
+ break;
4824
+ default:
4825
+ editorActor.send({
4826
+ type: "behavior event",
4827
+ behaviorEvent: event,
4828
+ editor
4829
+ });
4830
+ break;
4831
+ }
4832
+ });
4833
+ return () => {
4834
+ subscription.unsubscribe();
4835
+ };
4836
+ });
4837
+ const {
4838
+ deleteBackward,
4839
+ deleteForward,
4840
+ insertBreak,
4841
+ insertData,
4842
+ insertText,
4843
+ select,
4844
+ setFragmentData
4845
+ } = editor;
4846
+ return editor.deleteBackward = (unit) => {
4847
+ if (isApplyingBehaviorActions(editor)) {
4848
+ deleteBackward(unit);
4849
+ return;
4850
+ }
4851
+ editorActor.send({
4852
+ type: "behavior event",
4853
+ behaviorEvent: {
4854
+ type: "delete.backward",
4855
+ unit
4856
+ },
4857
+ editor
4858
+ });
4859
+ }, editor.deleteForward = (unit) => {
4860
+ if (isApplyingBehaviorActions(editor)) {
4861
+ deleteForward(unit);
4862
+ return;
4863
+ }
4864
+ editorActor.send({
4865
+ type: "behavior event",
4866
+ behaviorEvent: {
4867
+ type: "delete.forward",
4868
+ unit
4869
+ },
4870
+ editor
4871
+ });
4872
+ }, editor.insertBreak = () => {
4873
+ if (isApplyingBehaviorActions(editor)) {
4874
+ insertBreak();
4875
+ return;
4876
+ }
4877
+ editorActor.send({
4878
+ type: "behavior event",
4879
+ behaviorEvent: {
4880
+ type: "insert.break"
4881
+ },
4882
+ editor
4883
+ });
4884
+ }, editor.insertData = (dataTransfer) => {
4885
+ if (isApplyingBehaviorActions(editor)) {
4886
+ insertData(dataTransfer);
4887
+ return;
4888
+ }
4889
+ editorActor.send({
4890
+ type: "behavior event",
4891
+ behaviorEvent: {
4892
+ type: "deserialize",
4893
+ dataTransfer
4894
+ },
4895
+ editor
4896
+ });
4897
+ }, editor.insertSoftBreak = () => {
4898
+ if (isApplyingBehaviorActions(editor)) {
4899
+ insertSoftBreakActionImplementation({
4900
+ context: {
4901
+ keyGenerator: editorActor.getSnapshot().context.keyGenerator,
4902
+ schema: editorActor.getSnapshot().context.schema
4903
+ },
4904
+ action: {
4905
+ type: "insert.soft break",
4906
+ editor
4907
+ }
4908
+ });
4909
+ return;
4910
+ }
4911
+ editorActor.send({
4912
+ type: "behavior event",
4913
+ behaviorEvent: {
4914
+ type: "insert.soft break"
4915
+ },
4916
+ editor
4917
+ });
4918
+ }, editor.insertText = (text, options) => {
4919
+ if (isApplyingBehaviorActions(editor)) {
4920
+ insertText(text, options);
4921
+ return;
4922
+ }
4923
+ editorActor.send({
4924
+ type: "behavior event",
4925
+ behaviorEvent: {
4926
+ type: "insert.text",
4927
+ text,
4928
+ options
4929
+ },
4930
+ editor,
4931
+ defaultActionCallback: () => {
4932
+ insertText(text, options);
4933
+ }
4934
+ });
4935
+ }, editor.redo = () => {
4936
+ if (isApplyingBehaviorActions(editor)) {
4937
+ performAction({
4938
+ context: {
4939
+ keyGenerator: editorActor.getSnapshot().context.keyGenerator,
4940
+ schema: editorActor.getSnapshot().context.schema
4941
+ },
4942
+ action: {
4943
+ type: "history.redo",
4944
+ editor
4945
+ }
4946
+ });
4947
+ return;
4948
+ }
4949
+ editorActor.send({
4950
+ type: "behavior event",
4951
+ behaviorEvent: {
4952
+ type: "history.redo"
4953
+ },
4954
+ editor
4955
+ });
4956
+ }, editor.select = (location) => {
4957
+ if (isApplyingBehaviorActions(editor)) {
4958
+ select(location);
4959
+ return;
4960
+ }
4961
+ const range = slate.Editor.range(editor, location);
4962
+ editorActor.send({
4963
+ type: "behavior event",
4964
+ behaviorEvent: {
4965
+ type: "select",
4966
+ selection: toPortableTextRange(fromSlateValue(editor.children, editorActor.getSnapshot().context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(editor)), range, editorActor.getSnapshot().context.schema)
4967
+ },
4968
+ editor,
4969
+ defaultActionCallback: () => {
4970
+ select(location);
4971
+ }
4972
+ });
4973
+ }, editor.setFragmentData = (dataTransfer, originEvent) => {
4974
+ if (originEvent === "drag") {
4975
+ setFragmentData(dataTransfer);
4976
+ return;
4977
+ }
4978
+ if (isApplyingBehaviorActions(editor)) {
4979
+ setFragmentData(dataTransfer);
4980
+ return;
4981
+ }
4982
+ dataTransfer.clearData(), editorActor.send({
4983
+ type: "behavior event",
4984
+ behaviorEvent: {
4985
+ type: "serialize",
4986
+ dataTransfer,
4987
+ originEvent: originEvent ?? "unknown"
4988
+ },
4989
+ editor
5509
4990
  });
5510
- break;
4991
+ }, editor.undo = () => {
4992
+ if (isApplyingBehaviorActions(editor)) {
4993
+ performAction({
4994
+ context: {
4995
+ keyGenerator: editorActor.getSnapshot().context.keyGenerator,
4996
+ schema: editorActor.getSnapshot().context.schema
4997
+ },
4998
+ action: {
4999
+ type: "history.undo",
5000
+ editor
5001
+ }
5002
+ });
5003
+ return;
5004
+ }
5005
+ editorActor.send({
5006
+ type: "behavior event",
5007
+ behaviorEvent: {
5008
+ type: "history.undo"
5009
+ },
5010
+ editor
5011
+ });
5012
+ }, editor;
5013
+ };
5014
+ }
5015
+ function createWithMaxBlocks(editorActor) {
5016
+ return function(editor) {
5017
+ const {
5018
+ apply: apply2
5019
+ } = editor;
5020
+ return editor.apply = (operation) => {
5021
+ if (editorActor.getSnapshot().matches({
5022
+ "edit mode": "read only"
5023
+ })) {
5024
+ apply2(operation);
5025
+ return;
5026
+ }
5027
+ if (isChangingRemotely(editor)) {
5028
+ apply2(operation);
5029
+ return;
5030
+ }
5031
+ if (isUndoing(editor) || isRedoing(editor)) {
5032
+ apply2(operation);
5033
+ return;
5034
+ }
5035
+ const rows = editorActor.getSnapshot().context.maxBlocks ?? -1;
5036
+ rows > 0 && editor.children.length >= rows && (operation.type === "insert_node" || operation.type === "split_node") && operation.path.length === 1 || apply2(operation);
5037
+ }, editor;
5038
+ };
5039
+ }
5040
+ function createWithObjectKeys(editorActor, schemaTypes) {
5041
+ return function(editor) {
5042
+ const {
5043
+ apply: apply2,
5044
+ normalizeNode
5045
+ } = editor;
5046
+ return editor.apply = (operation) => {
5047
+ if (isChangingRemotely(editor)) {
5048
+ apply2(operation);
5049
+ return;
5050
+ }
5051
+ if (isUndoing(editor) || isRedoing(editor)) {
5052
+ apply2(operation);
5053
+ return;
5054
+ }
5055
+ if (operation.type === "split_node") {
5056
+ const existingKeys = [...slate.Node.descendants(editor)].map(([node]) => node._key);
5057
+ apply2({
5058
+ ...operation,
5059
+ properties: {
5060
+ ...operation.properties,
5061
+ _key: operation.properties._key === void 0 || existingKeys.includes(operation.properties._key) ? editorActor.getSnapshot().context.keyGenerator() : operation.properties._key
5062
+ }
5063
+ });
5064
+ return;
5065
+ }
5066
+ if (operation.type === "insert_node" && !slate.Editor.isEditor(operation.node)) {
5067
+ const existingKeys = [...slate.Node.descendants(editor)].map(([node]) => node._key);
5068
+ apply2({
5069
+ ...operation,
5070
+ node: {
5071
+ ...operation.node,
5072
+ _key: operation.node._key === void 0 || existingKeys.includes(operation.node._key) ? editorActor.getSnapshot().context.keyGenerator() : operation.node._key
5073
+ }
5074
+ });
5075
+ return;
5076
+ }
5077
+ apply2(operation);
5078
+ }, editor.normalizeNode = (entry) => {
5079
+ const [node, path] = entry;
5080
+ if (slate.Element.isElement(node) && node._type === schemaTypes.block.name) {
5081
+ if (!node._key) {
5082
+ editorActor.send({
5083
+ type: "normalizing"
5084
+ }), slate.Transforms.setNodes(editor, {
5085
+ _key: editorActor.getSnapshot().context.keyGenerator()
5086
+ }, {
5087
+ at: path
5088
+ }), editorActor.send({
5089
+ type: "done normalizing"
5090
+ });
5091
+ return;
5092
+ }
5093
+ for (const [child, childPath] of slate.Node.children(editor, path))
5094
+ if (!child._key) {
5095
+ editorActor.send({
5096
+ type: "normalizing"
5097
+ }), slate.Transforms.setNodes(editor, {
5098
+ _key: editorActor.getSnapshot().context.keyGenerator()
5099
+ }, {
5100
+ at: childPath
5101
+ }), editorActor.send({
5102
+ type: "done normalizing"
5103
+ });
5104
+ return;
5105
+ }
5106
+ }
5107
+ normalizeNode(entry);
5108
+ }, editor;
5109
+ };
5110
+ }
5111
+ const debug$7 = debugWithName("applyPatches"), debugVerbose = debug$7.enabled && !0;
5112
+ function createApplyPatch(schemaTypes) {
5113
+ return (editor, patch) => {
5114
+ let changed = !1;
5115
+ debugVerbose && (debug$7(`
5116
+
5117
+ NEW PATCH =============================================================`), debug$7(JSON.stringify(patch, null, 2)));
5118
+ try {
5119
+ switch (patch.type) {
5120
+ case "insert":
5121
+ changed = insertPatch(editor, patch, schemaTypes);
5122
+ break;
5123
+ case "unset":
5124
+ changed = unsetPatch(editor, patch);
5125
+ break;
5126
+ case "set":
5127
+ changed = setPatch(editor, patch);
5128
+ break;
5129
+ case "diffMatchPatch":
5130
+ changed = diffMatchPatch(editor, patch);
5131
+ break;
5132
+ default:
5133
+ debug$7("Unhandled patch", patch.type);
5134
+ }
5135
+ } catch (err) {
5136
+ console.error(err);
5511
5137
  }
5512
- case "style.add": {
5513
- behaviorActionImplementations["style.add"]({
5514
- context,
5515
- action
5138
+ return changed;
5139
+ };
5140
+ }
5141
+ function diffMatchPatch(editor, patch) {
5142
+ const {
5143
+ block,
5144
+ child,
5145
+ childPath
5146
+ } = findBlockAndChildFromPath(editor, patch.path);
5147
+ if (!block)
5148
+ return debug$7("Block not found"), !1;
5149
+ if (!child || !childPath)
5150
+ return debug$7("Child not found"), !1;
5151
+ if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
5152
+ return !1;
5153
+ const patches2 = parse(patch.value), [newValue] = apply(patches2, child.text, {
5154
+ allowExceedingIndices: !0
5155
+ }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
5156
+ debugState(editor, "before");
5157
+ let offset = 0;
5158
+ for (const [op, text] of diff$1)
5159
+ op === DIFF_INSERT ? (editor.apply({
5160
+ type: "insert_text",
5161
+ path: childPath,
5162
+ offset,
5163
+ text
5164
+ }), offset += text.length) : op === DIFF_DELETE ? editor.apply({
5165
+ type: "remove_text",
5166
+ path: childPath,
5167
+ offset,
5168
+ text
5169
+ }) : op === DIFF_EQUAL && (offset += text.length);
5170
+ return debugState(editor, "after"), !0;
5171
+ }
5172
+ function insertPatch(editor, patch, schemaTypes) {
5173
+ const {
5174
+ block: targetBlock,
5175
+ child: targetChild,
5176
+ blockPath: targetBlockPath,
5177
+ childPath: targetChildPath
5178
+ } = findBlockAndChildFromPath(editor, patch.path);
5179
+ if (!targetBlock || !targetBlockPath)
5180
+ return debug$7("Block not found"), !1;
5181
+ if (patch.path.length > 1 && patch.path[1] !== "children")
5182
+ return debug$7("Ignoring patch targeting void value"), !1;
5183
+ if (patch.path.length === 1) {
5184
+ const {
5185
+ items: items2,
5186
+ position: position2
5187
+ } = patch, blocksToInsert = toSlateValue(items2, {
5188
+ schemaTypes
5189
+ }, KEY_TO_SLATE_ELEMENT.get(editor)), targetBlockIndex = targetBlockPath[0], normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex;
5190
+ return debug$7(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
5191
+ at: [normalizedIdx2]
5192
+ }), debugState(editor, "after"), !0;
5193
+ }
5194
+ const {
5195
+ items,
5196
+ position
5197
+ } = patch;
5198
+ if (!targetChild || !targetChildPath)
5199
+ return debug$7("Child not found"), !1;
5200
+ const childrenToInsert = targetBlock && toSlateValue([{
5201
+ ...targetBlock,
5202
+ children: items
5203
+ }], {
5204
+ schemaTypes
5205
+ }, KEY_TO_SLATE_ELEMENT.get(editor)), targetChildIndex = targetChildPath[1], normalizedIdx = position === "after" ? targetChildIndex + 1 : targetChildIndex, childInsertPath = [targetChildPath[0], normalizedIdx];
5206
+ return debug$7(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
5207
+ at: childInsertPath
5208
+ }), debugState(editor, "after"), !0;
5209
+ }
5210
+ function setPatch(editor, patch) {
5211
+ let value = patch.value;
5212
+ typeof patch.path[3] == "string" && (value = {}, value[patch.path[3]] = patch.value);
5213
+ const {
5214
+ block,
5215
+ blockPath,
5216
+ child,
5217
+ childPath
5218
+ } = findBlockAndChildFromPath(editor, patch.path);
5219
+ if (!block)
5220
+ return debug$7("Block not found"), !1;
5221
+ const isTextBlock = editor.isTextBlock(block);
5222
+ if (isTextBlock && patch.path.length > 1 && patch.path[1] !== "children")
5223
+ return debug$7("Ignoring setting void value"), !1;
5224
+ if (debugState(editor, "before"), isTextBlock && child && childPath) {
5225
+ if (slate.Text.isText(value) && slate.Text.isText(child)) {
5226
+ const newText = child.text;
5227
+ value.text !== newText && (debug$7("Setting text property"), editor.apply({
5228
+ type: "remove_text",
5229
+ path: childPath,
5230
+ offset: 0,
5231
+ text: newText
5232
+ }), editor.apply({
5233
+ type: "insert_text",
5234
+ path: childPath,
5235
+ offset: 0,
5236
+ text: value.text
5237
+ }), editor.onChange());
5238
+ } else
5239
+ debug$7("Setting non-text property"), editor.apply({
5240
+ type: "set_node",
5241
+ path: childPath,
5242
+ properties: {},
5243
+ newProperties: value
5516
5244
  });
5517
- break;
5518
- }
5519
- case "style.remove": {
5520
- behaviorActionImplementations["style.remove"]({
5521
- context,
5522
- action
5245
+ return !0;
5246
+ } else if (slate.Element.isElement(block) && patch.path.length === 1 && blockPath) {
5247
+ debug$7("Setting block property");
5248
+ const {
5249
+ children,
5250
+ ...nextRest
5251
+ } = value, {
5252
+ children: prevChildren,
5253
+ ...prevRest
5254
+ } = block || {
5255
+ children: void 0
5256
+ };
5257
+ editor.apply({
5258
+ type: "set_node",
5259
+ path: blockPath,
5260
+ properties: {
5261
+ ...prevRest
5262
+ },
5263
+ newProperties: nextRest
5264
+ }), debug$7("Setting children"), block.children.forEach((c, cIndex) => {
5265
+ editor.apply({
5266
+ type: "remove_node",
5267
+ path: blockPath.concat(block.children.length - 1 - cIndex),
5268
+ node: c
5523
5269
  });
5524
- break;
5525
- }
5526
- case "style.toggle": {
5527
- behaviorActionImplementations["style.toggle"]({
5528
- context,
5529
- action
5270
+ }), Array.isArray(children) && children.forEach((c, cIndex) => {
5271
+ editor.apply({
5272
+ type: "insert_node",
5273
+ path: blockPath.concat(cIndex),
5274
+ node: c
5530
5275
  });
5531
- break;
5532
- }
5533
- case "text block.set": {
5534
- behaviorActionImplementations["text block.set"]({
5535
- context,
5536
- action
5276
+ });
5277
+ } else if (block && "value" in block)
5278
+ if (patch.path.length > 1 && patch.path[1] !== "children") {
5279
+ const newVal = patches.applyAll(block.value, [{
5280
+ ...patch,
5281
+ path: patch.path.slice(1)
5282
+ }]);
5283
+ slate.Transforms.setNodes(editor, {
5284
+ ...block,
5285
+ value: newVal
5286
+ }, {
5287
+ at: blockPath
5537
5288
  });
5538
- break;
5539
- }
5540
- default:
5541
- behaviorActionImplementations["text block.unset"]({
5542
- context,
5543
- action
5289
+ } else
5290
+ return !1;
5291
+ return debugState(editor, "after"), !0;
5292
+ }
5293
+ function unsetPatch(editor, patch) {
5294
+ if (patch.path.length === 0) {
5295
+ debug$7("Removing everything"), debugState(editor, "before");
5296
+ const previousSelection = editor.selection;
5297
+ return slate.Transforms.deselect(editor), editor.children.forEach((_child, i) => {
5298
+ slate.Transforms.removeNodes(editor, {
5299
+ at: [i]
5544
5300
  });
5301
+ }), slate.Transforms.insertNodes(editor, editor.pteCreateTextBlock({
5302
+ decorators: []
5303
+ })), previousSelection && slate.Transforms.select(editor, {
5304
+ anchor: {
5305
+ path: [0, 0],
5306
+ offset: 0
5307
+ },
5308
+ focus: {
5309
+ path: [0, 0],
5310
+ offset: 0
5311
+ }
5312
+ }), editor.onChange(), debugState(editor, "after"), !0;
5313
+ }
5314
+ const {
5315
+ block,
5316
+ blockPath,
5317
+ child,
5318
+ childPath
5319
+ } = findBlockAndChildFromPath(editor, patch.path);
5320
+ if (patch.path.length === 1) {
5321
+ if (!block || !blockPath)
5322
+ return debug$7("Block not found"), !1;
5323
+ const blockIndex = blockPath[0];
5324
+ return debug$7(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
5325
+ at: [blockIndex]
5326
+ }), debugState(editor, "after"), !0;
5545
5327
  }
5328
+ return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$7("Child not found"), !1) : (debug$7(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose && debug$7(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
5329
+ at: childPath
5330
+ }), debugState(editor, "after"), !0) : !1;
5331
+ }
5332
+ function isKeyedSegment(segment) {
5333
+ return typeof segment == "object" && "_key" in segment;
5334
+ }
5335
+ function debugState(editor, stateName) {
5336
+ debugVerbose && (debug$7(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$7(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
5337
+ }
5338
+ function findBlockFromPath(editor, path) {
5339
+ let blockIndex = -1;
5340
+ const block = editor.children.find((node, index) => {
5341
+ const isMatch = isKeyedSegment(path[0]) ? node._key === path[0]._key : index === path[0];
5342
+ return isMatch && (blockIndex = index), isMatch;
5343
+ });
5344
+ return block ? {
5345
+ block,
5346
+ path: [blockIndex]
5347
+ } : {};
5348
+ }
5349
+ function findBlockAndChildFromPath(editor, path) {
5350
+ const {
5351
+ block,
5352
+ path: blockPath
5353
+ } = findBlockFromPath(editor, path);
5354
+ if (!(slate.Element.isElement(block) && path[1] === "children"))
5355
+ return {
5356
+ block,
5357
+ blockPath,
5358
+ child: void 0,
5359
+ childPath: void 0
5360
+ };
5361
+ let childIndex = -1;
5362
+ const child = block.children.find((node, index) => {
5363
+ const isMatch = isKeyedSegment(path[2]) ? node._key === path[2]._key : index === path[2];
5364
+ return isMatch && (childIndex = index), isMatch;
5365
+ });
5366
+ return child ? {
5367
+ block,
5368
+ child,
5369
+ blockPath,
5370
+ childPath: blockPath?.concat(childIndex)
5371
+ } : {
5372
+ block,
5373
+ blockPath,
5374
+ child: void 0,
5375
+ childPath: void 0
5376
+ };
5377
+ }
5378
+ const debug$6 = debugWithName("plugin:withPatches");
5379
+ function createWithPatches({
5380
+ editorActor,
5381
+ patchFunctions,
5382
+ schemaTypes,
5383
+ subscriptions
5384
+ }) {
5385
+ let previousChildren;
5386
+ const applyPatch = createApplyPatch(schemaTypes);
5387
+ return function(editor) {
5388
+ IS_PROCESSING_REMOTE_CHANGES.set(editor, !1), PATCHING.set(editor, !0), previousChildren = [...editor.children];
5389
+ const {
5390
+ apply: apply2
5391
+ } = editor;
5392
+ let bufferedPatches = [];
5393
+ const handleBufferedRemotePatches = () => {
5394
+ if (bufferedPatches.length === 0)
5395
+ return;
5396
+ const patches2 = bufferedPatches;
5397
+ bufferedPatches = [];
5398
+ let changed = !1;
5399
+ withRemoteChanges(editor, () => {
5400
+ slate.Editor.withoutNormalizing(editor, () => {
5401
+ withoutPatching(editor, () => {
5402
+ withoutSaving(editor, () => {
5403
+ patches2.forEach((patch) => {
5404
+ debug$6.enabled && debug$6(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
5405
+ });
5406
+ });
5407
+ });
5408
+ }), changed && (editor.normalize(), editor.onChange());
5409
+ });
5410
+ }, handlePatches = ({
5411
+ patches: patches2
5412
+ }) => {
5413
+ const remotePatches = patches2.filter((p) => p.origin !== "local");
5414
+ remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
5415
+ };
5416
+ return subscriptions.push(() => {
5417
+ debug$6("Subscribing to remote patches");
5418
+ const sub = editorActor.on("patches", handlePatches);
5419
+ return () => {
5420
+ debug$6("Unsubscribing to remote patches"), sub.unsubscribe();
5421
+ };
5422
+ }), editor.apply = (operation) => {
5423
+ let patches$1 = [];
5424
+ previousChildren = editor.children;
5425
+ const editorWasEmpty = isEqualToEmptyEditor(previousChildren, schemaTypes);
5426
+ apply2(operation);
5427
+ const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes);
5428
+ if (!isPatching(editor))
5429
+ return editor;
5430
+ switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches$1.push(patches.insert(previousChildren, "before", [0])), operation.type) {
5431
+ case "insert_text":
5432
+ patches$1 = [...patches$1, ...patchFunctions.insertTextPatch(editor, operation, previousChildren)];
5433
+ break;
5434
+ case "remove_text":
5435
+ patches$1 = [...patches$1, ...patchFunctions.removeTextPatch(editor, operation, previousChildren)];
5436
+ break;
5437
+ case "remove_node":
5438
+ patches$1 = [...patches$1, ...patchFunctions.removeNodePatch(editor, operation, previousChildren)];
5439
+ break;
5440
+ case "split_node":
5441
+ patches$1 = [...patches$1, ...patchFunctions.splitNodePatch(editor, operation, previousChildren)];
5442
+ break;
5443
+ case "insert_node":
5444
+ patches$1 = [...patches$1, ...patchFunctions.insertNodePatch(editor, operation, previousChildren)];
5445
+ break;
5446
+ case "set_node":
5447
+ patches$1 = [...patches$1, ...patchFunctions.setNodePatch(editor, operation, previousChildren)];
5448
+ break;
5449
+ case "merge_node":
5450
+ patches$1 = [...patches$1, ...patchFunctions.mergeNodePatch(editor, operation, previousChildren)];
5451
+ break;
5452
+ case "move_node":
5453
+ patches$1 = [...patches$1, ...patchFunctions.moveNodePatch(editor, operation, previousChildren)];
5454
+ break;
5455
+ }
5456
+ return !editorWasEmpty && editorIsEmpty && ["merge_node", "set_node", "remove_text", "remove_node"].includes(operation.type) && (patches$1 = [...patches$1, patches.unset([])], editorActor.send({
5457
+ type: "notify.unset",
5458
+ previousValue: fromSlateValue(previousChildren, schemaTypes.block.name, KEY_TO_VALUE_ELEMENT.get(editor))
5459
+ })), editorWasEmpty && patches$1.length > 0 && (patches$1 = [patches.setIfMissing([], []), ...patches$1]), patches$1.length > 0 && patches$1.forEach((patch) => {
5460
+ editorActor.send({
5461
+ type: "patch",
5462
+ patch: {
5463
+ ...patch,
5464
+ origin: "local"
5465
+ }
5466
+ });
5467
+ }), editor;
5468
+ }, editor;
5469
+ };
5470
+ }
5471
+ const debug$5 = debugWithName("plugin:withPlaceholderBlock");
5472
+ function createWithPlaceholderBlock(editorActor) {
5473
+ return function(editor) {
5474
+ const {
5475
+ apply: apply2
5476
+ } = editor;
5477
+ return editor.apply = (op) => {
5478
+ if (editorActor.getSnapshot().matches({
5479
+ "edit mode": "read only"
5480
+ })) {
5481
+ apply2(op);
5482
+ return;
5483
+ }
5484
+ if (isChangingRemotely(editor)) {
5485
+ apply2(op);
5486
+ return;
5487
+ }
5488
+ if (isUndoing(editor) || isRedoing(editor)) {
5489
+ apply2(op);
5490
+ return;
5491
+ }
5492
+ if (op.type === "remove_node") {
5493
+ const node = op.node;
5494
+ if (op.path[0] === 0 && slate.Editor.isVoid(editor, node)) {
5495
+ const nextPath = slate.Path.next(op.path);
5496
+ editor.children[nextPath[0]] || (debug$5("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
5497
+ decorators: []
5498
+ })));
5499
+ }
5500
+ }
5501
+ apply2(op);
5502
+ }, editor;
5503
+ };
5504
+ }
5505
+ const debug$4 = debugWithName("plugin:withPortableTextBlockStyle");
5506
+ function createWithPortableTextBlockStyle(editorActor, types2) {
5507
+ const defaultStyle = types2.styles[0].value;
5508
+ return function(editor) {
5509
+ const {
5510
+ normalizeNode
5511
+ } = editor;
5512
+ return editor.normalizeNode = (nodeEntry) => {
5513
+ const [, path] = nodeEntry;
5514
+ for (const op of editor.operations)
5515
+ if (op.type === "split_node" && op.path.length === 1 && editor.isTextBlock(op.properties) && op.properties.style !== defaultStyle && op.path[0] === path[0] && !slate.Path.equals(path, op.path)) {
5516
+ const [child] = slate.Editor.node(editor, [op.path[0] + 1, 0]);
5517
+ if (slate.Text.isText(child) && child.text === "") {
5518
+ debug$4(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
5519
+ type: "normalizing"
5520
+ }), slate.Transforms.setNodes(editor, {
5521
+ style: defaultStyle
5522
+ }, {
5523
+ at: [op.path[0] + 1],
5524
+ voids: !1
5525
+ }), editorActor.send({
5526
+ type: "done normalizing"
5527
+ });
5528
+ return;
5529
+ }
5530
+ }
5531
+ normalizeNode(nodeEntry);
5532
+ }, editor;
5533
+ };
5534
+ }
5535
+ debugWithName("plugin:withPortableTextSelections");
5536
+ function createWithPortableTextSelections(editorActor, types2) {
5537
+ let prevSelection = null;
5538
+ return function(editor) {
5539
+ const emitPortableTextSelection = () => {
5540
+ if (prevSelection !== editor.selection) {
5541
+ let ptRange = null;
5542
+ if (editor.selection) {
5543
+ const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
5544
+ if (existing)
5545
+ ptRange = existing;
5546
+ else {
5547
+ const value = editor.children;
5548
+ ptRange = toPortableTextRange(value, editor.selection, types2), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
5549
+ }
5550
+ }
5551
+ ptRange ? editorActor.send({
5552
+ type: "notify.selection",
5553
+ selection: ptRange
5554
+ }) : editorActor.send({
5555
+ type: "notify.selection",
5556
+ selection: null
5557
+ });
5558
+ }
5559
+ prevSelection = editor.selection;
5560
+ }, {
5561
+ onChange
5562
+ } = editor;
5563
+ return editor.onChange = () => {
5564
+ onChange(), editorActor.getSnapshot().matches({
5565
+ setup: "setting up"
5566
+ }) || emitPortableTextSelection();
5567
+ }, editor;
5568
+ };
5569
+ }
5570
+ const debug$3 = debugWithName("plugin:withSchemaTypes");
5571
+ function createWithSchemaTypes({
5572
+ editorActor,
5573
+ schemaTypes
5574
+ }) {
5575
+ return function(editor) {
5576
+ editor.isTextBlock = (value) => types.isPortableTextTextBlock(value) && value._type === schemaTypes.block.name, editor.isTextSpan = (value) => types.isPortableTextSpan(value) && value._type === schemaTypes.span.name, editor.isListBlock = (value) => types.isPortableTextListBlock(value) && value._type === schemaTypes.block.name, editor.isVoid = (element) => schemaTypes.block.name !== element._type && (schemaTypes.blockObjects.map((obj) => obj.name).includes(element._type) || schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type)), editor.isInline = (element) => schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type) && "__inline" in element && element.__inline === !0;
5577
+ const {
5578
+ normalizeNode
5579
+ } = editor;
5580
+ return editor.normalizeNode = (entry) => {
5581
+ const [node, path] = entry;
5582
+ if (node._type === void 0 && path.length === 2) {
5583
+ debug$3("Setting span type on text node without a type");
5584
+ const span = node, key = span._key || editorActor.getSnapshot().context.keyGenerator();
5585
+ editorActor.send({
5586
+ type: "normalizing"
5587
+ }), slate.Transforms.setNodes(editor, {
5588
+ ...span,
5589
+ _type: schemaTypes.span.name,
5590
+ _key: key
5591
+ }, {
5592
+ at: path
5593
+ }), editorActor.send({
5594
+ type: "done normalizing"
5595
+ });
5596
+ return;
5597
+ }
5598
+ if (node._key === void 0 && (path.length === 1 || path.length === 2)) {
5599
+ debug$3("Setting missing key on child node without a key");
5600
+ const key = editorActor.getSnapshot().context.keyGenerator();
5601
+ editorActor.send({
5602
+ type: "normalizing"
5603
+ }), slate.Transforms.setNodes(editor, {
5604
+ _key: key
5605
+ }, {
5606
+ at: path
5607
+ }), editorActor.send({
5608
+ type: "done normalizing"
5609
+ });
5610
+ return;
5611
+ }
5612
+ normalizeNode(entry);
5613
+ }, editor;
5614
+ };
5615
+ }
5616
+ function createWithUtils({
5617
+ editorActor,
5618
+ schemaTypes
5619
+ }) {
5620
+ return function(editor) {
5621
+ return editor.pteCreateTextBlock = (options) => toSlateValue([{
5622
+ _type: schemaTypes.block.name,
5623
+ _key: editorActor.getSnapshot().context.keyGenerator(),
5624
+ style: schemaTypes.styles[0].value || "normal",
5625
+ ...options.listItem ? {
5626
+ listItem: options.listItem
5627
+ } : {},
5628
+ ...options.level ? {
5629
+ level: options.level
5630
+ } : {},
5631
+ markDefs: [],
5632
+ children: [{
5633
+ _type: "span",
5634
+ _key: editorActor.getSnapshot().context.keyGenerator(),
5635
+ text: "",
5636
+ marks: options.decorators.filter((decorator) => schemaTypes.decorators.find(({
5637
+ value
5638
+ }) => value === decorator))
5639
+ }]
5640
+ }], {
5641
+ schemaTypes
5642
+ })[0], editor;
5643
+ };
5644
+ }
5645
+ const withPlugins = (editor, options) => {
5646
+ const e = editor, {
5647
+ editorActor
5648
+ } = options, schemaTypes = editorActor.getSnapshot().context.schema, operationToPatches = createOperationToPatches(schemaTypes), withObjectKeys = createWithObjectKeys(editorActor, schemaTypes), withSchemaTypes = createWithSchemaTypes({
5649
+ editorActor,
5650
+ schemaTypes
5651
+ }), withPatches = createWithPatches({
5652
+ editorActor,
5653
+ patchFunctions: operationToPatches,
5654
+ schemaTypes,
5655
+ subscriptions: options.subscriptions
5656
+ }), withMaxBlocks = createWithMaxBlocks(editorActor), withUndoRedo = createWithUndoRedo({
5657
+ editorActor,
5658
+ blockSchemaType: schemaTypes.block,
5659
+ subscriptions: options.subscriptions
5660
+ }), withPortableTextMarkModel = createWithPortableTextMarkModel(editorActor, schemaTypes), withPortableTextBlockStyle = createWithPortableTextBlockStyle(editorActor, schemaTypes), withPlaceholderBlock = createWithPlaceholderBlock(editorActor), withUtils = createWithUtils({
5661
+ editorActor,
5662
+ schemaTypes
5663
+ }), withPortableTextSelections = createWithPortableTextSelections(editorActor, schemaTypes);
5664
+ return createWithEventListeners(editorActor, options.subscriptions)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e)))))))))));
5665
+ }, debug$2 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
5666
+ function createSlateEditor(config) {
5667
+ const existingSlateEditor = slateEditors.get(config.editorActor);
5668
+ if (existingSlateEditor)
5669
+ return debug$2("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
5670
+ debug$2("Creating new Slate editor instance", config.editorActor.id);
5671
+ const unsubscriptions = [], subscriptions = [], instance = withPlugins(slateReact.withReact(slate.createEditor()), {
5672
+ editorActor: config.editorActor,
5673
+ subscriptions
5674
+ });
5675
+ KEY_TO_VALUE_ELEMENT.set(instance, {}), KEY_TO_SLATE_ELEMENT.set(instance, {});
5676
+ for (const subscription of subscriptions)
5677
+ unsubscriptions.push(subscription());
5678
+ const initialValue = [instance.pteCreateTextBlock({
5679
+ decorators: []
5680
+ })], slateEditor = {
5681
+ instance,
5682
+ initialValue
5683
+ };
5684
+ return slateEditors.set(config.editorActor, slateEditor), slateEditor;
5546
5685
  }
5547
5686
  const keyIs = {
5548
5687
  lineBreak: (event) => event.key === "Enter" && event.shiftKey
@@ -5666,29 +5805,25 @@ const editorMachine = xstate.setup({
5666
5805
  if (eventBehaviors.length === 0) {
5667
5806
  if (defaultActionCallback) {
5668
5807
  withApplyingBehaviorActions(event.editor, () => {
5669
- slate.Editor.withoutNormalizing(event.editor, () => {
5670
- try {
5671
- defaultActionCallback();
5672
- } catch (error) {
5673
- console.error(new Error(`Performing action "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5674
- }
5675
- });
5808
+ try {
5809
+ defaultActionCallback();
5810
+ } catch (error) {
5811
+ console.error(new Error(`Performing action "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5812
+ }
5676
5813
  });
5677
5814
  return;
5678
5815
  }
5679
5816
  if (!defaultAction)
5680
5817
  return;
5681
5818
  withApplyingBehaviorActions(event.editor, () => {
5682
- slate.Editor.withoutNormalizing(event.editor, () => {
5683
- try {
5684
- performAction({
5685
- context,
5686
- action: defaultAction
5687
- });
5688
- } catch (error) {
5689
- console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5690
- }
5691
- });
5819
+ try {
5820
+ performAction({
5821
+ context,
5822
+ action: defaultAction
5823
+ });
5824
+ } catch (error) {
5825
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5826
+ }
5692
5827
  }), event.editor.onChange();
5693
5828
  return;
5694
5829
  }
@@ -5711,36 +5846,34 @@ const editorMachine = xstate.setup({
5711
5846
  event: event.behaviorEvent
5712
5847
  }, shouldRun));
5713
5848
  for (const actionIntends of actionIntendSets)
5714
- behaviorOverwritten = behaviorOverwritten || actionIntends.length > 0 && actionIntends.some((actionIntend) => actionIntend.type !== "effect"), withApplyingBehaviorActions(event.editor, () => {
5715
- slate.Editor.withoutNormalizing(event.editor, () => {
5716
- for (const actionIntend of actionIntends) {
5717
- if (actionIntend.type === "raise") {
5718
- behavior_core.isCustomBehaviorEvent(actionIntend.event) ? enqueue.raise({
5719
- type: "custom behavior event",
5720
- behaviorEvent: actionIntend.event,
5721
- editor: event.editor
5722
- }) : enqueue.raise({
5723
- type: "behavior event",
5724
- behaviorEvent: actionIntend.event,
5725
- editor: event.editor
5726
- });
5727
- continue;
5728
- }
5729
- const action = {
5730
- ...actionIntend,
5849
+ behaviorOverwritten = behaviorOverwritten || actionIntends.length > 0 && actionIntends.some((actionIntend) => actionIntend.type !== "effect"), withApplyingBehaviorActionIntendSet(event.editor, () => {
5850
+ for (const actionIntend of actionIntends) {
5851
+ if (actionIntend.type === "raise") {
5852
+ behavior_core.isCustomBehaviorEvent(actionIntend.event) ? enqueue.raise({
5853
+ type: "custom behavior event",
5854
+ behaviorEvent: actionIntend.event,
5731
5855
  editor: event.editor
5732
- };
5733
- try {
5734
- performAction({
5735
- context,
5736
- action
5737
- });
5738
- } catch (error) {
5739
- console.error(new Error(`Performing action "${action.type}" as a result of "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5740
- break;
5741
- }
5856
+ }) : enqueue.raise({
5857
+ type: "behavior event",
5858
+ behaviorEvent: actionIntend.event,
5859
+ editor: event.editor
5860
+ });
5861
+ continue;
5742
5862
  }
5743
- });
5863
+ const action = {
5864
+ ...actionIntend,
5865
+ editor: event.editor
5866
+ };
5867
+ try {
5868
+ performAction({
5869
+ context,
5870
+ action
5871
+ });
5872
+ } catch (error) {
5873
+ console.error(new Error(`Performing action "${action.type}" as a result of "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5874
+ break;
5875
+ }
5876
+ }
5744
5877
  }), event.editor.onChange();
5745
5878
  if (behaviorOverwritten) {
5746
5879
  event.nativeEvent?.preventDefault();
@@ -5750,29 +5883,25 @@ const editorMachine = xstate.setup({
5750
5883
  if (!behaviorOverwritten) {
5751
5884
  if (defaultActionCallback) {
5752
5885
  withApplyingBehaviorActions(event.editor, () => {
5753
- slate.Editor.withoutNormalizing(event.editor, () => {
5754
- try {
5755
- defaultActionCallback();
5756
- } catch (error) {
5757
- console.error(new Error(`Performing "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5758
- }
5759
- });
5886
+ try {
5887
+ defaultActionCallback();
5888
+ } catch (error) {
5889
+ console.error(new Error(`Performing "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5890
+ }
5760
5891
  });
5761
5892
  return;
5762
5893
  }
5763
5894
  if (!defaultAction)
5764
5895
  return;
5765
5896
  withApplyingBehaviorActions(event.editor, () => {
5766
- slate.Editor.withoutNormalizing(event.editor, () => {
5767
- try {
5768
- performAction({
5769
- context,
5770
- action: defaultAction
5771
- });
5772
- } catch (error) {
5773
- console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5774
- }
5775
- });
5897
+ try {
5898
+ performAction({
5899
+ context,
5900
+ action: defaultAction
5901
+ });
5902
+ } catch (error) {
5903
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.behaviorEvent.type}" failed due to: ${error.message}`));
5904
+ }
5776
5905
  }), event.editor.onChange();
5777
5906
  }
5778
5907
  })
@@ -5996,6 +6125,11 @@ const editorMachine = xstate.setup({
5996
6125
  event
5997
6126
  }) => event)
5998
6127
  },
6128
+ "history.*": {
6129
+ actions: xstate.emit(({
6130
+ event
6131
+ }) => event)
6132
+ },
5999
6133
  "insert.*": {
6000
6134
  actions: xstate.emit(({
6001
6135
  event
@@ -6141,25 +6275,6 @@ function getEditorSnapshot({
6141
6275
  }
6142
6276
  };
6143
6277
  }
6144
- const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
6145
- let table;
6146
- return () => {
6147
- if (table)
6148
- return table;
6149
- table = [];
6150
- for (let i = 0; i < 256; ++i)
6151
- table[i] = (i + 256).toString(16).slice(1);
6152
- return table;
6153
- };
6154
- })();
6155
- function whatwgRNG(length = 16) {
6156
- const rnds8 = new Uint8Array(length);
6157
- return getRandomValues__default.default(rnds8), rnds8;
6158
- }
6159
- function randomKey(length) {
6160
- const table = getByteHexTable();
6161
- return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
6162
- }
6163
6278
  function createEditor(config) {
6164
6279
  const editorActor = xstate.createActor(editorMachine, {
6165
6280
  input: editorConfigToMachineInput(config)