@portabletext/editor 1.31.2 → 1.32.0

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