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