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