@portabletext/editor 1.0.3 → 1.0.4

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.
package/lib/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var jsxRuntime = require("react/jsx-runtime"), isEqual = require("lodash/isEqual.js"), noop = require("lodash/noop.js"), react = require("react"), slate = require("slate"), slateReact = require("slate-react"), debug$l = require("debug"), types$1 = require("@sanity/types"), styledComponents = require("styled-components"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), schema = require("@sanity/schema"), patchEvent = require("@portabletext/patches/patch-event"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), apply$1 = require("@portabletext/patches/apply"), flatten = require("lodash/flatten.js"), isHotkeyEsm = require("is-hotkey-esm"), blockTools = require("@sanity/block-tools"), isPlainObject = require("lodash/isPlainObject.js"), throttle = require("lodash/throttle.js"), content = require("@sanity/util/content"), debounce = require("lodash/debounce.js"), types = require("@portabletext/patches/types");
3
+ var jsxRuntime = require("react/jsx-runtime"), isEqual = require("lodash/isEqual.js"), noop = require("lodash/noop.js"), react = require("react"), slate = require("slate"), slateReact = require("slate-react"), debug$l = require("debug"), types = require("@sanity/types"), styledComponents = require("styled-components"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), schema = require("@sanity/schema"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), isObject = require("lodash/isObject.js"), isString = require("lodash/isString.js"), findIndex = require("lodash/findIndex.js"), clone = require("lodash/clone.js"), omit = require("lodash/omit.js"), flatten$1 = require("lodash/flatten.js"), isHotkeyEsm = require("is-hotkey-esm"), blockTools = require("@sanity/block-tools"), isPlainObject = require("lodash/isPlainObject.js"), throttle = require("lodash/throttle.js"), content = require("@sanity/util/content"), debounce = require("lodash/debounce.js");
4
4
  function _interopDefaultCompat(e) {
5
5
  return e && typeof e == "object" && "default" in e ? e : { default: e };
6
6
  }
7
- var isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$l), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), throttle__default = /* @__PURE__ */ _interopDefaultCompat(throttle), debounce__default = /* @__PURE__ */ _interopDefaultCompat(debounce);
7
+ var isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$l), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), isObject__default = /* @__PURE__ */ _interopDefaultCompat(isObject), isString__default = /* @__PURE__ */ _interopDefaultCompat(isString), findIndex__default = /* @__PURE__ */ _interopDefaultCompat(findIndex), clone__default = /* @__PURE__ */ _interopDefaultCompat(clone), omit__default = /* @__PURE__ */ _interopDefaultCompat(omit), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten$1), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), throttle__default = /* @__PURE__ */ _interopDefaultCompat(throttle), debounce__default = /* @__PURE__ */ _interopDefaultCompat(debounce);
8
8
  const rootName = "sanity-pte:";
9
9
  debug__default.default(rootName);
10
10
  function debugWithName(name) {
@@ -31,7 +31,7 @@ function createArrayedPath(point, editor) {
31
31
  const [block, blockPath] = Array.from(
32
32
  slate.Editor.nodes(editor, {
33
33
  at: [],
34
- match: (n) => types$1.isKeySegment(point.path[0]) && n._key === point.path[0]._key
34
+ match: (n) => types.isKeySegment(point.path[0]) && n._key === point.path[0]._key
35
35
  })
36
36
  )[0] || [void 0, void 0];
37
37
  if (!block || !slate.Element.isElement(block))
@@ -701,1339 +701,1633 @@ function compileType(rawType) {
701
701
  types: [rawType]
702
702
  }).get(rawType.name);
703
703
  }
704
- const debug$j = debugWithName("operationToPatches");
705
- debug$j.enabled = !1;
706
- function createOperationToPatches(types2) {
707
- const textBlockName = types2.block.name;
708
- function insertTextPatch(editor, operation, beforeValue) {
709
- debug$j.enabled && debug$j("Operation", JSON.stringify(operation, null, 2));
710
- const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
711
- if (!block)
712
- throw new Error("Could not find block");
713
- const textChild = editor.isTextBlock(block) && editor.isTextSpan(block.children[operation.path[1]]) && block.children[operation.path[1]];
714
- if (!textChild)
715
- throw new Error("Could not find child");
716
- const path = [{ _key: block._key }, "children", { _key: textChild._key }, "text"], prevBlock = beforeValue[operation.path[0]], prevChild = editor.isTextBlock(prevBlock) && prevBlock.children[operation.path[1]], prevText = editor.isTextSpan(prevChild) ? prevChild.text : "", patch = patchEvent.diffMatchPatch(prevText, textChild.text, path);
717
- return patch.value.length ? [patch] : [];
718
- }
719
- function removeTextPatch(editor, operation, beforeValue) {
720
- const block = editor && editor.children[operation.path[0]];
721
- if (!block)
722
- throw new Error("Could not find block");
723
- const child = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, textChild = editor.isTextSpan(child) ? child : void 0;
724
- if (child && !textChild)
725
- throw new Error("Expected span");
726
- if (!textChild)
727
- throw new Error("Could not find child");
728
- const path = [{ _key: block._key }, "children", { _key: textChild._key }, "text"], beforeBlock = beforeValue[operation.path[0]], prevTextChild = editor.isTextBlock(beforeBlock) && beforeBlock.children[operation.path[1]], prevText = editor.isTextSpan(prevTextChild) && prevTextChild.text, patch = patchEvent.diffMatchPatch(prevText || "", textChild.text, path);
729
- return patch.value ? [patch] : [];
730
- }
731
- function setNodePatch(editor, operation) {
732
- if (operation.path.length === 1) {
733
- const block = editor.children[operation.path[0]];
734
- if (typeof block._key != "string")
735
- throw new Error("Expected block to have a _key");
736
- const setNode = omitBy__default.default(
737
- { ...editor.children[operation.path[0]], ...operation.newProperties },
738
- isUndefined__default.default
739
- );
740
- return [patchEvent.set(fromSlateValue([setNode], textBlockName)[0], [{ _key: block._key }])];
741
- } else if (operation.path.length === 2) {
742
- const block = editor.children[operation.path[0]];
743
- if (editor.isTextBlock(block)) {
744
- const child = block.children[operation.path[1]];
745
- if (child) {
746
- const blockKey = block._key, childKey = child._key, patches = [], keys = Object.keys(operation.newProperties);
747
- return keys.forEach((keyName) => {
748
- if (keys.length === 1 && keyName === "_key") {
749
- const val = get__default.default(operation.newProperties, keyName);
750
- patches.push(
751
- patchEvent.set(val, [{ _key: blockKey }, "children", block.children.indexOf(child), keyName])
752
- );
753
- } else {
754
- const val = get__default.default(operation.newProperties, keyName);
755
- patches.push(patchEvent.set(val, [{ _key: blockKey }, "children", { _key: childKey }, keyName]));
756
- }
757
- }), patches;
758
- }
759
- throw new Error("Could not find a valid child");
760
- }
761
- throw new Error("Could not find a valid block");
762
- } else
763
- throw new Error(`Unexpected path encountered: ${JSON.stringify(operation.path)}`);
704
+ function isHighSurrogate(char) {
705
+ const charCode = char.charCodeAt(0);
706
+ return charCode >= 55296 && charCode <= 56319;
707
+ }
708
+ function isLowSurrogate(char) {
709
+ const charCode = char.charCodeAt(0);
710
+ return charCode >= 56320 && charCode <= 57343;
711
+ }
712
+ function cloneDiff(diff2) {
713
+ const [type, patch] = diff2;
714
+ return [type, patch];
715
+ }
716
+ function getCommonOverlap(textA, textB) {
717
+ let text1 = textA, text2 = textB;
718
+ const text1Length = text1.length, text2Length = text2.length;
719
+ if (text1Length === 0 || text2Length === 0)
720
+ return 0;
721
+ text1Length > text2Length ? text1 = text1.substring(text1Length - text2Length) : text1Length < text2Length && (text2 = text2.substring(0, text1Length));
722
+ const textLength = Math.min(text1Length, text2Length);
723
+ if (text1 === text2)
724
+ return textLength;
725
+ let best = 0, length = 1;
726
+ for (let found = 0; found !== -1; ) {
727
+ const pattern = text1.substring(textLength - length);
728
+ if (found = text2.indexOf(pattern), found === -1)
729
+ return best;
730
+ length += found, (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) && (best = length, length++);
764
731
  }
765
- function insertNodePatch(editor, operation, beforeValue) {
766
- const block = beforeValue[operation.path[0]], isTextBlock = editor.isTextBlock(block);
767
- if (operation.path.length === 1) {
768
- const position = operation.path[0] === 0 ? "before" : "after", beforeBlock = beforeValue[operation.path[0] - 1], targetKey = operation.path[0] === 0 ? block == null ? void 0 : block._key : beforeBlock == null ? void 0 : beforeBlock._key;
769
- return targetKey ? [
770
- patchEvent.insert([fromSlateValue([operation.node], textBlockName)[0]], position, [
771
- { _key: targetKey }
772
- ])
773
- ] : [
774
- patchEvent.setIfMissing(beforeValue, []),
775
- patchEvent.insert([fromSlateValue([operation.node], textBlockName)[0]], "before", [
776
- operation.path[0]
777
- ])
778
- ];
779
- } else if (isTextBlock && operation.path.length === 2 && editor.children[operation.path[0]]) {
780
- const position = block.children.length === 0 || !block.children[operation.path[1] - 1] ? "before" : "after", node = { ...operation.node };
781
- !node._type && slate.Text.isText(node) && (node._type = "span", node.marks = []);
782
- const child = fromSlateValue(
783
- [
784
- {
785
- _key: "bogus",
786
- _type: textBlockName,
787
- children: [node]
788
- }
789
- ],
790
- textBlockName
791
- )[0].children[0];
792
- return [
793
- patchEvent.insert([child], position, [
794
- { _key: block._key },
795
- "children",
796
- block.children.length <= 1 || !block.children[operation.path[1] - 1] ? 0 : { _key: block.children[operation.path[1] - 1]._key }
797
- ])
798
- ];
732
+ return best;
733
+ }
734
+ function getCommonPrefix(text1, text2) {
735
+ if (!text1 || !text2 || text1[0] !== text2[0])
736
+ return 0;
737
+ let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerStart = 0;
738
+ for (; pointerMin < pointerMid; )
739
+ text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid) ? (pointerMin = pointerMid, pointerStart = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
740
+ return pointerMid;
741
+ }
742
+ function getCommonSuffix(text1, text2) {
743
+ if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1])
744
+ return 0;
745
+ let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerEnd = 0;
746
+ for (; pointerMin < pointerMid; )
747
+ text1.substring(text1.length - pointerMid, text1.length - pointerEnd) === text2.substring(text2.length - pointerMid, text2.length - pointerEnd) ? (pointerMin = pointerMid, pointerEnd = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
748
+ return pointerMid;
749
+ }
750
+ function cleanupSemantic(rawDiffs) {
751
+ let diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
752
+ const equalities = [];
753
+ let equalitiesLength = 0, lastEquality = null, pointer = 0, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0;
754
+ for (; pointer < diffs.length; )
755
+ diffs[pointer][0] === DIFF_EQUAL ? (equalities[equalitiesLength++] = pointer, lengthInsertions1 = lengthInsertions2, lengthDeletions1 = lengthDeletions2, lengthInsertions2 = 0, lengthDeletions2 = 0, lastEquality = diffs[pointer][1]) : (diffs[pointer][0] === DIFF_INSERT ? lengthInsertions2 += diffs[pointer][1].length : lengthDeletions2 += diffs[pointer][1].length, lastEquality && lastEquality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastEquality.length <= Math.max(lengthInsertions2, lengthDeletions2) && (diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]), diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT, equalitiesLength--, equalitiesLength--, pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0, lastEquality = null, hasChanges = !0)), pointer++;
756
+ for (hasChanges && (diffs = cleanupMerge(diffs)), diffs = cleanupSemanticLossless(diffs), pointer = 1; pointer < diffs.length; ) {
757
+ if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
758
+ const deletion = diffs[pointer - 1][1], insertion = diffs[pointer][1], overlapLength1 = getCommonOverlap(deletion, insertion), overlapLength2 = getCommonOverlap(insertion, deletion);
759
+ overlapLength1 >= overlapLength2 ? (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) && (diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]), diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1), diffs[pointer + 1][1] = insertion.substring(overlapLength1), pointer++) : (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) && (diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]), diffs[pointer - 1][0] = DIFF_INSERT, diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2), diffs[pointer + 1][0] = DIFF_DELETE, diffs[pointer + 1][1] = deletion.substring(overlapLength2), pointer++), pointer++;
799
760
  }
800
- return debug$j("Something was inserted into a void block. Not producing editor patches."), [];
761
+ pointer++;
801
762
  }
802
- function splitNodePatch(editor, operation, beforeValue) {
803
- const patches = [], splitBlock = editor.children[operation.path[0]];
804
- if (!editor.isTextBlock(splitBlock))
805
- throw new Error(
806
- `Block with path ${JSON.stringify(
807
- operation.path[0]
808
- )} is not a text block and can't be split`
809
- );
810
- if (operation.path.length === 1) {
811
- const oldBlock = beforeValue[operation.path[0]];
812
- if (editor.isTextBlock(oldBlock)) {
813
- const targetValue = fromSlateValue(
814
- [editor.children[operation.path[0] + 1]],
815
- textBlockName
816
- )[0];
817
- targetValue && (patches.push(patchEvent.insert([targetValue], "after", [{ _key: splitBlock._key }])), oldBlock.children.slice(operation.position).forEach((span) => {
818
- const path = [{ _key: oldBlock._key }, "children", { _key: span._key }];
819
- patches.push(patchEvent.unset(path));
820
- }));
763
+ return diffs;
764
+ }
765
+ const nonAlphaNumericRegex = /[^a-zA-Z0-9]/, whitespaceRegex = /\s/, linebreakRegex = /[\r\n]/, blanklineEndRegex = /\n\r?\n$/, blanklineStartRegex = /^\r?\n\r?\n/;
766
+ function cleanupSemanticLossless(rawDiffs) {
767
+ const diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
768
+ function diffCleanupSemanticScore(one, two) {
769
+ if (!one || !two)
770
+ return 6;
771
+ const char1 = one.charAt(one.length - 1), char2 = two.charAt(0), nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex), nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex), whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex), whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex), lineBreak1 = whitespace1 && char1.match(linebreakRegex), lineBreak2 = whitespace2 && char2.match(linebreakRegex), blankLine1 = lineBreak1 && one.match(blanklineEndRegex), blankLine2 = lineBreak2 && two.match(blanklineStartRegex);
772
+ return blankLine1 || blankLine2 ? 5 : lineBreak1 || lineBreak2 ? 4 : nonAlphaNumeric1 && !whitespace1 && whitespace2 ? 3 : whitespace1 || whitespace2 ? 2 : nonAlphaNumeric1 || nonAlphaNumeric2 ? 1 : 0;
773
+ }
774
+ let pointer = 1;
775
+ for (; pointer < diffs.length - 1; ) {
776
+ if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
777
+ let equality1 = diffs[pointer - 1][1], edit = diffs[pointer][1], equality2 = diffs[pointer + 1][1];
778
+ const commonOffset = getCommonSuffix(equality1, edit);
779
+ if (commonOffset) {
780
+ const commonString = edit.substring(edit.length - commonOffset);
781
+ equality1 = equality1.substring(0, equality1.length - commonOffset), edit = commonString + edit.substring(0, edit.length - commonOffset), equality2 = commonString + equality2;
821
782
  }
822
- return patches;
823
- }
824
- if (operation.path.length === 2) {
825
- const splitSpan = splitBlock.children[operation.path[1]];
826
- if (editor.isTextSpan(splitSpan)) {
827
- const targetSpans = fromSlateValue(
828
- [
829
- {
830
- ...splitBlock,
831
- children: splitBlock.children.slice(operation.path[1] + 1, operation.path[1] + 2)
832
- }
833
- ],
834
- textBlockName
835
- )[0].children;
836
- patches.push(
837
- patchEvent.insert(targetSpans, "after", [
838
- { _key: splitBlock._key },
839
- "children",
840
- { _key: splitSpan._key }
841
- ])
842
- ), patches.push(
843
- patchEvent.set(splitSpan.text, [
844
- { _key: splitBlock._key },
845
- "children",
846
- { _key: splitSpan._key },
847
- "text"
848
- ])
849
- );
783
+ let bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2, bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
784
+ for (; edit.charAt(0) === equality2.charAt(0); ) {
785
+ equality1 += edit.charAt(0), edit = edit.substring(1) + equality2.charAt(0), equality2 = equality2.substring(1);
786
+ const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
787
+ score >= bestScore && (bestScore = score, bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2);
850
788
  }
851
- return patches;
852
- }
853
- return patches;
854
- }
855
- function removeNodePatch(editor, operation, beforeValue) {
856
- const block = beforeValue[operation.path[0]];
857
- if (operation.path.length === 1) {
858
- if (block && block._key)
859
- return [patchEvent.unset([{ _key: block._key }])];
860
- throw new Error("Block not found");
861
- } else if (editor.isTextBlock(block) && operation.path.length === 2) {
862
- const spanToRemove = editor.isTextBlock(block) && block.children && block.children[operation.path[1]];
863
- return spanToRemove ? [patchEvent.unset([{ _key: block._key }, "children", { _key: spanToRemove._key }])] : (debug$j("Span not found in editor trying to remove node"), []);
864
- } else
865
- return debug$j("Not creating patch inside object block"), [];
866
- }
867
- function mergeNodePatch(editor, operation, beforeValue) {
868
- const patches = [], block = beforeValue[operation.path[0]], targetBlock = editor.children[operation.path[0]];
869
- if (operation.path.length === 1)
870
- if (block != null && block._key) {
871
- const newBlock = fromSlateValue([editor.children[operation.path[0] - 1]], textBlockName)[0];
872
- patches.push(patchEvent.set(newBlock, [{ _key: newBlock._key }])), patches.push(patchEvent.unset([{ _key: block._key }]));
873
- } else
874
- throw new Error("Target key not found!");
875
- else if (operation.path.length === 2 && editor.isTextBlock(targetBlock)) {
876
- const mergedSpan = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, targetSpan = targetBlock.children[operation.path[1] - 1];
877
- editor.isTextSpan(targetSpan) && (patches.push(
878
- patchEvent.set(targetSpan.text, [{ _key: block._key }, "children", { _key: targetSpan._key }, "text"])
879
- ), mergedSpan && patches.push(patchEvent.unset([{ _key: block._key }, "children", { _key: mergedSpan._key }])));
880
- } else
881
- debug$j("Void nodes can't be merged, not creating any patches");
882
- return patches;
883
- }
884
- function moveNodePatch(editor, operation, beforeValue) {
885
- const patches = [], block = beforeValue[operation.path[0]], targetBlock = beforeValue[operation.newPath[0]];
886
- if (operation.path.length === 1) {
887
- const position = operation.path[0] > operation.newPath[0] ? "before" : "after";
888
- patches.push(patchEvent.unset([{ _key: block._key }])), patches.push(
889
- patchEvent.insert([fromSlateValue([block], textBlockName)[0]], position, [{ _key: targetBlock._key }])
890
- );
891
- } else if (operation.path.length === 2 && editor.isTextBlock(block) && editor.isTextBlock(targetBlock)) {
892
- const child = block.children[operation.path[1]], targetChild = targetBlock.children[operation.newPath[1]], position = operation.newPath[1] === targetBlock.children.length ? "after" : "before", childToInsert = fromSlateValue([block], textBlockName)[0].children[operation.path[1]];
893
- patches.push(patchEvent.unset([{ _key: block._key }, "children", { _key: child._key }])), patches.push(
894
- patchEvent.insert([childToInsert], position, [
895
- { _key: targetBlock._key },
896
- "children",
897
- { _key: targetChild._key }
898
- ])
899
- );
789
+ diffs[pointer - 1][1] !== bestEquality1 && (bestEquality1 ? diffs[pointer - 1][1] = bestEquality1 : (diffs.splice(pointer - 1, 1), pointer--), diffs[pointer][1] = bestEdit, bestEquality2 ? diffs[pointer + 1][1] = bestEquality2 : (diffs.splice(pointer + 1, 1), pointer--));
900
790
  }
901
- return patches;
791
+ pointer++;
902
792
  }
903
- return {
904
- insertNodePatch,
905
- insertTextPatch,
906
- mergeNodePatch,
907
- moveNodePatch,
908
- removeNodePatch,
909
- removeTextPatch,
910
- setNodePatch,
911
- splitNodePatch
912
- };
793
+ return diffs;
913
794
  }
914
- const debug$i = debugWithName("API:editable");
915
- function createWithEditableAPI(portableTextEditor, types2, keyGenerator) {
916
- return function(editor) {
917
- return portableTextEditor.setEditable({
918
- focus: () => {
919
- slateReact.ReactEditor.focus(editor);
920
- },
921
- blur: () => {
922
- slateReact.ReactEditor.blur(editor);
923
- },
924
- toggleMark: (mark) => {
925
- editor.pteToggleMark(mark);
926
- },
927
- toggleList: (listStyle) => {
928
- editor.pteToggleListItem(listStyle);
929
- },
930
- toggleBlockStyle: (blockStyle) => {
931
- editor.pteToggleBlockStyle(blockStyle);
932
- },
933
- isMarkActive: (mark) => {
934
- try {
935
- return editor.pteIsMarkActive(mark);
936
- } catch (err) {
937
- return console.warn(err), !1;
795
+ function cleanupMerge(rawDiffs) {
796
+ let diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
797
+ diffs.push([DIFF_EQUAL, ""]);
798
+ let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "", commonlength;
799
+ for (; pointer < diffs.length; )
800
+ switch (diffs[pointer][0]) {
801
+ case DIFF_INSERT:
802
+ countInsert++, textInsert += diffs[pointer][1], pointer++;
803
+ break;
804
+ case DIFF_DELETE:
805
+ countDelete++, textDelete += diffs[pointer][1], pointer++;
806
+ break;
807
+ case DIFF_EQUAL:
808
+ countDelete + countInsert > 1 ? (countDelete !== 0 && countInsert !== 0 && (commonlength = getCommonPrefix(textInsert, textDelete), commonlength !== 0 && (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL ? diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength) : (diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]), pointer++), textInsert = textInsert.substring(commonlength), textDelete = textDelete.substring(commonlength)), commonlength = getCommonSuffix(textInsert, textDelete), commonlength !== 0 && (diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1], textInsert = textInsert.substring(0, textInsert.length - commonlength), textDelete = textDelete.substring(0, textDelete.length - commonlength))), pointer -= countDelete + countInsert, diffs.splice(pointer, countDelete + countInsert), textDelete.length && (diffs.splice(pointer, 0, [DIFF_DELETE, textDelete]), pointer++), textInsert.length && (diffs.splice(pointer, 0, [DIFF_INSERT, textInsert]), pointer++), pointer++) : pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL ? (diffs[pointer - 1][1] += diffs[pointer][1], diffs.splice(pointer, 1)) : pointer++, countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
809
+ break;
810
+ default:
811
+ throw new Error("Unknown diff operation");
812
+ }
813
+ diffs[diffs.length - 1][1] === "" && diffs.pop();
814
+ let hasChanges = !1;
815
+ for (pointer = 1; pointer < diffs.length - 1; )
816
+ diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL && (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1] ? (diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length), diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1], diffs.splice(pointer - 1, 1), hasChanges = !0) : diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1] && (diffs[pointer - 1][1] += diffs[pointer + 1][1], diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1], diffs.splice(pointer + 1, 1), hasChanges = !0)), pointer++;
817
+ return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
818
+ }
819
+ function trueCount() {
820
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)
821
+ args[_key] = arguments[_key];
822
+ return args.reduce((n, bool) => n + (bool ? 1 : 0), 0);
823
+ }
824
+ function cleanupEfficiency(rawDiffs) {
825
+ let editCost = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 4, diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
826
+ const equalities = [];
827
+ let equalitiesLength = 0, lastEquality = null, pointer = 0, preIns = !1, preDel = !1, postIns = !1, postDel = !1;
828
+ for (; pointer < diffs.length; )
829
+ diffs[pointer][0] === DIFF_EQUAL ? (diffs[pointer][1].length < editCost && (postIns || postDel) ? (equalities[equalitiesLength++] = pointer, preIns = postIns, preDel = postDel, lastEquality = diffs[pointer][1]) : (equalitiesLength = 0, lastEquality = null), postIns = !1, postDel = !1) : (diffs[pointer][0] === DIFF_DELETE ? postDel = !0 : postIns = !0, lastEquality && (preIns && preDel && postIns && postDel || lastEquality.length < editCost / 2 && trueCount(preIns, preDel, postIns, postDel) === 3) && (diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]), diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT, equalitiesLength--, lastEquality = null, preIns && preDel ? (postIns = !0, postDel = !0, equalitiesLength = 0) : (equalitiesLength--, pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1, postIns = !1, postDel = !1), hasChanges = !0)), pointer++;
830
+ return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
831
+ }
832
+ function bisect(text1, text2, deadline) {
833
+ const text1Length = text1.length, text2Length = text2.length, maxD = Math.ceil((text1Length + text2Length) / 2), vOffset = maxD, vLength = 2 * maxD, v1 = new Array(vLength), v2 = new Array(vLength);
834
+ for (let x = 0; x < vLength; x++)
835
+ v1[x] = -1, v2[x] = -1;
836
+ v1[vOffset + 1] = 0, v2[vOffset + 1] = 0;
837
+ const delta = text1Length - text2Length, front = delta % 2 !== 0;
838
+ let k1start = 0, k1end = 0, k2start = 0, k2end = 0;
839
+ for (let d = 0; d < maxD && !(Date.now() > deadline); d++) {
840
+ for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
841
+ const k1Offset = vOffset + k1;
842
+ let x1;
843
+ k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1] ? x1 = v1[k1Offset + 1] : x1 = v1[k1Offset - 1] + 1;
844
+ let y1 = x1 - k1;
845
+ for (; x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1); )
846
+ x1++, y1++;
847
+ if (v1[k1Offset] = x1, x1 > text1Length)
848
+ k1end += 2;
849
+ else if (y1 > text2Length)
850
+ k1start += 2;
851
+ else if (front) {
852
+ const k2Offset = vOffset + delta - k1;
853
+ if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
854
+ const x2 = text1Length - v2[k2Offset];
855
+ if (x1 >= x2)
856
+ return bisectSplit(text1, text2, x1, y1, deadline);
938
857
  }
939
- },
940
- marks: () => ({
941
- ...slate.Editor.marks(editor) || {}
942
- }).marks || [],
943
- undo: () => editor.undo(),
944
- redo: () => editor.redo(),
945
- select: (selection) => {
946
- const slateSelection = toSlateRange(selection, editor);
947
- slateSelection ? slate.Transforms.select(editor, slateSelection) : slate.Transforms.deselect(editor), editor.onChange();
948
- },
949
- focusBlock: () => {
950
- if (editor.selection) {
951
- const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
952
- if (block)
953
- return fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
858
+ }
859
+ }
860
+ for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
861
+ const k2Offset = vOffset + k2;
862
+ let x2;
863
+ k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1] ? x2 = v2[k2Offset + 1] : x2 = v2[k2Offset - 1] + 1;
864
+ let y2 = x2 - k2;
865
+ for (; x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1); )
866
+ x2++, y2++;
867
+ if (v2[k2Offset] = x2, x2 > text1Length)
868
+ k2end += 2;
869
+ else if (y2 > text2Length)
870
+ k2start += 2;
871
+ else if (!front) {
872
+ const k1Offset = vOffset + delta - k2;
873
+ if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
874
+ const x1 = v1[k1Offset], y1 = vOffset + x1 - k1Offset;
875
+ if (x2 = text1Length - x2, x1 >= x2)
876
+ return bisectSplit(text1, text2, x1, y1, deadline);
954
877
  }
955
- },
956
- focusChild: () => {
957
- if (editor.selection) {
958
- const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
959
- if (block && editor.isTextBlock(block))
960
- return fromSlateValue(
961
- [block],
962
- types2.block.name,
963
- KEY_TO_VALUE_ELEMENT.get(editor)
964
- )[0].children[editor.selection.focus.path[1]];
878
+ }
879
+ }
880
+ }
881
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
882
+ }
883
+ function bisectSplit(text1, text2, x, y, deadline) {
884
+ const text1a = text1.substring(0, x), text2a = text2.substring(0, y), text1b = text1.substring(x), text2b = text2.substring(y), diffs = doDiff(text1a, text2a, {
885
+ checkLines: !1,
886
+ deadline
887
+ }), diffsb = doDiff(text1b, text2b, {
888
+ checkLines: !1,
889
+ deadline
890
+ });
891
+ return diffs.concat(diffsb);
892
+ }
893
+ function findHalfMatch(text1, text2) {
894
+ if ((arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1) <= 0)
895
+ return null;
896
+ const longText = text1.length > text2.length ? text1 : text2, shortText = text1.length > text2.length ? text2 : text1;
897
+ if (longText.length < 4 || shortText.length * 2 < longText.length)
898
+ return null;
899
+ const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4)), halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));
900
+ let halfMatch;
901
+ if (halfMatch1 && halfMatch2)
902
+ halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;
903
+ else {
904
+ if (!halfMatch1 && !halfMatch2)
905
+ return null;
906
+ halfMatch2 ? halfMatch1 || (halfMatch = halfMatch2) : halfMatch = halfMatch1;
907
+ }
908
+ if (!halfMatch)
909
+ throw new Error("Unable to find a half match.");
910
+ let text1A, text1B, text2A, text2B;
911
+ text1.length > text2.length ? (text1A = halfMatch[0], text1B = halfMatch[1], text2A = halfMatch[2], text2B = halfMatch[3]) : (text2A = halfMatch[0], text2B = halfMatch[1], text1A = halfMatch[2], text1B = halfMatch[3]);
912
+ const midCommon = halfMatch[4];
913
+ return [text1A, text1B, text2A, text2B, midCommon];
914
+ }
915
+ function halfMatchI(longText, shortText, i) {
916
+ const seed = longText.slice(i, i + Math.floor(longText.length / 4));
917
+ let j = -1, bestCommon = "", bestLongTextA, bestLongTextB, bestShortTextA, bestShortTextB;
918
+ for (; (j = shortText.indexOf(seed, j + 1)) !== -1; ) {
919
+ const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j)), suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));
920
+ bestCommon.length < suffixLength + prefixLength && (bestCommon = shortText.slice(j - suffixLength, j) + shortText.slice(j, j + prefixLength), bestLongTextA = longText.slice(0, i - suffixLength), bestLongTextB = longText.slice(i + prefixLength), bestShortTextA = shortText.slice(0, j - suffixLength), bestShortTextB = shortText.slice(j + prefixLength));
921
+ }
922
+ return bestCommon.length * 2 >= longText.length ? [bestLongTextA || "", bestLongTextB || "", bestShortTextA || "", bestShortTextB || "", bestCommon || ""] : null;
923
+ }
924
+ function charsToLines(diffs, lineArray) {
925
+ for (let x = 0; x < diffs.length; x++) {
926
+ const chars = diffs[x][1], text = [];
927
+ for (let y = 0; y < chars.length; y++)
928
+ text[y] = lineArray[chars.charCodeAt(y)];
929
+ diffs[x][1] = text.join("");
930
+ }
931
+ }
932
+ function linesToChars(textA, textB) {
933
+ const lineArray = [], lineHash = {};
934
+ lineArray[0] = "";
935
+ function diffLinesToMunge(text) {
936
+ let chars = "", lineStart = 0, lineEnd = -1, lineArrayLength = lineArray.length;
937
+ for (; lineEnd < text.length - 1; ) {
938
+ lineEnd = text.indexOf(`
939
+ `, lineStart), lineEnd === -1 && (lineEnd = text.length - 1);
940
+ let line = text.slice(lineStart, lineEnd + 1);
941
+ (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) ? chars += String.fromCharCode(lineHash[line]) : (lineArrayLength === maxLines && (line = text.slice(lineStart), lineEnd = text.length), chars += String.fromCharCode(lineArrayLength), lineHash[line] = lineArrayLength, lineArray[lineArrayLength++] = line), lineStart = lineEnd + 1;
942
+ }
943
+ return chars;
944
+ }
945
+ let maxLines = 4e4;
946
+ const chars1 = diffLinesToMunge(textA);
947
+ maxLines = 65535;
948
+ const chars2 = diffLinesToMunge(textB);
949
+ return {
950
+ chars1,
951
+ chars2,
952
+ lineArray
953
+ };
954
+ }
955
+ function doLineModeDiff(textA, textB, opts) {
956
+ let text1 = textA, text2 = textB;
957
+ const a = linesToChars(text1, text2);
958
+ text1 = a.chars1, text2 = a.chars2;
959
+ const linearray = a.lineArray;
960
+ let diffs = doDiff(text1, text2, {
961
+ checkLines: !1,
962
+ deadline: opts.deadline
963
+ });
964
+ charsToLines(diffs, linearray), diffs = cleanupSemantic(diffs), diffs.push([DIFF_EQUAL, ""]);
965
+ let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "";
966
+ for (; pointer < diffs.length; ) {
967
+ switch (diffs[pointer][0]) {
968
+ case DIFF_INSERT:
969
+ countInsert++, textInsert += diffs[pointer][1];
970
+ break;
971
+ case DIFF_DELETE:
972
+ countDelete++, textDelete += diffs[pointer][1];
973
+ break;
974
+ case DIFF_EQUAL:
975
+ if (countDelete >= 1 && countInsert >= 1) {
976
+ diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert), pointer = pointer - countDelete - countInsert;
977
+ const aa = doDiff(textDelete, textInsert, {
978
+ checkLines: !1,
979
+ deadline: opts.deadline
980
+ });
981
+ for (let j = aa.length - 1; j >= 0; j--)
982
+ diffs.splice(pointer, 0, aa[j]);
983
+ pointer += aa.length;
965
984
  }
966
- },
967
- insertChild: (type, value) => {
968
- var _a;
969
- if (!editor.selection)
970
- throw new Error("The editor has no selection");
971
- const [focusBlock] = Array.from(
972
- slate.Editor.nodes(editor, {
973
- at: editor.selection.focus.path.slice(0, 1),
974
- match: (n) => n._type === types2.block.name
975
- })
976
- )[0] || [void 0];
977
- if (!focusBlock)
978
- throw new Error("No focused text block");
979
- if (type.name !== types2.span.name && !types2.inlineObjects.some((t) => t.name === type.name))
980
- throw new Error("This type cannot be inserted as a child to a text block");
981
- const child = toSlateValue(
982
- [
983
- {
984
- _key: keyGenerator(),
985
- _type: types2.block.name,
986
- children: [
987
- {
988
- _key: keyGenerator(),
989
- _type: type.name,
990
- ...value || {}
991
- }
992
- ]
993
- }
994
- ],
995
- portableTextEditor
996
- )[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types2.span.name, focusNode = slate.Node.get(editor, focusChildPath);
997
- return isSpanNode && focusNode._type !== types2.span.name && (debug$i("Inserting span child next to inline object child, moving selection + 1"), editor.move({ distance: 1, unit: "character" })), slate.Transforms.insertNodes(editor, child, {
998
- select: !0,
999
- at: editor.selection
1000
- }), editor.onChange(), ((_a = toPortableTextRange(
1001
- fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1002
- editor.selection,
1003
- types2
1004
- )) == null ? void 0 : _a.focus.path) || [];
1005
- },
1006
- insertBlock: (type, value) => {
1007
- var _a;
1008
- if (!editor.selection)
1009
- throw new Error("The editor has no selection");
1010
- const block = toSlateValue(
1011
- [
1012
- {
1013
- _key: keyGenerator(),
1014
- _type: type.name,
1015
- ...value || {}
1016
- }
1017
- ],
1018
- portableTextEditor
1019
- )[0], [focusBlock] = Array.from(
1020
- slate.Editor.nodes(editor, {
1021
- at: editor.selection.focus.path.slice(0, 1),
1022
- match: (n) => n._type === types2.block.name
1023
- })
1024
- )[0] || [void 0];
1025
- return focusBlock && isEqualToEmptyEditor([focusBlock], types2) && slate.Transforms.removeNodes(editor, { at: editor.selection }), slate.Editor.insertNode(editor, block), editor.onChange(), ((_a = toPortableTextRange(
1026
- fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1027
- editor.selection,
1028
- types2
1029
- )) == null ? void 0 : _a.focus.path) || [];
1030
- },
1031
- hasBlockStyle: (style) => {
1032
- try {
1033
- return editor.pteHasBlockStyle(style);
1034
- } catch {
1035
- return !1;
1036
- }
1037
- },
1038
- hasListStyle: (listStyle) => {
1039
- try {
1040
- return editor.pteHasListStyle(listStyle);
1041
- } catch {
1042
- return !1;
1043
- }
1044
- },
1045
- isVoid: (element) => ![types2.block.name, types2.span.name].includes(element._type),
1046
- findByPath: (path) => {
1047
- const slatePath = toSlateRange(
1048
- { focus: { path, offset: 0 }, anchor: { path, offset: 0 } },
1049
- editor
1050
- );
1051
- if (slatePath) {
1052
- const [block, blockPath] = slate.Editor.node(editor, slatePath.focus.path.slice(0, 1));
1053
- if (block && blockPath && typeof block._key == "string") {
1054
- if (path.length === 1 && slatePath.focus.path.length === 1)
1055
- return [fromSlateValue([block], types2.block.name)[0], [{ _key: block._key }]];
1056
- const ptBlock = fromSlateValue(
1057
- [block],
1058
- types2.block.name,
1059
- KEY_TO_VALUE_ELEMENT.get(editor)
1060
- )[0];
1061
- if (editor.isTextBlock(ptBlock)) {
1062
- const ptChild = ptBlock.children[slatePath.focus.path[1]];
1063
- if (ptChild)
1064
- return [ptChild, [{ _key: block._key }, "children", { _key: ptChild._key }]];
1065
- }
1066
- }
1067
- }
1068
- return [void 0, void 0];
1069
- },
1070
- findDOMNode: (element) => {
1071
- let node;
1072
- try {
1073
- const [item] = Array.from(
1074
- slate.Editor.nodes(editor, {
1075
- at: [],
1076
- match: (n) => n._key === element._key
1077
- }) || []
1078
- )[0] || [void 0];
1079
- node = slateReact.ReactEditor.toDOMNode(editor, item);
1080
- } catch {
1081
- }
1082
- return node;
1083
- },
1084
- activeAnnotations: () => {
1085
- var _a;
1086
- if (!editor.selection || editor.selection.focus.path.length < 2)
1087
- return [];
1088
- try {
1089
- const activeAnnotations = [], spans = slate.Editor.nodes(editor, {
1090
- at: editor.selection,
1091
- match: (node) => slate.Text.isText(node) && node.marks !== void 0 && Array.isArray(node.marks) && node.marks.length > 0
1092
- });
1093
- for (const [span, path] of spans) {
1094
- const [block] = slate.Editor.node(editor, path, { depth: 1 });
1095
- editor.isTextBlock(block) && ((_a = block.markDefs) == null || _a.forEach((def) => {
1096
- slate.Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
1097
- }));
1098
- }
1099
- return activeAnnotations;
1100
- } catch {
1101
- return [];
1102
- }
1103
- },
1104
- isAnnotationActive: (annotationType) => {
1105
- if (!editor.selection || editor.selection.focus.path.length < 2)
1106
- return !1;
1107
- try {
1108
- const spans = [
1109
- ...slate.Editor.nodes(editor, {
1110
- at: editor.selection,
1111
- match: (node) => slate.Text.isText(node)
1112
- })
1113
- ];
1114
- if (spans.some(
1115
- ([span]) => {
1116
- var _a;
1117
- return !types$1.isPortableTextSpan(span) || !span.marks || ((_a = span.marks) == null ? void 0 : _a.length) === 0;
1118
- }
1119
- ))
1120
- return !1;
1121
- const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
1122
- const [block] = slate.Editor.node(editor, path, { depth: 1 });
1123
- return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
1124
- }, []);
1125
- return spans.every(([span]) => {
1126
- var _a;
1127
- if (!types$1.isPortableTextSpan(span)) return !1;
1128
- const spanMarkDefs = (_a = span.marks) == null ? void 0 : _a.map(
1129
- (markKey) => {
1130
- var _a2;
1131
- return (_a2 = selectionMarkDefs.find((def) => (def == null ? void 0 : def._key) === markKey)) == null ? void 0 : _a2._type;
1132
- }
1133
- );
1134
- return spanMarkDefs == null ? void 0 : spanMarkDefs.includes(annotationType);
1135
- });
1136
- } catch {
1137
- return !1;
1138
- }
1139
- },
1140
- addAnnotation: (type, value) => {
1141
- const { selection: originalSelection } = editor;
1142
- let returnValue;
1143
- if (originalSelection) {
1144
- const [block] = slate.Editor.node(editor, originalSelection.focus, { depth: 1 });
1145
- if (!editor.isTextBlock(block))
1146
- return;
1147
- slate.Range.isCollapsed(originalSelection) && (editor.pteExpandToWord(), editor.onChange());
1148
- const [textNode] = slate.Editor.node(editor, originalSelection.focus, { depth: 2 });
1149
- editor.selection && (slate.Editor.withoutNormalizing(editor, () => {
1150
- const annotationKey = keyGenerator();
1151
- slate.Transforms.setNodes(
1152
- editor,
1153
- {
1154
- markDefs: [
1155
- ...block.markDefs || [],
1156
- { _type: type.name, _key: annotationKey, ...value }
1157
- ]
1158
- },
1159
- { at: originalSelection.focus }
1160
- ), editor.onChange(), slate.Transforms.setNodes(editor, {}, { match: slate.Text.isText, split: !0 }), editor.onChange(), editor.selection && slate.Text.isText(textNode) && slate.Transforms.setNodes(
1161
- editor,
1162
- {
1163
- marks: [...textNode.marks || [], annotationKey]
1164
- },
1165
- {
1166
- at: editor.selection,
1167
- match: (n) => n._type === types2.span.name
1168
- }
1169
- ), editor.onChange(), editor.selection && slate.Transforms.insertNodes(
1170
- editor,
1171
- [{ _type: "span", text: "", marks: [], _key: keyGenerator() }],
1172
- {
1173
- at: slate.Range.end(editor.selection)
1174
- }
1175
- );
1176
- const newPortableTextEditorSelection = toPortableTextRange(
1177
- fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1178
- editor.selection,
1179
- types2
1180
- );
1181
- newPortableTextEditorSelection && (returnValue = {
1182
- spanPath: newPortableTextEditorSelection.focus.path,
1183
- markDefPath: [{ _key: block._key }, "markDefs", { _key: annotationKey }]
1184
- });
1185
- }), slate.Editor.normalize(editor), editor.onChange());
1186
- }
1187
- return returnValue;
1188
- },
1189
- delete: (selection, options) => {
1190
- if (selection) {
1191
- const range = toSlateRange(selection, editor);
1192
- if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
1193
- throw new Error("Invalid range");
1194
- if (range) {
1195
- if (!(options != null && options.mode) || (options == null ? void 0 : options.mode) === "selected") {
1196
- debug$i("Deleting content in selection"), slate.Transforms.delete(editor, {
1197
- at: range,
1198
- hanging: !0,
1199
- voids: !0
1200
- }), editor.onChange();
1201
- return;
1202
- }
1203
- (options == null ? void 0 : options.mode) === "blocks" && (debug$i("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
1204
- at: range,
1205
- voids: !0,
1206
- match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && slate.Element.isElement(node)
1207
- })), (options == null ? void 0 : options.mode) === "children" && (debug$i("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
1208
- at: range,
1209
- voids: !0,
1210
- match: (node) => node._type === types2.span.name || // Text children
1211
- !editor.isTextBlock(node) && slate.Element.isElement(node)
1212
- })), editor.children.length === 0 && (editor.children = [editor.pteCreateEmptyBlock()]), editor.onChange();
1213
- }
1214
- }
1215
- },
1216
- removeAnnotation: (type) => {
1217
- let { selection } = editor;
1218
- if (debug$i("Removing annotation", type), selection) {
1219
- if (slate.Range.isCollapsed(selection)) {
1220
- const [node, nodePath] = slate.Editor.node(editor, selection, { depth: 2 });
1221
- slate.Text.isText(node) && node.marks && typeof node.text == "string" && (slate.Transforms.select(editor, nodePath), selection = editor.selection);
1222
- }
1223
- slate.Editor.withoutNormalizing(editor, () => {
1224
- if (selection && slate.Range.isExpanded(selection)) {
1225
- if (selection = editor.selection, !selection)
1226
- return;
1227
- [
1228
- ...slate.Editor.nodes(editor, {
1229
- at: selection,
1230
- match: (node) => editor.isTextBlock(node) && Array.isArray(node.markDefs) && node.markDefs.some((def) => def._type === type.name)
1231
- })
1232
- ].forEach(([block]) => {
1233
- editor.isTextBlock(block) && Array.isArray(block.markDefs) && block.markDefs.filter((def) => def._type === type.name).forEach((def) => {
1234
- slate.Editor.removeMark(editor, def._key);
1235
- });
1236
- });
1237
- }
1238
- }), slate.Editor.normalize(editor), editor.onChange();
1239
- }
1240
- },
1241
- getSelection: () => {
1242
- let ptRange = null;
1243
- if (editor.selection) {
1244
- const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
1245
- if (existing)
1246
- return existing;
1247
- ptRange = toPortableTextRange(
1248
- fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1249
- editor.selection,
1250
- types2
1251
- ), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
985
+ countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
986
+ break;
987
+ default:
988
+ throw new Error("Unknown diff operation.");
989
+ }
990
+ pointer++;
991
+ }
992
+ return diffs.pop(), diffs;
993
+ }
994
+ function computeDiff(text1, text2, opts) {
995
+ let diffs;
996
+ if (!text1)
997
+ return [[DIFF_INSERT, text2]];
998
+ if (!text2)
999
+ return [[DIFF_DELETE, text1]];
1000
+ const longtext = text1.length > text2.length ? text1 : text2, shorttext = text1.length > text2.length ? text2 : text1, i = longtext.indexOf(shorttext);
1001
+ if (i !== -1)
1002
+ return diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]], text1.length > text2.length && (diffs[0][0] = DIFF_DELETE, diffs[2][0] = DIFF_DELETE), diffs;
1003
+ if (shorttext.length === 1)
1004
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1005
+ const halfMatch = findHalfMatch(text1, text2);
1006
+ if (halfMatch) {
1007
+ const text1A = halfMatch[0], text1B = halfMatch[1], text2A = halfMatch[2], text2B = halfMatch[3], midCommon = halfMatch[4], diffsA = doDiff(text1A, text2A, opts), diffsB = doDiff(text1B, text2B, opts);
1008
+ return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
1009
+ }
1010
+ return opts.checkLines && text1.length > 100 && text2.length > 100 ? doLineModeDiff(text1, text2, opts) : bisect(text1, text2, opts.deadline);
1011
+ }
1012
+ const DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0;
1013
+ function diff(textA, textB, opts) {
1014
+ if (textA === null || textB === null)
1015
+ throw new Error("Null input. (diff)");
1016
+ const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));
1017
+ return adjustDiffForSurrogatePairs(diffs), diffs;
1018
+ }
1019
+ function doDiff(textA, textB, options) {
1020
+ let text1 = textA, text2 = textB;
1021
+ if (text1 === text2)
1022
+ return text1 ? [[DIFF_EQUAL, text1]] : [];
1023
+ let commonlength = getCommonPrefix(text1, text2);
1024
+ const commonprefix = text1.substring(0, commonlength);
1025
+ text1 = text1.substring(commonlength), text2 = text2.substring(commonlength), commonlength = getCommonSuffix(text1, text2);
1026
+ const commonsuffix = text1.substring(text1.length - commonlength);
1027
+ text1 = text1.substring(0, text1.length - commonlength), text2 = text2.substring(0, text2.length - commonlength);
1028
+ let diffs = computeDiff(text1, text2, options);
1029
+ return commonprefix && diffs.unshift([DIFF_EQUAL, commonprefix]), commonsuffix && diffs.push([DIFF_EQUAL, commonsuffix]), diffs = cleanupMerge(diffs), diffs;
1030
+ }
1031
+ function createDeadLine(timeout) {
1032
+ let t = 1;
1033
+ return typeof timeout < "u" && (t = timeout <= 0 ? Number.MAX_VALUE : timeout), Date.now() + t * 1e3;
1034
+ }
1035
+ function createInternalOpts(opts) {
1036
+ return {
1037
+ checkLines: !0,
1038
+ deadline: createDeadLine(opts.timeout || 1),
1039
+ ...opts
1040
+ };
1041
+ }
1042
+ function combineChar(data, char, dir) {
1043
+ return dir === 1 ? data + char : char + data;
1044
+ }
1045
+ function splitChar(data, dir) {
1046
+ return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];
1047
+ }
1048
+ function hasSharedChar(diffs, i, j, dir) {
1049
+ return dir === 1 ? diffs[i][1][diffs[i][1].length - 1] === diffs[j][1][diffs[j][1].length - 1] : diffs[i][1][0] === diffs[j][1][0];
1050
+ }
1051
+ function deisolateChar(diffs, i, dir) {
1052
+ const inv = dir === 1 ? -1 : 1;
1053
+ let insertIdx = null, deleteIdx = null, j = i + dir;
1054
+ for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {
1055
+ const [op, text2] = diffs[j];
1056
+ if (text2.length !== 0) {
1057
+ if (op === DIFF_INSERT) {
1058
+ insertIdx === null && (insertIdx = j);
1059
+ continue;
1060
+ } else if (op === DIFF_DELETE) {
1061
+ deleteIdx === null && (deleteIdx = j);
1062
+ continue;
1063
+ } else if (op === DIFF_EQUAL) {
1064
+ if (insertIdx === null && deleteIdx === null) {
1065
+ const [rest, char2] = splitChar(diffs[i][1], dir);
1066
+ diffs[i][1] = rest, diffs[j][1] = combineChar(diffs[j][1], char2, inv);
1067
+ return;
1252
1068
  }
1253
- return ptRange;
1254
- },
1255
- getValue: () => fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1256
- isCollapsedSelection: () => !!editor.selection && slate.Range.isCollapsed(editor.selection),
1257
- isExpandedSelection: () => !!editor.selection && slate.Range.isExpanded(editor.selection),
1258
- insertBreak: () => {
1259
- editor.insertBreak(), editor.onChange();
1260
- },
1261
- getFragment: () => fromSlateValue(editor.getFragment(), types2.block.name),
1262
- isSelectionsOverlapping: (selectionA, selectionB) => {
1263
- const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
1264
- return slate.Range.isRange(rangeA) && slate.Range.isRange(rangeB) && slate.Range.includes(rangeA, rangeB);
1069
+ break;
1265
1070
  }
1266
- }), editor;
1071
+ }
1072
+ }
1073
+ if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {
1074
+ const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv), [deleteText] = splitChar(diffs[deleteIdx][1], inv);
1075
+ diffs[insertIdx][1] = insertText, diffs[deleteIdx][1] = deleteText, diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);
1076
+ return;
1077
+ }
1078
+ const [text, char] = splitChar(diffs[i][1], dir);
1079
+ diffs[i][1] = text, insertIdx === null ? (diffs.splice(j, 0, [DIFF_INSERT, char]), deleteIdx !== null && deleteIdx >= j && deleteIdx++) : diffs[insertIdx][1] = combineChar(diffs[insertIdx][1], char, inv), deleteIdx === null ? diffs.splice(j, 0, [DIFF_DELETE, char]) : diffs[deleteIdx][1] = combineChar(diffs[deleteIdx][1], char, inv);
1080
+ }
1081
+ function adjustDiffForSurrogatePairs(diffs) {
1082
+ for (let i = 0; i < diffs.length; i++) {
1083
+ const [diffType, diffText] = diffs[i];
1084
+ if (diffText.length === 0) continue;
1085
+ const firstChar = diffText[0], lastChar = diffText[diffText.length - 1];
1086
+ isHighSurrogate(lastChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, 1), isLowSurrogate(firstChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, -1);
1087
+ }
1088
+ for (let i = 0; i < diffs.length; i++)
1089
+ diffs[i][1].length === 0 && diffs.splice(i, 1);
1090
+ }
1091
+ const DEFAULT_OPTIONS = {
1092
+ /**
1093
+ * At what point is no match declared (0.0 = perfection, 1.0 = very loose).
1094
+ */
1095
+ threshold: 0.5,
1096
+ /**
1097
+ * How far to search for a match (0 = exact location, 1000+ = broad match).
1098
+ * A match this many characters away from the expected location will add
1099
+ * 1.0 to the score (0.0 is a perfect match).
1100
+ */
1101
+ distance: 1e3
1102
+ };
1103
+ function applyDefaults(options) {
1104
+ return {
1105
+ ...DEFAULT_OPTIONS,
1106
+ ...options
1107
+ };
1108
+ }
1109
+ const MAX_BITS$1 = 32;
1110
+ function bitap(text, pattern, loc) {
1111
+ let opts = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1112
+ if (pattern.length > MAX_BITS$1)
1113
+ throw new Error("Pattern too long for this browser.");
1114
+ const options = applyDefaults(opts), s = getAlphabetFromPattern(pattern);
1115
+ function getBitapScore(e, x) {
1116
+ const accuracy = e / pattern.length, proximity = Math.abs(loc - x);
1117
+ return options.distance ? accuracy + proximity / options.distance : proximity ? 1 : accuracy;
1118
+ }
1119
+ let scoreThreshold = options.threshold, bestLoc = text.indexOf(pattern, loc);
1120
+ bestLoc !== -1 && (scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold), bestLoc = text.lastIndexOf(pattern, loc + pattern.length), bestLoc !== -1 && (scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold)));
1121
+ const matchmask = 1 << pattern.length - 1;
1122
+ bestLoc = -1;
1123
+ let binMin, binMid, binMax = pattern.length + text.length, lastRd = [];
1124
+ for (let d = 0; d < pattern.length; d++) {
1125
+ for (binMin = 0, binMid = binMax; binMin < binMid; )
1126
+ getBitapScore(d, loc + binMid) <= scoreThreshold ? binMin = binMid : binMax = binMid, binMid = Math.floor((binMax - binMin) / 2 + binMin);
1127
+ binMax = binMid;
1128
+ let start = Math.max(1, loc - binMid + 1);
1129
+ const finish = Math.min(loc + binMid, text.length) + pattern.length, rd = new Array(finish + 2);
1130
+ rd[finish + 1] = (1 << d) - 1;
1131
+ for (let j = finish; j >= start; j--) {
1132
+ const charMatch = s[text.charAt(j - 1)];
1133
+ if (d === 0 ? rd[j] = (rd[j + 1] << 1 | 1) & charMatch : rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((lastRd[j + 1] | lastRd[j]) << 1 | 1) | lastRd[j + 1], rd[j] & matchmask) {
1134
+ const score = getBitapScore(d, j - 1);
1135
+ if (score <= scoreThreshold)
1136
+ if (scoreThreshold = score, bestLoc = j - 1, bestLoc > loc)
1137
+ start = Math.max(1, 2 * loc - bestLoc);
1138
+ else
1139
+ break;
1140
+ }
1141
+ }
1142
+ if (getBitapScore(d + 1, loc) > scoreThreshold)
1143
+ break;
1144
+ lastRd = rd;
1145
+ }
1146
+ return bestLoc;
1147
+ }
1148
+ function getAlphabetFromPattern(pattern) {
1149
+ const s = {};
1150
+ for (let i = 0; i < pattern.length; i++)
1151
+ s[pattern.charAt(i)] = 0;
1152
+ for (let i = 0; i < pattern.length; i++)
1153
+ s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;
1154
+ return s;
1155
+ }
1156
+ function match(text, pattern, searchLocation) {
1157
+ if (text === null || pattern === null || searchLocation === null)
1158
+ throw new Error("Null input. (match())");
1159
+ const loc = Math.max(0, Math.min(searchLocation, text.length));
1160
+ if (text === pattern)
1161
+ return 0;
1162
+ if (text.length) {
1163
+ if (text.substring(loc, loc + pattern.length) === pattern)
1164
+ return loc;
1165
+ } else return -1;
1166
+ return bitap(text, pattern, loc);
1167
+ }
1168
+ function createPatchObject(start1, start2) {
1169
+ return {
1170
+ diffs: [],
1171
+ start1,
1172
+ start2,
1173
+ utf8Start1: start1,
1174
+ utf8Start2: start2,
1175
+ length1: 0,
1176
+ length2: 0,
1177
+ utf8Length1: 0,
1178
+ utf8Length2: 0
1267
1179
  };
1268
1180
  }
1269
- function createWithInsertBreak(types2) {
1270
- return function(editor) {
1271
- const { insertBreak } = editor;
1272
- return editor.insertBreak = () => {
1273
- if (editor.selection) {
1274
- const focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = slate.Node.descendant(editor, focusBlockPath);
1275
- if (editor.isTextBlock(focusBlock)) {
1276
- const [, end] = slate.Range.edges(editor.selection), isEndAtStartOfNode = slate.Editor.isStart(editor, end, end.path), isEmptyTextBlock = focusBlock && isEqualToEmptyEditor([focusBlock], types2);
1277
- if (isEndAtStartOfNode && !isEmptyTextBlock) {
1278
- slate.Editor.insertNode(editor, editor.pteCreateEmptyBlock());
1279
- const [nextBlockPath] = slate.Path.next(focusBlockPath);
1280
- slate.Transforms.select(editor, {
1281
- anchor: { path: [nextBlockPath, 0], offset: 0 },
1282
- focus: { path: [nextBlockPath, 0], offset: 0 }
1283
- }), editor.onChange();
1284
- return;
1285
- }
1286
- }
1287
- }
1288
- insertBreak();
1289
- }, editor;
1290
- };
1181
+ function diffText1(diffs) {
1182
+ const text = [];
1183
+ for (let x = 0; x < diffs.length; x++)
1184
+ diffs[x][0] !== DIFF_INSERT && (text[x] = diffs[x][1]);
1185
+ return text.join("");
1186
+ }
1187
+ function diffText2(diffs) {
1188
+ const text = [];
1189
+ for (let x = 0; x < diffs.length; x++)
1190
+ diffs[x][0] !== DIFF_DELETE && (text[x] = diffs[x][1]);
1191
+ return text.join("");
1192
+ }
1193
+ function countUtf8Bytes(str) {
1194
+ let bytes = 0;
1195
+ for (let i = 0; i < str.length; i++) {
1196
+ const codePoint = str.codePointAt(i);
1197
+ if (typeof codePoint > "u")
1198
+ throw new Error("Failed to get codepoint");
1199
+ bytes += utf8len(codePoint);
1200
+ }
1201
+ return bytes;
1202
+ }
1203
+ function adjustIndiciesToUcs2(patches, base) {
1204
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, byteOffset = 0, idx = 0;
1205
+ function advanceTo(target) {
1206
+ for (; byteOffset < target; ) {
1207
+ const codePoint = base.codePointAt(idx);
1208
+ if (typeof codePoint > "u")
1209
+ return idx;
1210
+ byteOffset += utf8len(codePoint), codePoint > 65535 ? idx += 2 : idx += 1;
1211
+ }
1212
+ if (!options.allowExceedingIndices && byteOffset !== target)
1213
+ throw new Error("Failed to determine byte offset");
1214
+ return idx;
1215
+ }
1216
+ const adjusted = [];
1217
+ for (const patch of patches)
1218
+ adjusted.push({
1219
+ diffs: patch.diffs.map((diff2) => cloneDiff(diff2)),
1220
+ start1: advanceTo(patch.start1),
1221
+ start2: advanceTo(patch.start2),
1222
+ utf8Start1: patch.utf8Start1,
1223
+ utf8Start2: patch.utf8Start2,
1224
+ length1: patch.length1,
1225
+ length2: patch.length2,
1226
+ utf8Length1: patch.utf8Length1,
1227
+ utf8Length2: patch.utf8Length2
1228
+ });
1229
+ return adjusted;
1291
1230
  }
1292
- function createWithMaxBlocks(maxBlocks) {
1293
- return function(editor) {
1294
- const { apply: apply2 } = editor;
1295
- return editor.apply = (operation) => {
1296
- const rows = maxBlocks;
1297
- rows > 0 && editor.children.length >= rows && (operation.type === "insert_node" || operation.type === "split_node") && operation.path.length === 1 || apply2(operation);
1298
- }, editor;
1231
+ function utf8len(codePoint) {
1232
+ return codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
1233
+ }
1234
+ const MAX_BITS = 32, DEFAULT_MARGIN = 4, DEFAULT_OPTS = {
1235
+ margin: 4
1236
+ };
1237
+ function getDefaultOpts() {
1238
+ let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1239
+ return {
1240
+ ...DEFAULT_OPTS,
1241
+ ...opts
1299
1242
  };
1300
1243
  }
1301
- const PRESERVE_KEYS = /* @__PURE__ */ new WeakMap();
1302
- function withPreserveKeys(editor, fn) {
1303
- const prev = isPreservingKeys(editor);
1304
- PRESERVE_KEYS.set(editor, !0), fn(), PRESERVE_KEYS.set(editor, prev);
1244
+ function make(a, b, options) {
1245
+ if (typeof a == "string" && typeof b == "string") {
1246
+ let diffs = diff(a, b, {
1247
+ checkLines: !0
1248
+ });
1249
+ return diffs.length > 2 && (diffs = cleanupSemantic(diffs), diffs = cleanupEfficiency(diffs)), _make(a, diffs, getDefaultOpts(options));
1250
+ }
1251
+ if (a && Array.isArray(a) && typeof b > "u")
1252
+ return _make(diffText1(a), a, getDefaultOpts(options));
1253
+ if (typeof a == "string" && b && Array.isArray(b))
1254
+ return _make(a, b, getDefaultOpts(options));
1255
+ throw new Error("Unknown call format to make()");
1305
1256
  }
1306
- function isPreservingKeys(editor) {
1307
- return PRESERVE_KEYS.get(editor);
1257
+ function _make(textA, diffs, options) {
1258
+ if (diffs.length === 0)
1259
+ return [];
1260
+ const patches = [];
1261
+ let patch = createPatchObject(0, 0), patchDiffLength = 0, charCount1 = 0, charCount2 = 0, utf8Count1 = 0, utf8Count2 = 0, prepatchText = textA, postpatchText = textA;
1262
+ for (let x = 0; x < diffs.length; x++) {
1263
+ const currentDiff = diffs[x], [diffType, diffText] = currentDiff, diffTextLength = diffText.length, diffByteLength = countUtf8Bytes(diffText);
1264
+ switch (!patchDiffLength && diffType !== DIFF_EQUAL && (patch.start1 = charCount1, patch.start2 = charCount2, patch.utf8Start1 = utf8Count1, patch.utf8Start2 = utf8Count2), diffType) {
1265
+ case DIFF_INSERT:
1266
+ patch.diffs[patchDiffLength++] = currentDiff, patch.length2 += diffTextLength, patch.utf8Length2 += diffByteLength, postpatchText = postpatchText.substring(0, charCount2) + diffText + postpatchText.substring(charCount2);
1267
+ break;
1268
+ case DIFF_DELETE:
1269
+ patch.length1 += diffTextLength, patch.utf8Length1 += diffByteLength, patch.diffs[patchDiffLength++] = currentDiff, postpatchText = postpatchText.substring(0, charCount2) + postpatchText.substring(charCount2 + diffTextLength);
1270
+ break;
1271
+ case DIFF_EQUAL:
1272
+ diffTextLength <= 2 * options.margin && patchDiffLength && diffs.length !== x + 1 ? (patch.diffs[patchDiffLength++] = currentDiff, patch.length1 += diffTextLength, patch.length2 += diffTextLength, patch.utf8Length1 += diffByteLength, patch.utf8Length2 += diffByteLength) : diffTextLength >= 2 * options.margin && patchDiffLength && (addContext(patch, prepatchText, options), patches.push(patch), patch = createPatchObject(-1, -1), patchDiffLength = 0, prepatchText = postpatchText, charCount1 = charCount2, utf8Count1 = utf8Count2);
1273
+ break;
1274
+ default:
1275
+ throw new Error("Unknown diff type");
1276
+ }
1277
+ diffType !== DIFF_INSERT && (charCount1 += diffTextLength, utf8Count1 += diffByteLength), diffType !== DIFF_DELETE && (charCount2 += diffTextLength, utf8Count2 += diffByteLength);
1278
+ }
1279
+ return patchDiffLength && (addContext(patch, prepatchText, options), patches.push(patch)), patches;
1308
1280
  }
1309
- function createWithObjectKeys(schemaTypes, keyGenerator) {
1310
- return function(editor) {
1311
- PRESERVE_KEYS.set(editor, !1);
1312
- const { apply: apply2, normalizeNode } = editor;
1313
- return editor.apply = (operation) => {
1314
- if (operation.type === "split_node") {
1315
- const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.properties);
1316
- operation.properties = {
1317
- ...operation.properties,
1318
- ...withNewKey ? { _key: keyGenerator() } : {}
1319
- };
1281
+ function addContext(patch, text, opts) {
1282
+ if (text.length === 0)
1283
+ return;
1284
+ let pattern = text.substring(patch.start2, patch.start2 + patch.length1), padding = 0;
1285
+ for (; text.indexOf(pattern) !== text.lastIndexOf(pattern) && pattern.length < MAX_BITS - opts.margin - opts.margin; )
1286
+ padding += opts.margin, pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding);
1287
+ padding += opts.margin;
1288
+ let prefixStart = patch.start2 - padding;
1289
+ prefixStart >= 1 && isLowSurrogate(text[prefixStart]) && prefixStart--;
1290
+ const prefix = text.substring(prefixStart, patch.start2);
1291
+ prefix && patch.diffs.unshift([DIFF_EQUAL, prefix]);
1292
+ const prefixLength = prefix.length, prefixUtf8Length = countUtf8Bytes(prefix);
1293
+ let suffixEnd = patch.start2 + patch.length1 + padding;
1294
+ suffixEnd < text.length && isLowSurrogate(text[suffixEnd]) && suffixEnd++;
1295
+ const suffix = text.substring(patch.start2 + patch.length1, suffixEnd);
1296
+ suffix && patch.diffs.push([DIFF_EQUAL, suffix]);
1297
+ const suffixLength = suffix.length, suffixUtf8Length = countUtf8Bytes(suffix);
1298
+ patch.start1 -= prefixLength, patch.start2 -= prefixLength, patch.utf8Start1 -= prefixUtf8Length, patch.utf8Start2 -= prefixUtf8Length, patch.length1 += prefixLength + suffixLength, patch.length2 += prefixLength + suffixLength, patch.utf8Length1 += prefixUtf8Length + suffixUtf8Length, patch.utf8Length2 += prefixUtf8Length + suffixUtf8Length;
1299
+ }
1300
+ function levenshtein(diffs) {
1301
+ let leven = 0, insertions = 0, deletions = 0;
1302
+ for (let x = 0; x < diffs.length; x++) {
1303
+ const op = diffs[x][0], data = diffs[x][1];
1304
+ switch (op) {
1305
+ case DIFF_INSERT:
1306
+ insertions += data.length;
1307
+ break;
1308
+ case DIFF_DELETE:
1309
+ deletions += data.length;
1310
+ break;
1311
+ case DIFF_EQUAL:
1312
+ leven += Math.max(insertions, deletions), insertions = 0, deletions = 0;
1313
+ break;
1314
+ default:
1315
+ throw new Error("Unknown diff operation.");
1316
+ }
1317
+ }
1318
+ return leven += Math.max(insertions, deletions), leven;
1319
+ }
1320
+ function xIndex(diffs, loc) {
1321
+ let chars1 = 0, chars2 = 0, lastChars1 = 0, lastChars2 = 0, x;
1322
+ for (x = 0; x < diffs.length && (diffs[x][0] !== DIFF_INSERT && (chars1 += diffs[x][1].length), diffs[x][0] !== DIFF_DELETE && (chars2 += diffs[x][1].length), !(chars1 > loc)); x++)
1323
+ lastChars1 = chars1, lastChars2 = chars2;
1324
+ return diffs.length !== x && diffs[x][0] === DIFF_DELETE ? lastChars2 : lastChars2 + (loc - lastChars1);
1325
+ }
1326
+ function addPadding(patches) {
1327
+ const paddingLength = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1328
+ let nullPadding = "";
1329
+ for (let x = 1; x <= paddingLength; x++)
1330
+ nullPadding += String.fromCharCode(x);
1331
+ for (const p of patches)
1332
+ p.start1 += paddingLength, p.start2 += paddingLength, p.utf8Start1 += paddingLength, p.utf8Start2 += paddingLength;
1333
+ let patch = patches[0], diffs = patch.diffs;
1334
+ if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL)
1335
+ diffs.unshift([DIFF_EQUAL, nullPadding]), patch.start1 -= paddingLength, patch.start2 -= paddingLength, patch.utf8Start1 -= paddingLength, patch.utf8Start2 -= paddingLength, patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
1336
+ else if (paddingLength > diffs[0][1].length) {
1337
+ const firstDiffLength = diffs[0][1].length, extraLength = paddingLength - firstDiffLength;
1338
+ diffs[0][1] = nullPadding.substring(firstDiffLength) + diffs[0][1], patch.start1 -= extraLength, patch.start2 -= extraLength, patch.utf8Start1 -= extraLength, patch.utf8Start2 -= extraLength, patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
1339
+ }
1340
+ if (patch = patches[patches.length - 1], diffs = patch.diffs, diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL)
1341
+ diffs.push([DIFF_EQUAL, nullPadding]), patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
1342
+ else if (paddingLength > diffs[diffs.length - 1][1].length) {
1343
+ const extraLength = paddingLength - diffs[diffs.length - 1][1].length;
1344
+ diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength), patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
1345
+ }
1346
+ return nullPadding;
1347
+ }
1348
+ function splitMax(patches) {
1349
+ let margin = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1350
+ const patchSize = MAX_BITS;
1351
+ for (let x = 0; x < patches.length; x++) {
1352
+ if (patches[x].length1 <= patchSize)
1353
+ continue;
1354
+ const bigpatch = patches[x];
1355
+ patches.splice(x--, 1);
1356
+ let start1 = bigpatch.start1, start2 = bigpatch.start2, preContext = "";
1357
+ for (; bigpatch.diffs.length !== 0; ) {
1358
+ const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);
1359
+ let empty = !0;
1360
+ if (preContext !== "") {
1361
+ const precontextByteCount = countUtf8Bytes(preContext);
1362
+ patch.length1 = preContext.length, patch.utf8Length1 = precontextByteCount, patch.length2 = preContext.length, patch.utf8Length2 = precontextByteCount, patch.diffs.push([DIFF_EQUAL, preContext]);
1320
1363
  }
1321
- if (operation.type === "insert_node") {
1322
- const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.node);
1323
- slate.Editor.isEditor(operation.node) || (operation.node = {
1324
- ...operation.node,
1325
- ...withNewKey ? { _key: keyGenerator() } : {}
1326
- });
1364
+ for (; bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin; ) {
1365
+ const diffType = bigpatch.diffs[0][0];
1366
+ let diffText = bigpatch.diffs[0][1], diffTextByteCount = countUtf8Bytes(diffText);
1367
+ if (diffType === DIFF_INSERT) {
1368
+ patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length;
1369
+ const diff2 = bigpatch.diffs.shift();
1370
+ diff2 && patch.diffs.push(diff2), empty = !1;
1371
+ } else diffType === DIFF_DELETE && patch.diffs.length === 1 && patch.diffs[0][0] === DIFF_EQUAL && diffText.length > 2 * patchSize ? (patch.length1 += diffText.length, patch.utf8Length1 += diffTextByteCount, start1 += diffText.length, empty = !1, patch.diffs.push([diffType, diffText]), bigpatch.diffs.shift()) : (diffText = diffText.substring(0, patchSize - patch.length1 - margin), diffTextByteCount = countUtf8Bytes(diffText), patch.length1 += diffText.length, patch.utf8Length1 += diffTextByteCount, start1 += diffText.length, diffType === DIFF_EQUAL ? (patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length) : empty = !1, patch.diffs.push([diffType, diffText]), diffText === bigpatch.diffs[0][1] ? bigpatch.diffs.shift() : bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diffText.length));
1327
1372
  }
1328
- apply2(operation);
1329
- }, editor.normalizeNode = (entry) => {
1330
- const [node, path] = entry;
1331
- if (slate.Element.isElement(node) && node._type === schemaTypes.block.name) {
1332
- node._key || slate.Transforms.setNodes(editor, { _key: keyGenerator() }, { at: path });
1333
- for (const [child, childPath] of slate.Node.children(editor, path))
1334
- if (!child._key) {
1335
- slate.Transforms.setNodes(editor, { _key: keyGenerator() }, { at: childPath });
1336
- return;
1373
+ preContext = diffText2(patch.diffs), preContext = preContext.substring(preContext.length - margin);
1374
+ const postContext = diffText1(bigpatch.diffs).substring(0, margin), postContextByteCount = countUtf8Bytes(postContext);
1375
+ postContext !== "" && (patch.length1 += postContext.length, patch.length2 += postContext.length, patch.utf8Length1 += postContextByteCount, patch.utf8Length2 += postContextByteCount, patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL ? patch.diffs[patch.diffs.length - 1][1] += postContext : patch.diffs.push([DIFF_EQUAL, postContext])), empty || patches.splice(++x, 0, patch);
1376
+ }
1377
+ }
1378
+ }
1379
+ function apply$4(patches, originalText) {
1380
+ let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1381
+ if (typeof patches == "string")
1382
+ throw new Error("Patches must be an array - pass the patch to `parsePatch()` first");
1383
+ let text = originalText;
1384
+ if (patches.length === 0)
1385
+ return [text, []];
1386
+ const parsed = adjustIndiciesToUcs2(patches, text, {
1387
+ allowExceedingIndices: opts.allowExceedingIndices
1388
+ }), margin = opts.margin || DEFAULT_MARGIN, deleteThreshold = opts.deleteThreshold || 0.4, nullPadding = addPadding(parsed, margin);
1389
+ text = nullPadding + text + nullPadding, splitMax(parsed, margin);
1390
+ let delta = 0;
1391
+ const results = [];
1392
+ for (let x = 0; x < parsed.length; x++) {
1393
+ const expectedLoc = parsed[x].start2 + delta, text1 = diffText1(parsed[x].diffs);
1394
+ let startLoc, endLoc = -1;
1395
+ if (text1.length > MAX_BITS ? (startLoc = match(text, text1.substring(0, MAX_BITS), expectedLoc), startLoc !== -1 && (endLoc = match(text, text1.substring(text1.length - MAX_BITS), expectedLoc + text1.length - MAX_BITS), (endLoc === -1 || startLoc >= endLoc) && (startLoc = -1))) : startLoc = match(text, text1, expectedLoc), startLoc === -1)
1396
+ results[x] = !1, delta -= parsed[x].length2 - parsed[x].length1;
1397
+ else {
1398
+ results[x] = !0, delta = startLoc - expectedLoc;
1399
+ let text2;
1400
+ if (endLoc === -1 ? text2 = text.substring(startLoc, startLoc + text1.length) : text2 = text.substring(startLoc, endLoc + MAX_BITS), text1 === text2)
1401
+ text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);
1402
+ else {
1403
+ let diffs = diff(text1, text2, {
1404
+ checkLines: !1
1405
+ });
1406
+ if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold)
1407
+ results[x] = !1;
1408
+ else {
1409
+ diffs = cleanupSemanticLossless(diffs);
1410
+ let index1 = 0, index2 = 0;
1411
+ for (let y = 0; y < parsed[x].diffs.length; y++) {
1412
+ const mod = parsed[x].diffs[y];
1413
+ mod[0] !== DIFF_EQUAL && (index2 = xIndex(diffs, index1)), mod[0] === DIFF_INSERT ? text = text.substring(0, startLoc + index2) + mod[1] + text.substring(startLoc + index2) : mod[0] === DIFF_DELETE && (text = text.substring(0, startLoc + index2) + text.substring(startLoc + xIndex(diffs, index1 + mod[1].length))), mod[0] !== DIFF_DELETE && (index1 += mod[1].length);
1337
1414
  }
1415
+ }
1416
+ }
1417
+ }
1418
+ }
1419
+ return text = text.substring(nullPadding.length, text.length - nullPadding.length), [text, results];
1420
+ }
1421
+ function stringify(patches) {
1422
+ return patches.map(stringifyPatch).join("");
1423
+ }
1424
+ function stringifyPatch(patch) {
1425
+ const {
1426
+ utf8Length1,
1427
+ utf8Length2,
1428
+ utf8Start1,
1429
+ utf8Start2,
1430
+ diffs
1431
+ } = patch;
1432
+ let coords1;
1433
+ utf8Length1 === 0 ? coords1 = "".concat(utf8Start1, ",0") : utf8Length1 === 1 ? coords1 = "".concat(utf8Start1 + 1) : coords1 = "".concat(utf8Start1 + 1, ",").concat(utf8Length1);
1434
+ let coords2;
1435
+ utf8Length2 === 0 ? coords2 = "".concat(utf8Start2, ",0") : utf8Length2 === 1 ? coords2 = "".concat(utf8Start2 + 1) : coords2 = "".concat(utf8Start2 + 1, ",").concat(utf8Length2);
1436
+ const text = ["@@ -".concat(coords1, " +").concat(coords2, ` @@
1437
+ `)];
1438
+ let op;
1439
+ for (let x = 0; x < diffs.length; x++) {
1440
+ switch (diffs[x][0]) {
1441
+ case DIFF_INSERT:
1442
+ op = "+";
1443
+ break;
1444
+ case DIFF_DELETE:
1445
+ op = "-";
1446
+ break;
1447
+ case DIFF_EQUAL:
1448
+ op = " ";
1449
+ break;
1450
+ default:
1451
+ throw new Error("Unknown patch operation.");
1452
+ }
1453
+ text[x + 1] = "".concat(op + encodeURI(diffs[x][1]), `
1454
+ `);
1455
+ }
1456
+ return text.join("").replace(/%20/g, " ");
1457
+ }
1458
+ const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
1459
+ function parse(textline) {
1460
+ if (!textline)
1461
+ return [];
1462
+ const patches = [], lines = textline.split(`
1463
+ `);
1464
+ let textPointer = 0;
1465
+ for (; textPointer < lines.length; ) {
1466
+ const m = lines[textPointer].match(patchHeader);
1467
+ if (!m)
1468
+ throw new Error("Invalid patch string: ".concat(lines[textPointer]));
1469
+ const patch = createPatchObject(toInt(m[1]), toInt(m[3]));
1470
+ for (patches.push(patch), m[2] === "" ? (patch.start1--, patch.utf8Start1--, patch.length1 = 1, patch.utf8Length1 = 1) : m[2] === "0" ? (patch.length1 = 0, patch.utf8Length1 = 0) : (patch.start1--, patch.utf8Start1--, patch.utf8Length1 = toInt(m[2]), patch.length1 = patch.utf8Length1), m[4] === "" ? (patch.start2--, patch.utf8Start2--, patch.length2 = 1, patch.utf8Length2 = 1) : m[4] === "0" ? (patch.length2 = 0, patch.utf8Length2 = 0) : (patch.start2--, patch.utf8Start2--, patch.utf8Length2 = toInt(m[4]), patch.length2 = patch.utf8Length2), textPointer++; textPointer < lines.length; ) {
1471
+ const currentLine = lines[textPointer], sign = currentLine.charAt(0);
1472
+ if (sign === "@")
1473
+ break;
1474
+ if (sign === "") {
1475
+ textPointer++;
1476
+ continue;
1338
1477
  }
1339
- normalizeNode(entry);
1340
- }, editor;
1341
- };
1478
+ let line;
1479
+ try {
1480
+ line = decodeURI(currentLine.slice(1));
1481
+ } catch {
1482
+ throw new Error("Illegal escape in parse: ".concat(currentLine));
1483
+ }
1484
+ const utf8Diff = countUtf8Bytes(line) - line.length;
1485
+ if (sign === "-")
1486
+ patch.diffs.push([DIFF_DELETE, line]), patch.length1 -= utf8Diff;
1487
+ else if (sign === "+")
1488
+ patch.diffs.push([DIFF_INSERT, line]), patch.length2 -= utf8Diff;
1489
+ else if (sign === " ")
1490
+ patch.diffs.push([DIFF_EQUAL, line]), patch.length1 -= utf8Diff, patch.length2 -= utf8Diff;
1491
+ else
1492
+ throw new Error('Invalid patch mode "'.concat(sign, '" in: ').concat(line));
1493
+ textPointer++;
1494
+ }
1495
+ }
1496
+ return patches;
1342
1497
  }
1343
- function isHighSurrogate(char) {
1344
- const charCode = char.charCodeAt(0);
1345
- return charCode >= 55296 && charCode <= 56319;
1498
+ function toInt(num) {
1499
+ return parseInt(num, 10);
1346
1500
  }
1347
- function isLowSurrogate(char) {
1348
- const charCode = char.charCodeAt(0);
1349
- return charCode >= 56320 && charCode <= 57343;
1501
+ function setIfMissing(value, path = []) {
1502
+ return {
1503
+ type: "setIfMissing",
1504
+ path,
1505
+ value
1506
+ };
1350
1507
  }
1351
- function cloneDiff(diff2) {
1352
- const [type, patch] = diff2;
1353
- return [type, patch];
1508
+ function diffMatchPatch$1(currentValue, nextValue, path = []) {
1509
+ const patches = make(currentValue, nextValue), patch = stringify(patches);
1510
+ return { type: "diffMatchPatch", path, value: patch };
1354
1511
  }
1355
- function getCommonOverlap(textA, textB) {
1356
- let text1 = textA, text2 = textB;
1357
- const text1Length = text1.length, text2Length = text2.length;
1358
- if (text1Length === 0 || text2Length === 0)
1359
- return 0;
1360
- text1Length > text2Length ? text1 = text1.substring(text1Length - text2Length) : text1Length < text2Length && (text2 = text2.substring(0, text1Length));
1361
- const textLength = Math.min(text1Length, text2Length);
1362
- if (text1 === text2)
1363
- return textLength;
1364
- let best = 0, length = 1;
1365
- for (let found = 0; found !== -1; ) {
1366
- const pattern = text1.substring(textLength - length);
1367
- if (found = text2.indexOf(pattern), found === -1)
1368
- return best;
1369
- length += found, (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) && (best = length, length++);
1370
- }
1371
- return best;
1512
+ function insert$1(items, position, path = []) {
1513
+ return {
1514
+ type: "insert",
1515
+ path,
1516
+ position,
1517
+ items
1518
+ };
1372
1519
  }
1373
- function getCommonPrefix(text1, text2) {
1374
- if (!text1 || !text2 || text1[0] !== text2[0])
1375
- return 0;
1376
- let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerStart = 0;
1377
- for (; pointerMin < pointerMid; )
1378
- text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid) ? (pointerMin = pointerMid, pointerStart = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
1379
- return pointerMid;
1520
+ function set(value, path = []) {
1521
+ return { type: "set", path, value };
1380
1522
  }
1381
- function getCommonSuffix(text1, text2) {
1382
- if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1])
1383
- return 0;
1384
- let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerEnd = 0;
1385
- for (; pointerMin < pointerMid; )
1386
- text1.substring(text1.length - pointerMid, text1.length - pointerEnd) === text2.substring(text2.length - pointerMid, text2.length - pointerEnd) ? (pointerMin = pointerMid, pointerEnd = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
1387
- return pointerMid;
1523
+ function unset(path = []) {
1524
+ return { type: "unset", path };
1388
1525
  }
1389
- function cleanupSemantic(rawDiffs) {
1390
- let diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
1391
- const equalities = [];
1392
- let equalitiesLength = 0, lastEquality = null, pointer = 0, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0;
1393
- for (; pointer < diffs.length; )
1394
- diffs[pointer][0] === DIFF_EQUAL ? (equalities[equalitiesLength++] = pointer, lengthInsertions1 = lengthInsertions2, lengthDeletions1 = lengthDeletions2, lengthInsertions2 = 0, lengthDeletions2 = 0, lastEquality = diffs[pointer][1]) : (diffs[pointer][0] === DIFF_INSERT ? lengthInsertions2 += diffs[pointer][1].length : lengthDeletions2 += diffs[pointer][1].length, lastEquality && lastEquality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastEquality.length <= Math.max(lengthInsertions2, lengthDeletions2) && (diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]), diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT, equalitiesLength--, equalitiesLength--, pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0, lastEquality = null, hasChanges = !0)), pointer++;
1395
- for (hasChanges && (diffs = cleanupMerge(diffs)), diffs = cleanupSemanticLossless(diffs), pointer = 1; pointer < diffs.length; ) {
1396
- if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
1397
- const deletion = diffs[pointer - 1][1], insertion = diffs[pointer][1], overlapLength1 = getCommonOverlap(deletion, insertion), overlapLength2 = getCommonOverlap(insertion, deletion);
1398
- overlapLength1 >= overlapLength2 ? (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) && (diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]), diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1), diffs[pointer + 1][1] = insertion.substring(overlapLength1), pointer++) : (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) && (diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]), diffs[pointer - 1][0] = DIFF_INSERT, diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2), diffs[pointer + 1][0] = DIFF_DELETE, diffs[pointer + 1][1] = deletion.substring(overlapLength2), pointer++), pointer++;
1399
- }
1400
- pointer++;
1526
+ const debug$j = debugWithName("operationToPatches");
1527
+ debug$j.enabled = !1;
1528
+ function createOperationToPatches(types2) {
1529
+ const textBlockName = types2.block.name;
1530
+ function insertTextPatch(editor, operation, beforeValue) {
1531
+ debug$j.enabled && debug$j("Operation", JSON.stringify(operation, null, 2));
1532
+ const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
1533
+ if (!block)
1534
+ throw new Error("Could not find block");
1535
+ const textChild = editor.isTextBlock(block) && editor.isTextSpan(block.children[operation.path[1]]) && block.children[operation.path[1]];
1536
+ if (!textChild)
1537
+ throw new Error("Could not find child");
1538
+ const path = [{ _key: block._key }, "children", { _key: textChild._key }, "text"], prevBlock = beforeValue[operation.path[0]], prevChild = editor.isTextBlock(prevBlock) && prevBlock.children[operation.path[1]], prevText = editor.isTextSpan(prevChild) ? prevChild.text : "", patch = diffMatchPatch$1(prevText, textChild.text, path);
1539
+ return patch.value.length ? [patch] : [];
1401
1540
  }
1402
- return diffs;
1403
- }
1404
- const nonAlphaNumericRegex = /[^a-zA-Z0-9]/, whitespaceRegex = /\s/, linebreakRegex = /[\r\n]/, blanklineEndRegex = /\n\r?\n$/, blanklineStartRegex = /^\r?\n\r?\n/;
1405
- function cleanupSemanticLossless(rawDiffs) {
1406
- const diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
1407
- function diffCleanupSemanticScore(one, two) {
1408
- if (!one || !two)
1409
- return 6;
1410
- const char1 = one.charAt(one.length - 1), char2 = two.charAt(0), nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex), nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex), whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex), whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex), lineBreak1 = whitespace1 && char1.match(linebreakRegex), lineBreak2 = whitespace2 && char2.match(linebreakRegex), blankLine1 = lineBreak1 && one.match(blanklineEndRegex), blankLine2 = lineBreak2 && two.match(blanklineStartRegex);
1411
- return blankLine1 || blankLine2 ? 5 : lineBreak1 || lineBreak2 ? 4 : nonAlphaNumeric1 && !whitespace1 && whitespace2 ? 3 : whitespace1 || whitespace2 ? 2 : nonAlphaNumeric1 || nonAlphaNumeric2 ? 1 : 0;
1541
+ function removeTextPatch(editor, operation, beforeValue) {
1542
+ const block = editor && editor.children[operation.path[0]];
1543
+ if (!block)
1544
+ throw new Error("Could not find block");
1545
+ const child = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, textChild = editor.isTextSpan(child) ? child : void 0;
1546
+ if (child && !textChild)
1547
+ throw new Error("Expected span");
1548
+ if (!textChild)
1549
+ throw new Error("Could not find child");
1550
+ const path = [{ _key: block._key }, "children", { _key: textChild._key }, "text"], beforeBlock = beforeValue[operation.path[0]], prevTextChild = editor.isTextBlock(beforeBlock) && beforeBlock.children[operation.path[1]], prevText = editor.isTextSpan(prevTextChild) && prevTextChild.text, patch = diffMatchPatch$1(prevText || "", textChild.text, path);
1551
+ return patch.value ? [patch] : [];
1412
1552
  }
1413
- let pointer = 1;
1414
- for (; pointer < diffs.length - 1; ) {
1415
- if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
1416
- let equality1 = diffs[pointer - 1][1], edit = diffs[pointer][1], equality2 = diffs[pointer + 1][1];
1417
- const commonOffset = getCommonSuffix(equality1, edit);
1418
- if (commonOffset) {
1419
- const commonString = edit.substring(edit.length - commonOffset);
1420
- equality1 = equality1.substring(0, equality1.length - commonOffset), edit = commonString + edit.substring(0, edit.length - commonOffset), equality2 = commonString + equality2;
1553
+ function setNodePatch(editor, operation) {
1554
+ if (operation.path.length === 1) {
1555
+ const block = editor.children[operation.path[0]];
1556
+ if (typeof block._key != "string")
1557
+ throw new Error("Expected block to have a _key");
1558
+ const setNode = omitBy__default.default(
1559
+ { ...editor.children[operation.path[0]], ...operation.newProperties },
1560
+ isUndefined__default.default
1561
+ );
1562
+ return [set(fromSlateValue([setNode], textBlockName)[0], [{ _key: block._key }])];
1563
+ } else if (operation.path.length === 2) {
1564
+ const block = editor.children[operation.path[0]];
1565
+ if (editor.isTextBlock(block)) {
1566
+ const child = block.children[operation.path[1]];
1567
+ if (child) {
1568
+ const blockKey = block._key, childKey = child._key, patches = [], keys = Object.keys(operation.newProperties);
1569
+ return keys.forEach((keyName) => {
1570
+ if (keys.length === 1 && keyName === "_key") {
1571
+ const val = get__default.default(operation.newProperties, keyName);
1572
+ patches.push(
1573
+ set(val, [{ _key: blockKey }, "children", block.children.indexOf(child), keyName])
1574
+ );
1575
+ } else {
1576
+ const val = get__default.default(operation.newProperties, keyName);
1577
+ patches.push(set(val, [{ _key: blockKey }, "children", { _key: childKey }, keyName]));
1578
+ }
1579
+ }), patches;
1580
+ }
1581
+ throw new Error("Could not find a valid child");
1421
1582
  }
1422
- let bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2, bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
1423
- for (; edit.charAt(0) === equality2.charAt(0); ) {
1424
- equality1 += edit.charAt(0), edit = edit.substring(1) + equality2.charAt(0), equality2 = equality2.substring(1);
1425
- const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
1426
- score >= bestScore && (bestScore = score, bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2);
1583
+ throw new Error("Could not find a valid block");
1584
+ } else
1585
+ throw new Error(`Unexpected path encountered: ${JSON.stringify(operation.path)}`);
1586
+ }
1587
+ function insertNodePatch(editor, operation, beforeValue) {
1588
+ const block = beforeValue[operation.path[0]], isTextBlock = editor.isTextBlock(block);
1589
+ if (operation.path.length === 1) {
1590
+ const position = operation.path[0] === 0 ? "before" : "after", beforeBlock = beforeValue[operation.path[0] - 1], targetKey = operation.path[0] === 0 ? block == null ? void 0 : block._key : beforeBlock == null ? void 0 : beforeBlock._key;
1591
+ return targetKey ? [
1592
+ insert$1([fromSlateValue([operation.node], textBlockName)[0]], position, [
1593
+ { _key: targetKey }
1594
+ ])
1595
+ ] : [
1596
+ setIfMissing(beforeValue, []),
1597
+ insert$1([fromSlateValue([operation.node], textBlockName)[0]], "before", [
1598
+ operation.path[0]
1599
+ ])
1600
+ ];
1601
+ } else if (isTextBlock && operation.path.length === 2 && editor.children[operation.path[0]]) {
1602
+ const position = block.children.length === 0 || !block.children[operation.path[1] - 1] ? "before" : "after", node = { ...operation.node };
1603
+ !node._type && slate.Text.isText(node) && (node._type = "span", node.marks = []);
1604
+ const child = fromSlateValue(
1605
+ [
1606
+ {
1607
+ _key: "bogus",
1608
+ _type: textBlockName,
1609
+ children: [node]
1610
+ }
1611
+ ],
1612
+ textBlockName
1613
+ )[0].children[0];
1614
+ return [
1615
+ insert$1([child], position, [
1616
+ { _key: block._key },
1617
+ "children",
1618
+ block.children.length <= 1 || !block.children[operation.path[1] - 1] ? 0 : { _key: block.children[operation.path[1] - 1]._key }
1619
+ ])
1620
+ ];
1621
+ }
1622
+ return debug$j("Something was inserted into a void block. Not producing editor patches."), [];
1623
+ }
1624
+ function splitNodePatch(editor, operation, beforeValue) {
1625
+ const patches = [], splitBlock = editor.children[operation.path[0]];
1626
+ if (!editor.isTextBlock(splitBlock))
1627
+ throw new Error(
1628
+ `Block with path ${JSON.stringify(
1629
+ operation.path[0]
1630
+ )} is not a text block and can't be split`
1631
+ );
1632
+ if (operation.path.length === 1) {
1633
+ const oldBlock = beforeValue[operation.path[0]];
1634
+ if (editor.isTextBlock(oldBlock)) {
1635
+ const targetValue = fromSlateValue(
1636
+ [editor.children[operation.path[0] + 1]],
1637
+ textBlockName
1638
+ )[0];
1639
+ targetValue && (patches.push(insert$1([targetValue], "after", [{ _key: splitBlock._key }])), oldBlock.children.slice(operation.position).forEach((span) => {
1640
+ const path = [{ _key: oldBlock._key }, "children", { _key: span._key }];
1641
+ patches.push(unset(path));
1642
+ }));
1427
1643
  }
1428
- diffs[pointer - 1][1] !== bestEquality1 && (bestEquality1 ? diffs[pointer - 1][1] = bestEquality1 : (diffs.splice(pointer - 1, 1), pointer--), diffs[pointer][1] = bestEdit, bestEquality2 ? diffs[pointer + 1][1] = bestEquality2 : (diffs.splice(pointer + 1, 1), pointer--));
1644
+ return patches;
1429
1645
  }
1430
- pointer++;
1646
+ if (operation.path.length === 2) {
1647
+ const splitSpan = splitBlock.children[operation.path[1]];
1648
+ if (editor.isTextSpan(splitSpan)) {
1649
+ const targetSpans = fromSlateValue(
1650
+ [
1651
+ {
1652
+ ...splitBlock,
1653
+ children: splitBlock.children.slice(operation.path[1] + 1, operation.path[1] + 2)
1654
+ }
1655
+ ],
1656
+ textBlockName
1657
+ )[0].children;
1658
+ patches.push(
1659
+ insert$1(targetSpans, "after", [
1660
+ { _key: splitBlock._key },
1661
+ "children",
1662
+ { _key: splitSpan._key }
1663
+ ])
1664
+ ), patches.push(
1665
+ set(splitSpan.text, [
1666
+ { _key: splitBlock._key },
1667
+ "children",
1668
+ { _key: splitSpan._key },
1669
+ "text"
1670
+ ])
1671
+ );
1672
+ }
1673
+ return patches;
1674
+ }
1675
+ return patches;
1676
+ }
1677
+ function removeNodePatch(editor, operation, beforeValue) {
1678
+ const block = beforeValue[operation.path[0]];
1679
+ if (operation.path.length === 1) {
1680
+ if (block && block._key)
1681
+ return [unset([{ _key: block._key }])];
1682
+ throw new Error("Block not found");
1683
+ } else if (editor.isTextBlock(block) && operation.path.length === 2) {
1684
+ const spanToRemove = editor.isTextBlock(block) && block.children && block.children[operation.path[1]];
1685
+ return spanToRemove ? [unset([{ _key: block._key }, "children", { _key: spanToRemove._key }])] : (debug$j("Span not found in editor trying to remove node"), []);
1686
+ } else
1687
+ return debug$j("Not creating patch inside object block"), [];
1688
+ }
1689
+ function mergeNodePatch(editor, operation, beforeValue) {
1690
+ const patches = [], block = beforeValue[operation.path[0]], targetBlock = editor.children[operation.path[0]];
1691
+ if (operation.path.length === 1)
1692
+ if (block != null && block._key) {
1693
+ const newBlock = fromSlateValue([editor.children[operation.path[0] - 1]], textBlockName)[0];
1694
+ patches.push(set(newBlock, [{ _key: newBlock._key }])), patches.push(unset([{ _key: block._key }]));
1695
+ } else
1696
+ throw new Error("Target key not found!");
1697
+ else if (operation.path.length === 2 && editor.isTextBlock(targetBlock)) {
1698
+ const mergedSpan = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, targetSpan = targetBlock.children[operation.path[1] - 1];
1699
+ editor.isTextSpan(targetSpan) && (patches.push(
1700
+ set(targetSpan.text, [{ _key: block._key }, "children", { _key: targetSpan._key }, "text"])
1701
+ ), mergedSpan && patches.push(unset([{ _key: block._key }, "children", { _key: mergedSpan._key }])));
1702
+ } else
1703
+ debug$j("Void nodes can't be merged, not creating any patches");
1704
+ return patches;
1431
1705
  }
1432
- return diffs;
1433
- }
1434
- function cleanupMerge(rawDiffs) {
1435
- let diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
1436
- diffs.push([DIFF_EQUAL, ""]);
1437
- let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "", commonlength;
1438
- for (; pointer < diffs.length; )
1439
- switch (diffs[pointer][0]) {
1440
- case DIFF_INSERT:
1441
- countInsert++, textInsert += diffs[pointer][1], pointer++;
1442
- break;
1443
- case DIFF_DELETE:
1444
- countDelete++, textDelete += diffs[pointer][1], pointer++;
1445
- break;
1446
- case DIFF_EQUAL:
1447
- countDelete + countInsert > 1 ? (countDelete !== 0 && countInsert !== 0 && (commonlength = getCommonPrefix(textInsert, textDelete), commonlength !== 0 && (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL ? diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength) : (diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]), pointer++), textInsert = textInsert.substring(commonlength), textDelete = textDelete.substring(commonlength)), commonlength = getCommonSuffix(textInsert, textDelete), commonlength !== 0 && (diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1], textInsert = textInsert.substring(0, textInsert.length - commonlength), textDelete = textDelete.substring(0, textDelete.length - commonlength))), pointer -= countDelete + countInsert, diffs.splice(pointer, countDelete + countInsert), textDelete.length && (diffs.splice(pointer, 0, [DIFF_DELETE, textDelete]), pointer++), textInsert.length && (diffs.splice(pointer, 0, [DIFF_INSERT, textInsert]), pointer++), pointer++) : pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL ? (diffs[pointer - 1][1] += diffs[pointer][1], diffs.splice(pointer, 1)) : pointer++, countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
1448
- break;
1449
- default:
1450
- throw new Error("Unknown diff operation");
1706
+ function moveNodePatch(editor, operation, beforeValue) {
1707
+ const patches = [], block = beforeValue[operation.path[0]], targetBlock = beforeValue[operation.newPath[0]];
1708
+ if (operation.path.length === 1) {
1709
+ const position = operation.path[0] > operation.newPath[0] ? "before" : "after";
1710
+ patches.push(unset([{ _key: block._key }])), patches.push(
1711
+ insert$1([fromSlateValue([block], textBlockName)[0]], position, [{ _key: targetBlock._key }])
1712
+ );
1713
+ } else if (operation.path.length === 2 && editor.isTextBlock(block) && editor.isTextBlock(targetBlock)) {
1714
+ const child = block.children[operation.path[1]], targetChild = targetBlock.children[operation.newPath[1]], position = operation.newPath[1] === targetBlock.children.length ? "after" : "before", childToInsert = fromSlateValue([block], textBlockName)[0].children[operation.path[1]];
1715
+ patches.push(unset([{ _key: block._key }, "children", { _key: child._key }])), patches.push(
1716
+ insert$1([childToInsert], position, [
1717
+ { _key: targetBlock._key },
1718
+ "children",
1719
+ { _key: targetChild._key }
1720
+ ])
1721
+ );
1451
1722
  }
1452
- diffs[diffs.length - 1][1] === "" && diffs.pop();
1453
- let hasChanges = !1;
1454
- for (pointer = 1; pointer < diffs.length - 1; )
1455
- diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL && (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1] ? (diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length), diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1], diffs.splice(pointer - 1, 1), hasChanges = !0) : diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1] && (diffs[pointer - 1][1] += diffs[pointer + 1][1], diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1], diffs.splice(pointer + 1, 1), hasChanges = !0)), pointer++;
1456
- return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
1457
- }
1458
- function trueCount() {
1459
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)
1460
- args[_key] = arguments[_key];
1461
- return args.reduce((n, bool) => n + (bool ? 1 : 0), 0);
1462
- }
1463
- function cleanupEfficiency(rawDiffs) {
1464
- let editCost = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 4, diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
1465
- const equalities = [];
1466
- let equalitiesLength = 0, lastEquality = null, pointer = 0, preIns = !1, preDel = !1, postIns = !1, postDel = !1;
1467
- for (; pointer < diffs.length; )
1468
- diffs[pointer][0] === DIFF_EQUAL ? (diffs[pointer][1].length < editCost && (postIns || postDel) ? (equalities[equalitiesLength++] = pointer, preIns = postIns, preDel = postDel, lastEquality = diffs[pointer][1]) : (equalitiesLength = 0, lastEquality = null), postIns = !1, postDel = !1) : (diffs[pointer][0] === DIFF_DELETE ? postDel = !0 : postIns = !0, lastEquality && (preIns && preDel && postIns && postDel || lastEquality.length < editCost / 2 && trueCount(preIns, preDel, postIns, postDel) === 3) && (diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]), diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT, equalitiesLength--, lastEquality = null, preIns && preDel ? (postIns = !0, postDel = !0, equalitiesLength = 0) : (equalitiesLength--, pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1, postIns = !1, postDel = !1), hasChanges = !0)), pointer++;
1469
- return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
1723
+ return patches;
1724
+ }
1725
+ return {
1726
+ insertNodePatch,
1727
+ insertTextPatch,
1728
+ mergeNodePatch,
1729
+ moveNodePatch,
1730
+ removeNodePatch,
1731
+ removeTextPatch,
1732
+ setNodePatch,
1733
+ splitNodePatch
1734
+ };
1470
1735
  }
1471
- function bisect(text1, text2, deadline) {
1472
- const text1Length = text1.length, text2Length = text2.length, maxD = Math.ceil((text1Length + text2Length) / 2), vOffset = maxD, vLength = 2 * maxD, v1 = new Array(vLength), v2 = new Array(vLength);
1473
- for (let x = 0; x < vLength; x++)
1474
- v1[x] = -1, v2[x] = -1;
1475
- v1[vOffset + 1] = 0, v2[vOffset + 1] = 0;
1476
- const delta = text1Length - text2Length, front = delta % 2 !== 0;
1477
- let k1start = 0, k1end = 0, k2start = 0, k2end = 0;
1478
- for (let d = 0; d < maxD && !(Date.now() > deadline); d++) {
1479
- for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
1480
- const k1Offset = vOffset + k1;
1481
- let x1;
1482
- k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1] ? x1 = v1[k1Offset + 1] : x1 = v1[k1Offset - 1] + 1;
1483
- let y1 = x1 - k1;
1484
- for (; x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1); )
1485
- x1++, y1++;
1486
- if (v1[k1Offset] = x1, x1 > text1Length)
1487
- k1end += 2;
1488
- else if (y1 > text2Length)
1489
- k1start += 2;
1490
- else if (front) {
1491
- const k2Offset = vOffset + delta - k1;
1492
- if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
1493
- const x2 = text1Length - v2[k2Offset];
1494
- if (x1 >= x2)
1495
- return bisectSplit(text1, text2, x1, y1, deadline);
1736
+ const debug$i = debugWithName("API:editable");
1737
+ function createWithEditableAPI(portableTextEditor, types$1, keyGenerator) {
1738
+ return function(editor) {
1739
+ return portableTextEditor.setEditable({
1740
+ focus: () => {
1741
+ slateReact.ReactEditor.focus(editor);
1742
+ },
1743
+ blur: () => {
1744
+ slateReact.ReactEditor.blur(editor);
1745
+ },
1746
+ toggleMark: (mark) => {
1747
+ editor.pteToggleMark(mark);
1748
+ },
1749
+ toggleList: (listStyle) => {
1750
+ editor.pteToggleListItem(listStyle);
1751
+ },
1752
+ toggleBlockStyle: (blockStyle) => {
1753
+ editor.pteToggleBlockStyle(blockStyle);
1754
+ },
1755
+ isMarkActive: (mark) => {
1756
+ try {
1757
+ return editor.pteIsMarkActive(mark);
1758
+ } catch (err) {
1759
+ return console.warn(err), !1;
1760
+ }
1761
+ },
1762
+ marks: () => ({
1763
+ ...slate.Editor.marks(editor) || {}
1764
+ }).marks || [],
1765
+ undo: () => editor.undo(),
1766
+ redo: () => editor.redo(),
1767
+ select: (selection) => {
1768
+ const slateSelection = toSlateRange(selection, editor);
1769
+ slateSelection ? slate.Transforms.select(editor, slateSelection) : slate.Transforms.deselect(editor), editor.onChange();
1770
+ },
1771
+ focusBlock: () => {
1772
+ if (editor.selection) {
1773
+ const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
1774
+ if (block)
1775
+ return fromSlateValue([block], types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
1776
+ }
1777
+ },
1778
+ focusChild: () => {
1779
+ if (editor.selection) {
1780
+ const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
1781
+ if (block && editor.isTextBlock(block))
1782
+ return fromSlateValue(
1783
+ [block],
1784
+ types$1.block.name,
1785
+ KEY_TO_VALUE_ELEMENT.get(editor)
1786
+ )[0].children[editor.selection.focus.path[1]];
1787
+ }
1788
+ },
1789
+ insertChild: (type, value) => {
1790
+ var _a;
1791
+ if (!editor.selection)
1792
+ throw new Error("The editor has no selection");
1793
+ const [focusBlock] = Array.from(
1794
+ slate.Editor.nodes(editor, {
1795
+ at: editor.selection.focus.path.slice(0, 1),
1796
+ match: (n) => n._type === types$1.block.name
1797
+ })
1798
+ )[0] || [void 0];
1799
+ if (!focusBlock)
1800
+ throw new Error("No focused text block");
1801
+ if (type.name !== types$1.span.name && !types$1.inlineObjects.some((t) => t.name === type.name))
1802
+ throw new Error("This type cannot be inserted as a child to a text block");
1803
+ const child = toSlateValue(
1804
+ [
1805
+ {
1806
+ _key: keyGenerator(),
1807
+ _type: types$1.block.name,
1808
+ children: [
1809
+ {
1810
+ _key: keyGenerator(),
1811
+ _type: type.name,
1812
+ ...value || {}
1813
+ }
1814
+ ]
1815
+ }
1816
+ ],
1817
+ portableTextEditor
1818
+ )[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types$1.span.name, focusNode = slate.Node.get(editor, focusChildPath);
1819
+ return isSpanNode && focusNode._type !== types$1.span.name && (debug$i("Inserting span child next to inline object child, moving selection + 1"), editor.move({ distance: 1, unit: "character" })), slate.Transforms.insertNodes(editor, child, {
1820
+ select: !0,
1821
+ at: editor.selection
1822
+ }), editor.onChange(), ((_a = toPortableTextRange(
1823
+ fromSlateValue(editor.children, types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1824
+ editor.selection,
1825
+ types$1
1826
+ )) == null ? void 0 : _a.focus.path) || [];
1827
+ },
1828
+ insertBlock: (type, value) => {
1829
+ var _a;
1830
+ if (!editor.selection)
1831
+ throw new Error("The editor has no selection");
1832
+ const block = toSlateValue(
1833
+ [
1834
+ {
1835
+ _key: keyGenerator(),
1836
+ _type: type.name,
1837
+ ...value || {}
1838
+ }
1839
+ ],
1840
+ portableTextEditor
1841
+ )[0], [focusBlock] = Array.from(
1842
+ slate.Editor.nodes(editor, {
1843
+ at: editor.selection.focus.path.slice(0, 1),
1844
+ match: (n) => n._type === types$1.block.name
1845
+ })
1846
+ )[0] || [void 0];
1847
+ return focusBlock && isEqualToEmptyEditor([focusBlock], types$1) && slate.Transforms.removeNodes(editor, { at: editor.selection }), slate.Editor.insertNode(editor, block), editor.onChange(), ((_a = toPortableTextRange(
1848
+ fromSlateValue(editor.children, types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1849
+ editor.selection,
1850
+ types$1
1851
+ )) == null ? void 0 : _a.focus.path) || [];
1852
+ },
1853
+ hasBlockStyle: (style) => {
1854
+ try {
1855
+ return editor.pteHasBlockStyle(style);
1856
+ } catch {
1857
+ return !1;
1858
+ }
1859
+ },
1860
+ hasListStyle: (listStyle) => {
1861
+ try {
1862
+ return editor.pteHasListStyle(listStyle);
1863
+ } catch {
1864
+ return !1;
1865
+ }
1866
+ },
1867
+ isVoid: (element) => ![types$1.block.name, types$1.span.name].includes(element._type),
1868
+ findByPath: (path) => {
1869
+ const slatePath = toSlateRange(
1870
+ { focus: { path, offset: 0 }, anchor: { path, offset: 0 } },
1871
+ editor
1872
+ );
1873
+ if (slatePath) {
1874
+ const [block, blockPath] = slate.Editor.node(editor, slatePath.focus.path.slice(0, 1));
1875
+ if (block && blockPath && typeof block._key == "string") {
1876
+ if (path.length === 1 && slatePath.focus.path.length === 1)
1877
+ return [fromSlateValue([block], types$1.block.name)[0], [{ _key: block._key }]];
1878
+ const ptBlock = fromSlateValue(
1879
+ [block],
1880
+ types$1.block.name,
1881
+ KEY_TO_VALUE_ELEMENT.get(editor)
1882
+ )[0];
1883
+ if (editor.isTextBlock(ptBlock)) {
1884
+ const ptChild = ptBlock.children[slatePath.focus.path[1]];
1885
+ if (ptChild)
1886
+ return [ptChild, [{ _key: block._key }, "children", { _key: ptChild._key }]];
1887
+ }
1888
+ }
1889
+ }
1890
+ return [void 0, void 0];
1891
+ },
1892
+ findDOMNode: (element) => {
1893
+ let node;
1894
+ try {
1895
+ const [item] = Array.from(
1896
+ slate.Editor.nodes(editor, {
1897
+ at: [],
1898
+ match: (n) => n._key === element._key
1899
+ }) || []
1900
+ )[0] || [void 0];
1901
+ node = slateReact.ReactEditor.toDOMNode(editor, item);
1902
+ } catch {
1903
+ }
1904
+ return node;
1905
+ },
1906
+ activeAnnotations: () => {
1907
+ var _a;
1908
+ if (!editor.selection || editor.selection.focus.path.length < 2)
1909
+ return [];
1910
+ try {
1911
+ const activeAnnotations = [], spans = slate.Editor.nodes(editor, {
1912
+ at: editor.selection,
1913
+ match: (node) => slate.Text.isText(node) && node.marks !== void 0 && Array.isArray(node.marks) && node.marks.length > 0
1914
+ });
1915
+ for (const [span, path] of spans) {
1916
+ const [block] = slate.Editor.node(editor, path, { depth: 1 });
1917
+ editor.isTextBlock(block) && ((_a = block.markDefs) == null || _a.forEach((def) => {
1918
+ slate.Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
1919
+ }));
1920
+ }
1921
+ return activeAnnotations;
1922
+ } catch {
1923
+ return [];
1496
1924
  }
1497
- }
1498
- }
1499
- for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
1500
- const k2Offset = vOffset + k2;
1501
- let x2;
1502
- k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1] ? x2 = v2[k2Offset + 1] : x2 = v2[k2Offset - 1] + 1;
1503
- let y2 = x2 - k2;
1504
- for (; x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1); )
1505
- x2++, y2++;
1506
- if (v2[k2Offset] = x2, x2 > text1Length)
1507
- k2end += 2;
1508
- else if (y2 > text2Length)
1509
- k2start += 2;
1510
- else if (!front) {
1511
- const k1Offset = vOffset + delta - k2;
1512
- if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
1513
- const x1 = v1[k1Offset], y1 = vOffset + x1 - k1Offset;
1514
- if (x2 = text1Length - x2, x1 >= x2)
1515
- return bisectSplit(text1, text2, x1, y1, deadline);
1925
+ },
1926
+ isAnnotationActive: (annotationType) => {
1927
+ if (!editor.selection || editor.selection.focus.path.length < 2)
1928
+ return !1;
1929
+ try {
1930
+ const spans = [
1931
+ ...slate.Editor.nodes(editor, {
1932
+ at: editor.selection,
1933
+ match: (node) => slate.Text.isText(node)
1934
+ })
1935
+ ];
1936
+ if (spans.some(
1937
+ ([span]) => {
1938
+ var _a;
1939
+ return !types.isPortableTextSpan(span) || !span.marks || ((_a = span.marks) == null ? void 0 : _a.length) === 0;
1940
+ }
1941
+ ))
1942
+ return !1;
1943
+ const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
1944
+ const [block] = slate.Editor.node(editor, path, { depth: 1 });
1945
+ return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
1946
+ }, []);
1947
+ return spans.every(([span]) => {
1948
+ var _a;
1949
+ if (!types.isPortableTextSpan(span)) return !1;
1950
+ const spanMarkDefs = (_a = span.marks) == null ? void 0 : _a.map(
1951
+ (markKey) => {
1952
+ var _a2;
1953
+ return (_a2 = selectionMarkDefs.find((def) => (def == null ? void 0 : def._key) === markKey)) == null ? void 0 : _a2._type;
1954
+ }
1955
+ );
1956
+ return spanMarkDefs == null ? void 0 : spanMarkDefs.includes(annotationType);
1957
+ });
1958
+ } catch {
1959
+ return !1;
1516
1960
  }
1517
- }
1518
- }
1519
- }
1520
- return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1521
- }
1522
- function bisectSplit(text1, text2, x, y, deadline) {
1523
- const text1a = text1.substring(0, x), text2a = text2.substring(0, y), text1b = text1.substring(x), text2b = text2.substring(y), diffs = doDiff(text1a, text2a, {
1524
- checkLines: !1,
1525
- deadline
1526
- }), diffsb = doDiff(text1b, text2b, {
1527
- checkLines: !1,
1528
- deadline
1529
- });
1530
- return diffs.concat(diffsb);
1531
- }
1532
- function findHalfMatch(text1, text2) {
1533
- if ((arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1) <= 0)
1534
- return null;
1535
- const longText = text1.length > text2.length ? text1 : text2, shortText = text1.length > text2.length ? text2 : text1;
1536
- if (longText.length < 4 || shortText.length * 2 < longText.length)
1537
- return null;
1538
- const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4)), halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));
1539
- let halfMatch;
1540
- if (halfMatch1 && halfMatch2)
1541
- halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;
1542
- else {
1543
- if (!halfMatch1 && !halfMatch2)
1544
- return null;
1545
- halfMatch2 ? halfMatch1 || (halfMatch = halfMatch2) : halfMatch = halfMatch1;
1546
- }
1547
- if (!halfMatch)
1548
- throw new Error("Unable to find a half match.");
1549
- let text1A, text1B, text2A, text2B;
1550
- text1.length > text2.length ? (text1A = halfMatch[0], text1B = halfMatch[1], text2A = halfMatch[2], text2B = halfMatch[3]) : (text2A = halfMatch[0], text2B = halfMatch[1], text1A = halfMatch[2], text1B = halfMatch[3]);
1551
- const midCommon = halfMatch[4];
1552
- return [text1A, text1B, text2A, text2B, midCommon];
1553
- }
1554
- function halfMatchI(longText, shortText, i) {
1555
- const seed = longText.slice(i, i + Math.floor(longText.length / 4));
1556
- let j = -1, bestCommon = "", bestLongTextA, bestLongTextB, bestShortTextA, bestShortTextB;
1557
- for (; (j = shortText.indexOf(seed, j + 1)) !== -1; ) {
1558
- const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j)), suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));
1559
- bestCommon.length < suffixLength + prefixLength && (bestCommon = shortText.slice(j - suffixLength, j) + shortText.slice(j, j + prefixLength), bestLongTextA = longText.slice(0, i - suffixLength), bestLongTextB = longText.slice(i + prefixLength), bestShortTextA = shortText.slice(0, j - suffixLength), bestShortTextB = shortText.slice(j + prefixLength));
1560
- }
1561
- return bestCommon.length * 2 >= longText.length ? [bestLongTextA || "", bestLongTextB || "", bestShortTextA || "", bestShortTextB || "", bestCommon || ""] : null;
1562
- }
1563
- function charsToLines(diffs, lineArray) {
1564
- for (let x = 0; x < diffs.length; x++) {
1565
- const chars = diffs[x][1], text = [];
1566
- for (let y = 0; y < chars.length; y++)
1567
- text[y] = lineArray[chars.charCodeAt(y)];
1568
- diffs[x][1] = text.join("");
1569
- }
1570
- }
1571
- function linesToChars(textA, textB) {
1572
- const lineArray = [], lineHash = {};
1573
- lineArray[0] = "";
1574
- function diffLinesToMunge(text) {
1575
- let chars = "", lineStart = 0, lineEnd = -1, lineArrayLength = lineArray.length;
1576
- for (; lineEnd < text.length - 1; ) {
1577
- lineEnd = text.indexOf(`
1578
- `, lineStart), lineEnd === -1 && (lineEnd = text.length - 1);
1579
- let line = text.slice(lineStart, lineEnd + 1);
1580
- (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) ? chars += String.fromCharCode(lineHash[line]) : (lineArrayLength === maxLines && (line = text.slice(lineStart), lineEnd = text.length), chars += String.fromCharCode(lineArrayLength), lineHash[line] = lineArrayLength, lineArray[lineArrayLength++] = line), lineStart = lineEnd + 1;
1581
- }
1582
- return chars;
1583
- }
1584
- let maxLines = 4e4;
1585
- const chars1 = diffLinesToMunge(textA);
1586
- maxLines = 65535;
1587
- const chars2 = diffLinesToMunge(textB);
1588
- return {
1589
- chars1,
1590
- chars2,
1591
- lineArray
1961
+ },
1962
+ addAnnotation: (type, value) => {
1963
+ const { selection: originalSelection } = editor;
1964
+ let returnValue;
1965
+ if (originalSelection) {
1966
+ const [block] = slate.Editor.node(editor, originalSelection.focus, { depth: 1 });
1967
+ if (!editor.isTextBlock(block))
1968
+ return;
1969
+ slate.Range.isCollapsed(originalSelection) && (editor.pteExpandToWord(), editor.onChange());
1970
+ const [textNode] = slate.Editor.node(editor, originalSelection.focus, { depth: 2 });
1971
+ editor.selection && (slate.Editor.withoutNormalizing(editor, () => {
1972
+ const annotationKey = keyGenerator();
1973
+ slate.Transforms.setNodes(
1974
+ editor,
1975
+ {
1976
+ markDefs: [
1977
+ ...block.markDefs || [],
1978
+ { _type: type.name, _key: annotationKey, ...value }
1979
+ ]
1980
+ },
1981
+ { at: originalSelection.focus }
1982
+ ), editor.onChange(), slate.Transforms.setNodes(editor, {}, { match: slate.Text.isText, split: !0 }), editor.onChange(), editor.selection && slate.Text.isText(textNode) && slate.Transforms.setNodes(
1983
+ editor,
1984
+ {
1985
+ marks: [...textNode.marks || [], annotationKey]
1986
+ },
1987
+ {
1988
+ at: editor.selection,
1989
+ match: (n) => n._type === types$1.span.name
1990
+ }
1991
+ ), editor.onChange(), editor.selection && slate.Transforms.insertNodes(
1992
+ editor,
1993
+ [{ _type: "span", text: "", marks: [], _key: keyGenerator() }],
1994
+ {
1995
+ at: slate.Range.end(editor.selection)
1996
+ }
1997
+ );
1998
+ const newPortableTextEditorSelection = toPortableTextRange(
1999
+ fromSlateValue(editor.children, types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
2000
+ editor.selection,
2001
+ types$1
2002
+ );
2003
+ newPortableTextEditorSelection && (returnValue = {
2004
+ spanPath: newPortableTextEditorSelection.focus.path,
2005
+ markDefPath: [{ _key: block._key }, "markDefs", { _key: annotationKey }]
2006
+ });
2007
+ }), slate.Editor.normalize(editor), editor.onChange());
2008
+ }
2009
+ return returnValue;
2010
+ },
2011
+ delete: (selection, options) => {
2012
+ if (selection) {
2013
+ const range = toSlateRange(selection, editor);
2014
+ if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
2015
+ throw new Error("Invalid range");
2016
+ if (range) {
2017
+ if (!(options != null && options.mode) || (options == null ? void 0 : options.mode) === "selected") {
2018
+ debug$i("Deleting content in selection"), slate.Transforms.delete(editor, {
2019
+ at: range,
2020
+ hanging: !0,
2021
+ voids: !0
2022
+ }), editor.onChange();
2023
+ return;
2024
+ }
2025
+ (options == null ? void 0 : options.mode) === "blocks" && (debug$i("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
2026
+ at: range,
2027
+ voids: !0,
2028
+ match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && slate.Element.isElement(node)
2029
+ })), (options == null ? void 0 : options.mode) === "children" && (debug$i("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
2030
+ at: range,
2031
+ voids: !0,
2032
+ match: (node) => node._type === types$1.span.name || // Text children
2033
+ !editor.isTextBlock(node) && slate.Element.isElement(node)
2034
+ })), editor.children.length === 0 && (editor.children = [editor.pteCreateEmptyBlock()]), editor.onChange();
2035
+ }
2036
+ }
2037
+ },
2038
+ removeAnnotation: (type) => {
2039
+ let { selection } = editor;
2040
+ if (debug$i("Removing annotation", type), selection) {
2041
+ if (slate.Range.isCollapsed(selection)) {
2042
+ const [node, nodePath] = slate.Editor.node(editor, selection, { depth: 2 });
2043
+ slate.Text.isText(node) && node.marks && typeof node.text == "string" && (slate.Transforms.select(editor, nodePath), selection = editor.selection);
2044
+ }
2045
+ slate.Editor.withoutNormalizing(editor, () => {
2046
+ if (selection && slate.Range.isExpanded(selection)) {
2047
+ if (selection = editor.selection, !selection)
2048
+ return;
2049
+ [
2050
+ ...slate.Editor.nodes(editor, {
2051
+ at: selection,
2052
+ match: (node) => editor.isTextBlock(node) && Array.isArray(node.markDefs) && node.markDefs.some((def) => def._type === type.name)
2053
+ })
2054
+ ].forEach(([block]) => {
2055
+ editor.isTextBlock(block) && Array.isArray(block.markDefs) && block.markDefs.filter((def) => def._type === type.name).forEach((def) => {
2056
+ slate.Editor.removeMark(editor, def._key);
2057
+ });
2058
+ });
2059
+ }
2060
+ }), slate.Editor.normalize(editor), editor.onChange();
2061
+ }
2062
+ },
2063
+ getSelection: () => {
2064
+ let ptRange = null;
2065
+ if (editor.selection) {
2066
+ const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
2067
+ if (existing)
2068
+ return existing;
2069
+ ptRange = toPortableTextRange(
2070
+ fromSlateValue(editor.children, types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
2071
+ editor.selection,
2072
+ types$1
2073
+ ), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
2074
+ }
2075
+ return ptRange;
2076
+ },
2077
+ getValue: () => fromSlateValue(editor.children, types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
2078
+ isCollapsedSelection: () => !!editor.selection && slate.Range.isCollapsed(editor.selection),
2079
+ isExpandedSelection: () => !!editor.selection && slate.Range.isExpanded(editor.selection),
2080
+ insertBreak: () => {
2081
+ editor.insertBreak(), editor.onChange();
2082
+ },
2083
+ getFragment: () => fromSlateValue(editor.getFragment(), types$1.block.name),
2084
+ isSelectionsOverlapping: (selectionA, selectionB) => {
2085
+ const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
2086
+ return slate.Range.isRange(rangeA) && slate.Range.isRange(rangeB) && slate.Range.includes(rangeA, rangeB);
2087
+ }
2088
+ }), editor;
1592
2089
  };
1593
2090
  }
1594
- function doLineModeDiff(textA, textB, opts) {
1595
- let text1 = textA, text2 = textB;
1596
- const a = linesToChars(text1, text2);
1597
- text1 = a.chars1, text2 = a.chars2;
1598
- const linearray = a.lineArray;
1599
- let diffs = doDiff(text1, text2, {
1600
- checkLines: !1,
1601
- deadline: opts.deadline
1602
- });
1603
- charsToLines(diffs, linearray), diffs = cleanupSemantic(diffs), diffs.push([DIFF_EQUAL, ""]);
1604
- let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "";
1605
- for (; pointer < diffs.length; ) {
1606
- switch (diffs[pointer][0]) {
1607
- case DIFF_INSERT:
1608
- countInsert++, textInsert += diffs[pointer][1];
1609
- break;
1610
- case DIFF_DELETE:
1611
- countDelete++, textDelete += diffs[pointer][1];
1612
- break;
1613
- case DIFF_EQUAL:
1614
- if (countDelete >= 1 && countInsert >= 1) {
1615
- diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert), pointer = pointer - countDelete - countInsert;
1616
- const aa = doDiff(textDelete, textInsert, {
1617
- checkLines: !1,
1618
- deadline: opts.deadline
1619
- });
1620
- for (let j = aa.length - 1; j >= 0; j--)
1621
- diffs.splice(pointer, 0, aa[j]);
1622
- pointer += aa.length;
2091
+ function createWithInsertBreak(types2) {
2092
+ return function(editor) {
2093
+ const { insertBreak } = editor;
2094
+ return editor.insertBreak = () => {
2095
+ if (editor.selection) {
2096
+ const focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = slate.Node.descendant(editor, focusBlockPath);
2097
+ if (editor.isTextBlock(focusBlock)) {
2098
+ const [, end] = slate.Range.edges(editor.selection), isEndAtStartOfNode = slate.Editor.isStart(editor, end, end.path), isEmptyTextBlock = focusBlock && isEqualToEmptyEditor([focusBlock], types2);
2099
+ if (isEndAtStartOfNode && !isEmptyTextBlock) {
2100
+ slate.Editor.insertNode(editor, editor.pteCreateEmptyBlock());
2101
+ const [nextBlockPath] = slate.Path.next(focusBlockPath);
2102
+ slate.Transforms.select(editor, {
2103
+ anchor: { path: [nextBlockPath, 0], offset: 0 },
2104
+ focus: { path: [nextBlockPath, 0], offset: 0 }
2105
+ }), editor.onChange();
2106
+ return;
2107
+ }
1623
2108
  }
1624
- countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
1625
- break;
1626
- default:
1627
- throw new Error("Unknown diff operation.");
1628
- }
1629
- pointer++;
1630
- }
1631
- return diffs.pop(), diffs;
1632
- }
1633
- function computeDiff(text1, text2, opts) {
1634
- let diffs;
1635
- if (!text1)
1636
- return [[DIFF_INSERT, text2]];
1637
- if (!text2)
1638
- return [[DIFF_DELETE, text1]];
1639
- const longtext = text1.length > text2.length ? text1 : text2, shorttext = text1.length > text2.length ? text2 : text1, i = longtext.indexOf(shorttext);
1640
- if (i !== -1)
1641
- return diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]], text1.length > text2.length && (diffs[0][0] = DIFF_DELETE, diffs[2][0] = DIFF_DELETE), diffs;
1642
- if (shorttext.length === 1)
1643
- return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1644
- const halfMatch = findHalfMatch(text1, text2);
1645
- if (halfMatch) {
1646
- const text1A = halfMatch[0], text1B = halfMatch[1], text2A = halfMatch[2], text2B = halfMatch[3], midCommon = halfMatch[4], diffsA = doDiff(text1A, text2A, opts), diffsB = doDiff(text1B, text2B, opts);
1647
- return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
1648
- }
1649
- return opts.checkLines && text1.length > 100 && text2.length > 100 ? doLineModeDiff(text1, text2, opts) : bisect(text1, text2, opts.deadline);
1650
- }
1651
- const DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0;
1652
- function diff(textA, textB, opts) {
1653
- if (textA === null || textB === null)
1654
- throw new Error("Null input. (diff)");
1655
- const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));
1656
- return adjustDiffForSurrogatePairs(diffs), diffs;
1657
- }
1658
- function doDiff(textA, textB, options) {
1659
- let text1 = textA, text2 = textB;
1660
- if (text1 === text2)
1661
- return text1 ? [[DIFF_EQUAL, text1]] : [];
1662
- let commonlength = getCommonPrefix(text1, text2);
1663
- const commonprefix = text1.substring(0, commonlength);
1664
- text1 = text1.substring(commonlength), text2 = text2.substring(commonlength), commonlength = getCommonSuffix(text1, text2);
1665
- const commonsuffix = text1.substring(text1.length - commonlength);
1666
- text1 = text1.substring(0, text1.length - commonlength), text2 = text2.substring(0, text2.length - commonlength);
1667
- let diffs = computeDiff(text1, text2, options);
1668
- return commonprefix && diffs.unshift([DIFF_EQUAL, commonprefix]), commonsuffix && diffs.push([DIFF_EQUAL, commonsuffix]), diffs = cleanupMerge(diffs), diffs;
1669
- }
1670
- function createDeadLine(timeout) {
1671
- let t = 1;
1672
- return typeof timeout < "u" && (t = timeout <= 0 ? Number.MAX_VALUE : timeout), Date.now() + t * 1e3;
1673
- }
1674
- function createInternalOpts(opts) {
1675
- return {
1676
- checkLines: !0,
1677
- deadline: createDeadLine(opts.timeout || 1),
1678
- ...opts
2109
+ }
2110
+ insertBreak();
2111
+ }, editor;
1679
2112
  };
1680
2113
  }
1681
- function combineChar(data, char, dir) {
1682
- return dir === 1 ? data + char : char + data;
2114
+ function createWithMaxBlocks(maxBlocks) {
2115
+ return function(editor) {
2116
+ const { apply: apply2 } = editor;
2117
+ return editor.apply = (operation) => {
2118
+ const rows = maxBlocks;
2119
+ rows > 0 && editor.children.length >= rows && (operation.type === "insert_node" || operation.type === "split_node") && operation.path.length === 1 || apply2(operation);
2120
+ }, editor;
2121
+ };
1683
2122
  }
1684
- function splitChar(data, dir) {
1685
- return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];
2123
+ const PRESERVE_KEYS = /* @__PURE__ */ new WeakMap();
2124
+ function withPreserveKeys(editor, fn) {
2125
+ const prev = isPreservingKeys(editor);
2126
+ PRESERVE_KEYS.set(editor, !0), fn(), PRESERVE_KEYS.set(editor, prev);
1686
2127
  }
1687
- function hasSharedChar(diffs, i, j, dir) {
1688
- return dir === 1 ? diffs[i][1][diffs[i][1].length - 1] === diffs[j][1][diffs[j][1].length - 1] : diffs[i][1][0] === diffs[j][1][0];
2128
+ function isPreservingKeys(editor) {
2129
+ return PRESERVE_KEYS.get(editor);
1689
2130
  }
1690
- function deisolateChar(diffs, i, dir) {
1691
- const inv = dir === 1 ? -1 : 1;
1692
- let insertIdx = null, deleteIdx = null, j = i + dir;
1693
- for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {
1694
- const [op, text2] = diffs[j];
1695
- if (text2.length !== 0) {
1696
- if (op === DIFF_INSERT) {
1697
- insertIdx === null && (insertIdx = j);
1698
- continue;
1699
- } else if (op === DIFF_DELETE) {
1700
- deleteIdx === null && (deleteIdx = j);
1701
- continue;
1702
- } else if (op === DIFF_EQUAL) {
1703
- if (insertIdx === null && deleteIdx === null) {
1704
- const [rest, char2] = splitChar(diffs[i][1], dir);
1705
- diffs[i][1] = rest, diffs[j][1] = combineChar(diffs[j][1], char2, inv);
1706
- return;
1707
- }
1708
- break;
2131
+ function createWithObjectKeys(schemaTypes, keyGenerator) {
2132
+ return function(editor) {
2133
+ PRESERVE_KEYS.set(editor, !1);
2134
+ const { apply: apply2, normalizeNode } = editor;
2135
+ return editor.apply = (operation) => {
2136
+ if (operation.type === "split_node") {
2137
+ const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.properties);
2138
+ operation.properties = {
2139
+ ...operation.properties,
2140
+ ...withNewKey ? { _key: keyGenerator() } : {}
2141
+ };
1709
2142
  }
1710
- }
1711
- }
1712
- if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {
1713
- const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv), [deleteText] = splitChar(diffs[deleteIdx][1], inv);
1714
- diffs[insertIdx][1] = insertText, diffs[deleteIdx][1] = deleteText, diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);
1715
- return;
1716
- }
1717
- const [text, char] = splitChar(diffs[i][1], dir);
1718
- diffs[i][1] = text, insertIdx === null ? (diffs.splice(j, 0, [DIFF_INSERT, char]), deleteIdx !== null && deleteIdx >= j && deleteIdx++) : diffs[insertIdx][1] = combineChar(diffs[insertIdx][1], char, inv), deleteIdx === null ? diffs.splice(j, 0, [DIFF_DELETE, char]) : diffs[deleteIdx][1] = combineChar(diffs[deleteIdx][1], char, inv);
1719
- }
1720
- function adjustDiffForSurrogatePairs(diffs) {
1721
- for (let i = 0; i < diffs.length; i++) {
1722
- const [diffType, diffText] = diffs[i];
1723
- if (diffText.length === 0) continue;
1724
- const firstChar = diffText[0], lastChar = diffText[diffText.length - 1];
1725
- isHighSurrogate(lastChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, 1), isLowSurrogate(firstChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, -1);
1726
- }
1727
- for (let i = 0; i < diffs.length; i++)
1728
- diffs[i][1].length === 0 && diffs.splice(i, 1);
1729
- }
1730
- const DEFAULT_OPTIONS = {
1731
- /**
1732
- * At what point is no match declared (0.0 = perfection, 1.0 = very loose).
1733
- */
1734
- threshold: 0.5,
1735
- /**
1736
- * How far to search for a match (0 = exact location, 1000+ = broad match).
1737
- * A match this many characters away from the expected location will add
1738
- * 1.0 to the score (0.0 is a perfect match).
1739
- */
1740
- distance: 1e3
1741
- };
1742
- function applyDefaults(options) {
1743
- return {
1744
- ...DEFAULT_OPTIONS,
1745
- ...options
1746
- };
1747
- }
1748
- const MAX_BITS$1 = 32;
1749
- function bitap(text, pattern, loc) {
1750
- let opts = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1751
- if (pattern.length > MAX_BITS$1)
1752
- throw new Error("Pattern too long for this browser.");
1753
- const options = applyDefaults(opts), s = getAlphabetFromPattern(pattern);
1754
- function getBitapScore(e, x) {
1755
- const accuracy = e / pattern.length, proximity = Math.abs(loc - x);
1756
- return options.distance ? accuracy + proximity / options.distance : proximity ? 1 : accuracy;
1757
- }
1758
- let scoreThreshold = options.threshold, bestLoc = text.indexOf(pattern, loc);
1759
- bestLoc !== -1 && (scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold), bestLoc = text.lastIndexOf(pattern, loc + pattern.length), bestLoc !== -1 && (scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold)));
1760
- const matchmask = 1 << pattern.length - 1;
1761
- bestLoc = -1;
1762
- let binMin, binMid, binMax = pattern.length + text.length, lastRd = [];
1763
- for (let d = 0; d < pattern.length; d++) {
1764
- for (binMin = 0, binMid = binMax; binMin < binMid; )
1765
- getBitapScore(d, loc + binMid) <= scoreThreshold ? binMin = binMid : binMax = binMid, binMid = Math.floor((binMax - binMin) / 2 + binMin);
1766
- binMax = binMid;
1767
- let start = Math.max(1, loc - binMid + 1);
1768
- const finish = Math.min(loc + binMid, text.length) + pattern.length, rd = new Array(finish + 2);
1769
- rd[finish + 1] = (1 << d) - 1;
1770
- for (let j = finish; j >= start; j--) {
1771
- const charMatch = s[text.charAt(j - 1)];
1772
- if (d === 0 ? rd[j] = (rd[j + 1] << 1 | 1) & charMatch : rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((lastRd[j + 1] | lastRd[j]) << 1 | 1) | lastRd[j + 1], rd[j] & matchmask) {
1773
- const score = getBitapScore(d, j - 1);
1774
- if (score <= scoreThreshold)
1775
- if (scoreThreshold = score, bestLoc = j - 1, bestLoc > loc)
1776
- start = Math.max(1, 2 * loc - bestLoc);
1777
- else
1778
- break;
2143
+ if (operation.type === "insert_node") {
2144
+ const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.node);
2145
+ slate.Editor.isEditor(operation.node) || (operation.node = {
2146
+ ...operation.node,
2147
+ ...withNewKey ? { _key: keyGenerator() } : {}
2148
+ });
1779
2149
  }
1780
- }
1781
- if (getBitapScore(d + 1, loc) > scoreThreshold)
1782
- break;
1783
- lastRd = rd;
1784
- }
1785
- return bestLoc;
1786
- }
1787
- function getAlphabetFromPattern(pattern) {
1788
- const s = {};
1789
- for (let i = 0; i < pattern.length; i++)
1790
- s[pattern.charAt(i)] = 0;
1791
- for (let i = 0; i < pattern.length; i++)
1792
- s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;
1793
- return s;
2150
+ apply2(operation);
2151
+ }, editor.normalizeNode = (entry) => {
2152
+ const [node, path] = entry;
2153
+ if (slate.Element.isElement(node) && node._type === schemaTypes.block.name) {
2154
+ node._key || slate.Transforms.setNodes(editor, { _key: keyGenerator() }, { at: path });
2155
+ for (const [child, childPath] of slate.Node.children(editor, path))
2156
+ if (!child._key) {
2157
+ slate.Transforms.setNodes(editor, { _key: keyGenerator() }, { at: childPath });
2158
+ return;
2159
+ }
2160
+ }
2161
+ normalizeNode(entry);
2162
+ }, editor;
2163
+ };
1794
2164
  }
1795
- function match(text, pattern, searchLocation) {
1796
- if (text === null || pattern === null || searchLocation === null)
1797
- throw new Error("Null input. (match())");
1798
- const loc = Math.max(0, Math.min(searchLocation, text.length));
1799
- if (text === pattern)
1800
- return 0;
1801
- if (text.length) {
1802
- if (text.substring(loc, loc + pattern.length) === pattern)
1803
- return loc;
1804
- } else return -1;
1805
- return bitap(text, pattern, loc);
2165
+ const BEFORE = "before", AFTER = "after";
2166
+ function insert(array, position, index, ...args) {
2167
+ if (position !== BEFORE && position !== AFTER)
2168
+ throw new Error(`Invalid position "${position}", must be either ${BEFORE} or ${AFTER}`);
2169
+ const items = flatten(...args);
2170
+ if (array.length === 0)
2171
+ return items;
2172
+ const len = array.length, idx = Math.abs((len + index) % len) % len, normalizedIdx = position === "after" ? idx + 1 : idx, copy = array.slice();
2173
+ return copy.splice(normalizedIdx, 0, ...flatten(items)), copy;
1806
2174
  }
1807
- function createPatchObject(start1, start2) {
1808
- return {
1809
- diffs: [],
1810
- start1,
1811
- start2,
1812
- utf8Start1: start1,
1813
- utf8Start2: start2,
1814
- length1: 0,
1815
- length2: 0,
1816
- utf8Length1: 0,
1817
- utf8Length2: 0
1818
- };
2175
+ function flatten(...values) {
2176
+ return values.reduce((prev, item) => prev.concat(item), []);
1819
2177
  }
1820
- function diffText1(diffs) {
1821
- const text = [];
1822
- for (let x = 0; x < diffs.length; x++)
1823
- diffs[x][0] !== DIFF_INSERT && (text[x] = diffs[x][1]);
1824
- return text.join("");
2178
+ const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
2179
+ function move(arr, from, to) {
2180
+ const nextValue = arr.slice(), val = nextValue[from];
2181
+ return nextValue.splice(from, 1), nextValue.splice(to, 0, val), nextValue;
1825
2182
  }
1826
- function diffText2(diffs) {
1827
- const text = [];
1828
- for (let x = 0; x < diffs.length; x++)
1829
- diffs[x][0] !== DIFF_DELETE && (text[x] = diffs[x][1]);
1830
- return text.join("");
2183
+ function findTargetIndex(array, pathSegment) {
2184
+ if (typeof pathSegment == "number")
2185
+ return pathSegment;
2186
+ const index = findIndex__default.default(array, pathSegment);
2187
+ return index === -1 ? !1 : index;
1831
2188
  }
1832
- function countUtf8Bytes(str) {
1833
- let bytes = 0;
1834
- for (let i = 0; i < str.length; i++) {
1835
- const codePoint = str.codePointAt(i);
1836
- if (typeof codePoint > "u")
1837
- throw new Error("Failed to get codepoint");
1838
- bytes += utf8len(codePoint);
2189
+ function apply$3(value, patch) {
2190
+ const nextValue = value.slice();
2191
+ if (patch.path.length === 0) {
2192
+ if (patch.type === "setIfMissing") {
2193
+ if (!Array.isArray(patch.value))
2194
+ throw new Error("Cannot set value of an array to a non-array");
2195
+ return value === void 0 ? patch.value : value;
2196
+ } else if (patch.type === "set") {
2197
+ if (!Array.isArray(patch.value))
2198
+ throw new Error("Cannot set value of an array to a non-array");
2199
+ return patch.value;
2200
+ } else {
2201
+ if (patch.type === "unset")
2202
+ return;
2203
+ if (patch.type === "move") {
2204
+ if (!patch.value || !hasOwn(patch.value, "from") || !hasOwn(patch.value, "to"))
2205
+ throw new Error(
2206
+ `Invalid value of 'move' patch. Expected a value with "from" and "to" indexes, instead got: ${JSON.stringify(
2207
+ patch.value
2208
+ )}`
2209
+ );
2210
+ return move(nextValue, patch.value.from, patch.value.to);
2211
+ }
2212
+ }
2213
+ throw new Error(`Invalid array operation: ${patch.type}`);
1839
2214
  }
1840
- return bytes;
1841
- }
1842
- function adjustIndiciesToUcs2(patches, base) {
1843
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, byteOffset = 0, idx = 0;
1844
- function advanceTo(target) {
1845
- for (; byteOffset < target; ) {
1846
- const codePoint = base.codePointAt(idx);
1847
- if (typeof codePoint > "u")
1848
- return idx;
1849
- byteOffset += utf8len(codePoint), codePoint > 65535 ? idx += 2 : idx += 1;
2215
+ const [head, ...tail] = patch.path, index = findTargetIndex(value, head);
2216
+ if (index === !1)
2217
+ return nextValue;
2218
+ if (tail.length === 0) {
2219
+ if (patch.type === "insert") {
2220
+ const { position, items } = patch;
2221
+ return insert(value, position, index, items);
2222
+ } else if (patch.type === "unset") {
2223
+ if (typeof index != "number")
2224
+ throw new Error(`Expected array index to be a number, instead got "${index}"`);
2225
+ return nextValue.splice(index, 1), nextValue;
1850
2226
  }
1851
- if (!options.allowExceedingIndices && byteOffset !== target)
1852
- throw new Error("Failed to determine byte offset");
1853
- return idx;
1854
2227
  }
1855
- const adjusted = [];
1856
- for (const patch of patches)
1857
- adjusted.push({
1858
- diffs: patch.diffs.map((diff2) => cloneDiff(diff2)),
1859
- start1: advanceTo(patch.start1),
1860
- start2: advanceTo(patch.start2),
1861
- utf8Start1: patch.utf8Start1,
1862
- utf8Start2: patch.utf8Start2,
1863
- length1: patch.length1,
1864
- length2: patch.length2,
1865
- utf8Length1: patch.utf8Length1,
1866
- utf8Length2: patch.utf8Length2
1867
- });
1868
- return adjusted;
1869
- }
1870
- function utf8len(codePoint) {
1871
- return codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
2228
+ return nextValue[index] = _apply(nextValue[index], {
2229
+ ...patch,
2230
+ path: tail
2231
+ }), nextValue;
1872
2232
  }
1873
- const MAX_BITS = 32, DEFAULT_MARGIN = 4;
1874
- function levenshtein(diffs) {
1875
- let leven = 0, insertions = 0, deletions = 0;
1876
- for (let x = 0; x < diffs.length; x++) {
1877
- const op = diffs[x][0], data = diffs[x][1];
1878
- switch (op) {
1879
- case DIFF_INSERT:
1880
- insertions += data.length;
1881
- break;
1882
- case DIFF_DELETE:
1883
- deletions += data.length;
1884
- break;
1885
- case DIFF_EQUAL:
1886
- leven += Math.max(insertions, deletions), insertions = 0, deletions = 0;
1887
- break;
1888
- default:
1889
- throw new Error("Unknown diff operation.");
2233
+ function apply$2(value, patch) {
2234
+ const nextValue = clone__default.default(value);
2235
+ if (patch.path.length === 0) {
2236
+ if (patch.type === "set") {
2237
+ if (!isObject__default.default(patch.value))
2238
+ throw new Error("Cannot set value of an object to a non-object");
2239
+ return patch.value;
2240
+ } else {
2241
+ if (patch.type === "unset")
2242
+ return;
2243
+ if (patch.type === "setIfMissing")
2244
+ return value === void 0 ? patch.value : value;
1890
2245
  }
2246
+ throw new Error(`Invalid object operation: ${patch.type}`);
1891
2247
  }
1892
- return leven += Math.max(insertions, deletions), leven;
1893
- }
1894
- function xIndex(diffs, loc) {
1895
- let chars1 = 0, chars2 = 0, lastChars1 = 0, lastChars2 = 0, x;
1896
- for (x = 0; x < diffs.length && (diffs[x][0] !== DIFF_INSERT && (chars1 += diffs[x][1].length), diffs[x][0] !== DIFF_DELETE && (chars2 += diffs[x][1].length), !(chars1 > loc)); x++)
1897
- lastChars1 = chars1, lastChars2 = chars2;
1898
- return diffs.length !== x && diffs[x][0] === DIFF_DELETE ? lastChars2 : lastChars2 + (loc - lastChars1);
2248
+ const [head, ...tail] = patch.path;
2249
+ if (typeof head != "string")
2250
+ throw new Error(`Expected field name to be a string, instad got: ${head}`);
2251
+ return tail.length === 0 && patch.type === "unset" ? omit__default.default(nextValue, head) : (nextValue[head] = _apply(nextValue[head], {
2252
+ ...patch,
2253
+ path: tail
2254
+ }), nextValue);
1899
2255
  }
1900
- function addPadding(patches) {
1901
- const paddingLength = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1902
- let nullPadding = "";
1903
- for (let x = 1; x <= paddingLength; x++)
1904
- nullPadding += String.fromCharCode(x);
1905
- for (const p of patches)
1906
- p.start1 += paddingLength, p.start2 += paddingLength, p.utf8Start1 += paddingLength, p.utf8Start2 += paddingLength;
1907
- let patch = patches[0], diffs = patch.diffs;
1908
- if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL)
1909
- diffs.unshift([DIFF_EQUAL, nullPadding]), patch.start1 -= paddingLength, patch.start2 -= paddingLength, patch.utf8Start1 -= paddingLength, patch.utf8Start2 -= paddingLength, patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
1910
- else if (paddingLength > diffs[0][1].length) {
1911
- const firstDiffLength = diffs[0][1].length, extraLength = paddingLength - firstDiffLength;
1912
- diffs[0][1] = nullPadding.substring(firstDiffLength) + diffs[0][1], patch.start1 -= extraLength, patch.start2 -= extraLength, patch.utf8Start1 -= extraLength, patch.utf8Start2 -= extraLength, patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
1913
- }
1914
- if (patch = patches[patches.length - 1], diffs = patch.diffs, diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL)
1915
- diffs.push([DIFF_EQUAL, nullPadding]), patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
1916
- else if (paddingLength > diffs[diffs.length - 1][1].length) {
1917
- const extraLength = paddingLength - diffs[diffs.length - 1][1].length;
1918
- diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength), patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
2256
+ const OPERATIONS$1 = {
2257
+ replace(_currentValue, nextValue) {
2258
+ return nextValue;
2259
+ },
2260
+ set(_currentValue, nextValue) {
2261
+ return nextValue;
2262
+ },
2263
+ setIfMissing(currentValue, nextValue) {
2264
+ return currentValue === void 0 ? nextValue : currentValue;
2265
+ },
2266
+ unset(_currentValue, _nextValue) {
2267
+ },
2268
+ inc(currentValue, nextValue) {
2269
+ return currentValue + nextValue;
2270
+ },
2271
+ dec(currentValue, nextValue) {
2272
+ return currentValue - nextValue;
1919
2273
  }
1920
- return nullPadding;
2274
+ }, SUPPORTED_PATCH_TYPES$1 = Object.keys(OPERATIONS$1);
2275
+ function apply$1(value, patch) {
2276
+ if (!SUPPORTED_PATCH_TYPES$1.includes(patch.type))
2277
+ throw new Error(
2278
+ `Received patch of unsupported type: "${JSON.stringify(
2279
+ patch.type
2280
+ )}" for primitives. This is most likely a bug.`
2281
+ );
2282
+ if (patch.path.length > 0)
2283
+ throw new Error(
2284
+ `Cannot apply deep operations on primitive values. Received patch with type "${patch.type}" and path "${patch.path.map((path) => JSON.stringify(path)).join(".")} that targeted the value "${JSON.stringify(value)}"`
2285
+ );
2286
+ return OPERATIONS$1[patch.type](value, patch.value);
1921
2287
  }
1922
- function splitMax(patches) {
1923
- let margin = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1924
- const patchSize = MAX_BITS;
1925
- for (let x = 0; x < patches.length; x++) {
1926
- if (patches[x].length1 <= patchSize)
1927
- continue;
1928
- const bigpatch = patches[x];
1929
- patches.splice(x--, 1);
1930
- let start1 = bigpatch.start1, start2 = bigpatch.start2, preContext = "";
1931
- for (; bigpatch.diffs.length !== 0; ) {
1932
- const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);
1933
- let empty = !0;
1934
- if (preContext !== "") {
1935
- const precontextByteCount = countUtf8Bytes(preContext);
1936
- patch.length1 = preContext.length, patch.utf8Length1 = precontextByteCount, patch.length2 = preContext.length, patch.utf8Length2 = precontextByteCount, patch.diffs.push([DIFF_EQUAL, preContext]);
1937
- }
1938
- for (; bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin; ) {
1939
- const diffType = bigpatch.diffs[0][0];
1940
- let diffText = bigpatch.diffs[0][1], diffTextByteCount = countUtf8Bytes(diffText);
1941
- if (diffType === DIFF_INSERT) {
1942
- patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length;
1943
- const diff2 = bigpatch.diffs.shift();
1944
- diff2 && patch.diffs.push(diff2), empty = !1;
1945
- } else diffType === DIFF_DELETE && patch.diffs.length === 1 && patch.diffs[0][0] === DIFF_EQUAL && diffText.length > 2 * patchSize ? (patch.length1 += diffText.length, patch.utf8Length1 += diffTextByteCount, start1 += diffText.length, empty = !1, patch.diffs.push([diffType, diffText]), bigpatch.diffs.shift()) : (diffText = diffText.substring(0, patchSize - patch.length1 - margin), diffTextByteCount = countUtf8Bytes(diffText), patch.length1 += diffText.length, patch.utf8Length1 += diffTextByteCount, start1 += diffText.length, diffType === DIFF_EQUAL ? (patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length) : empty = !1, patch.diffs.push([diffType, diffText]), diffText === bigpatch.diffs[0][1] ? bigpatch.diffs.shift() : bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diffText.length));
1946
- }
1947
- preContext = diffText2(patch.diffs), preContext = preContext.substring(preContext.length - margin);
1948
- const postContext = diffText1(bigpatch.diffs).substring(0, margin), postContextByteCount = countUtf8Bytes(postContext);
1949
- postContext !== "" && (patch.length1 += postContext.length, patch.length2 += postContext.length, patch.utf8Length1 += postContextByteCount, patch.utf8Length2 += postContextByteCount, patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL ? patch.diffs[patch.diffs.length - 1][1] += postContext : patch.diffs.push([DIFF_EQUAL, postContext])), empty || patches.splice(++x, 0, patch);
1950
- }
2288
+ const OPERATIONS = {
2289
+ replace(_currentValue, nextValue) {
2290
+ return nextValue;
2291
+ },
2292
+ set(_currentValue, nextValue) {
2293
+ return nextValue;
2294
+ },
2295
+ setIfMissing(currentValue, nextValue) {
2296
+ return currentValue === void 0 ? nextValue : currentValue;
2297
+ },
2298
+ unset(_currentValue, _nextValue) {
2299
+ },
2300
+ diffMatchPatch(currentValue, nextValue) {
2301
+ const [result] = apply$4(parse(nextValue), currentValue, {
2302
+ allowExceedingIndices: !0
2303
+ });
2304
+ return result;
1951
2305
  }
2306
+ }, SUPPORTED_PATCH_TYPES = Object.keys(OPERATIONS);
2307
+ function apply(value, patch) {
2308
+ if (!SUPPORTED_PATCH_TYPES.includes(patch.type))
2309
+ throw new Error(
2310
+ `Received patch of unsupported type: "${JSON.stringify(
2311
+ patch.type
2312
+ )}" for string. This is most likely a bug.`
2313
+ );
2314
+ if (patch.path.length > 0)
2315
+ throw new Error(
2316
+ `Cannot apply deep operations on string values. Received patch with type "${patch.type}" and path "${patch.path.join(".")} that targeted the value "${JSON.stringify(value)}"`
2317
+ );
2318
+ const func = OPERATIONS[patch.type];
2319
+ if (func)
2320
+ return func(value, patch.value);
2321
+ throw new Error("Unknown patch type");
1952
2322
  }
1953
- function apply(patches, originalText) {
1954
- let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1955
- if (typeof patches == "string")
1956
- throw new Error("Patches must be an array - pass the patch to `parsePatch()` first");
1957
- let text = originalText;
1958
- if (patches.length === 0)
1959
- return [text, []];
1960
- const parsed = adjustIndiciesToUcs2(patches, text, {
1961
- allowExceedingIndices: opts.allowExceedingIndices
1962
- }), margin = opts.margin || DEFAULT_MARGIN, deleteThreshold = opts.deleteThreshold || 0.4, nullPadding = addPadding(parsed, margin);
1963
- text = nullPadding + text + nullPadding, splitMax(parsed, margin);
1964
- let delta = 0;
1965
- const results = [];
1966
- for (let x = 0; x < parsed.length; x++) {
1967
- const expectedLoc = parsed[x].start2 + delta, text1 = diffText1(parsed[x].diffs);
1968
- let startLoc, endLoc = -1;
1969
- if (text1.length > MAX_BITS ? (startLoc = match(text, text1.substring(0, MAX_BITS), expectedLoc), startLoc !== -1 && (endLoc = match(text, text1.substring(text1.length - MAX_BITS), expectedLoc + text1.length - MAX_BITS), (endLoc === -1 || startLoc >= endLoc) && (startLoc = -1))) : startLoc = match(text, text1, expectedLoc), startLoc === -1)
1970
- results[x] = !1, delta -= parsed[x].length2 - parsed[x].length1;
1971
- else {
1972
- results[x] = !0, delta = startLoc - expectedLoc;
1973
- let text2;
1974
- if (endLoc === -1 ? text2 = text.substring(startLoc, startLoc + text1.length) : text2 = text.substring(startLoc, endLoc + MAX_BITS), text1 === text2)
1975
- text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);
1976
- else {
1977
- let diffs = diff(text1, text2, {
1978
- checkLines: !1
1979
- });
1980
- if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold)
1981
- results[x] = !1;
1982
- else {
1983
- diffs = cleanupSemanticLossless(diffs);
1984
- let index1 = 0, index2 = 0;
1985
- for (let y = 0; y < parsed[x].diffs.length; y++) {
1986
- const mod = parsed[x].diffs[y];
1987
- mod[0] !== DIFF_EQUAL && (index2 = xIndex(diffs, index1)), mod[0] === DIFF_INSERT ? text = text.substring(0, startLoc + index2) + mod[1] + text.substring(startLoc + index2) : mod[0] === DIFF_DELETE && (text = text.substring(0, startLoc + index2) + text.substring(startLoc + xIndex(diffs, index1 + mod[1].length))), mod[0] !== DIFF_DELETE && (index1 += mod[1].length);
1988
- }
1989
- }
1990
- }
1991
- }
1992
- }
1993
- return text = text.substring(nullPadding.length, text.length - nullPadding.length), [text, results];
2323
+ function applyAll(value, patches) {
2324
+ return patches.reduce(_apply, value);
1994
2325
  }
1995
- const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
1996
- function parse(textline) {
1997
- if (!textline)
1998
- return [];
1999
- const patches = [], lines = textline.split(`
2000
- `);
2001
- let textPointer = 0;
2002
- for (; textPointer < lines.length; ) {
2003
- const m = lines[textPointer].match(patchHeader);
2004
- if (!m)
2005
- throw new Error("Invalid patch string: ".concat(lines[textPointer]));
2006
- const patch = createPatchObject(toInt(m[1]), toInt(m[3]));
2007
- for (patches.push(patch), m[2] === "" ? (patch.start1--, patch.utf8Start1--, patch.length1 = 1, patch.utf8Length1 = 1) : m[2] === "0" ? (patch.length1 = 0, patch.utf8Length1 = 0) : (patch.start1--, patch.utf8Start1--, patch.utf8Length1 = toInt(m[2]), patch.length1 = patch.utf8Length1), m[4] === "" ? (patch.start2--, patch.utf8Start2--, patch.length2 = 1, patch.utf8Length2 = 1) : m[4] === "0" ? (patch.length2 = 0, patch.utf8Length2 = 0) : (patch.start2--, patch.utf8Start2--, patch.utf8Length2 = toInt(m[4]), patch.length2 = patch.utf8Length2), textPointer++; textPointer < lines.length; ) {
2008
- const currentLine = lines[textPointer], sign = currentLine.charAt(0);
2009
- if (sign === "@")
2010
- break;
2011
- if (sign === "") {
2012
- textPointer++;
2013
- continue;
2014
- }
2015
- let line;
2016
- try {
2017
- line = decodeURI(currentLine.slice(1));
2018
- } catch {
2019
- throw new Error("Illegal escape in parse: ".concat(currentLine));
2020
- }
2021
- const utf8Diff = countUtf8Bytes(line) - line.length;
2022
- if (sign === "-")
2023
- patch.diffs.push([DIFF_DELETE, line]), patch.length1 -= utf8Diff;
2024
- else if (sign === "+")
2025
- patch.diffs.push([DIFF_INSERT, line]), patch.length2 -= utf8Diff;
2026
- else if (sign === " ")
2027
- patch.diffs.push([DIFF_EQUAL, line]), patch.length1 -= utf8Diff, patch.length2 -= utf8Diff;
2028
- else
2029
- throw new Error('Invalid patch mode "'.concat(sign, '" in: ').concat(line));
2030
- textPointer++;
2031
- }
2032
- }
2033
- return patches;
2326
+ function applyPatch(value, patch) {
2327
+ return Array.isArray(value) ? apply$3(value, patch) : isString__default.default(value) ? apply(value, patch) : isObject__default.default(value) ? apply$2(value, patch) : apply$1(value, patch);
2034
2328
  }
2035
- function toInt(num) {
2036
- return parseInt(num, 10);
2329
+ function _apply(value, patch) {
2330
+ return applyPatch(value, patch);
2037
2331
  }
2038
2332
  const debug$h = debugWithName("applyPatches"), debugVerbose$3 = debug$h.enabled && !0;
2039
2333
  function createApplyPatch(schemaTypes) {
@@ -2074,7 +2368,7 @@ function diffMatchPatch(editor, patch) {
2074
2368
  return debug$h("Child not found"), !1;
2075
2369
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
2076
2370
  return !1;
2077
- const patches = parse(patch.value), [newValue] = apply(patches, child.text, { allowExceedingIndices: !0 }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
2371
+ const patches = parse(patch.value), [newValue] = apply$4(patches, child.text, { allowExceedingIndices: !0 }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
2078
2372
  debugState(editor, "before");
2079
2373
  let offset = 0;
2080
2374
  for (const [op, text] of diff$1)
@@ -2163,7 +2457,7 @@ function setPatch(editor, patch) {
2163
2457
  });
2164
2458
  });
2165
2459
  } else if (block && "value" in block) {
2166
- const newVal = apply$1.applyAll([block.value], [patch])[0];
2460
+ const newVal = applyAll([block.value], [patch])[0];
2167
2461
  return slate.Transforms.setNodes(editor, { ...block, value: newVal }, { at: blockPath }), !0;
2168
2462
  }
2169
2463
  return debugState(editor, "after"), !0;
@@ -2445,7 +2739,7 @@ function createWithPatches({
2445
2739
  schemaTypes
2446
2740
  }) {
2447
2741
  let previousChildren;
2448
- const applyPatch = createApplyPatch(schemaTypes);
2742
+ const applyPatch2 = createApplyPatch(schemaTypes);
2449
2743
  return function(editor) {
2450
2744
  IS_PROCESSING_REMOTE_CHANGES.set(editor, !1), PATCHING.set(editor, !0), previousChildren = [...editor.children];
2451
2745
  const { apply: apply2 } = editor;
@@ -2462,7 +2756,7 @@ function createWithPatches({
2462
2756
  withoutSaving(editor, () => {
2463
2757
  withPreserveKeys(editor, () => {
2464
2758
  patches.forEach((patch) => {
2465
- debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
2759
+ debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch2(editor, patch);
2466
2760
  });
2467
2761
  });
2468
2762
  });
@@ -2489,7 +2783,7 @@ function createWithPatches({
2489
2783
  const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes);
2490
2784
  if (!isPatching(editor))
2491
2785
  return editor;
2492
- switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches.push(patchEvent.insert(previousChildren, "before", [0])), operation.type) {
2786
+ switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches.push(insert$1(previousChildren, "before", [0])), operation.type) {
2493
2787
  case "insert_text":
2494
2788
  patches = [
2495
2789
  ...patches,
@@ -2539,14 +2833,14 @@ function createWithPatches({
2539
2833
  ];
2540
2834
  break;
2541
2835
  }
2542
- return !editorWasEmpty && editorIsEmpty && ["merge_node", "set_node", "remove_text", "remove_node"].includes(operation.type) && (patches = [...patches, patchEvent.unset([])], change$.next({
2836
+ return !editorWasEmpty && editorIsEmpty && ["merge_node", "set_node", "remove_text", "remove_node"].includes(operation.type) && (patches = [...patches, unset([])], change$.next({
2543
2837
  type: "unset",
2544
2838
  previousValue: fromSlateValue(
2545
2839
  previousChildren,
2546
2840
  schemaTypes.block.name,
2547
2841
  KEY_TO_VALUE_ELEMENT.get(editor)
2548
2842
  )
2549
- })), editorWasEmpty && patches.length > 0 && (patches = [patchEvent.setIfMissing([], []), ...patches]), patches.length > 0 && patches.forEach((patch) => {
2843
+ })), editorWasEmpty && patches.length > 0 && (patches = [setIfMissing([], []), ...patches]), patches.length > 0 && patches.forEach((patch) => {
2550
2844
  change$.next({
2551
2845
  type: "patch",
2552
2846
  patch: { ...patch, origin: "local" }
@@ -2958,7 +3252,7 @@ function createWithSchemaTypes({
2958
3252
  keyGenerator
2959
3253
  }) {
2960
3254
  return function(editor) {
2961
- editor.isTextBlock = (value) => types$1.isPortableTextTextBlock(value) && value._type === schemaTypes.block.name, editor.isTextSpan = (value) => types$1.isPortableTextSpan(value) && value._type == schemaTypes.span.name, editor.isListBlock = (value) => types$1.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;
3255
+ editor.isTextBlock = (value) => types.isPortableTextTextBlock(value) && value._type === schemaTypes.block.name, editor.isTextSpan = (value) => types.isPortableTextSpan(value) && value._type == schemaTypes.span.name, editor.isListBlock = (value) => types.isPortableTextListBlock(value) && value._type === schemaTypes.block.name, editor.isVoid = (element) => schemaTypes.block.name !== element._type && (schemaTypes.blockObjects.map((obj) => obj.name).includes(element._type) || schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type)), editor.isInline = (element) => schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type) && "__inline" in element && element.__inline === !0;
2962
3256
  const { normalizeNode } = editor;
2963
3257
  return editor.normalizeNode = (entry) => {
2964
3258
  const [node, path] = entry;
@@ -3027,7 +3321,7 @@ const debug$7 = debugWithName("plugin:withHotKeys"), DEFAULT_HOTKEYS = {
3027
3321
  },
3028
3322
  custom: {}
3029
3323
  };
3030
- function createWithHotkeys(types2, portableTextEditor, hotkeysFromOptions) {
3324
+ function createWithHotkeys(types$1, portableTextEditor, hotkeysFromOptions) {
3031
3325
  const reservedHotkeys = ["enter", "tab", "shift", "delete", "end"], activeHotkeys = hotkeysFromOptions || DEFAULT_HOTKEYS;
3032
3326
  return function(editor) {
3033
3327
  return editor.pteWithHotKeys = (event) => {
@@ -3078,7 +3372,7 @@ function createWithHotkeys(types2, portableTextEditor, hotkeysFromOptions) {
3078
3372
  }
3079
3373
  }
3080
3374
  if (isBackspace && editor.selection && editor.selection.focus.path[0] === 0 && slate.Range.isCollapsed(editor.selection)) {
3081
- const focusBlock = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1)), nextPath = slate.Path.next(editor.selection.focus.path.slice(0, 1)), nextBlock = slate.Node.has(editor, nextPath), isTextBlock = types$1.isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && ((_b = (_a = focusBlock.children) == null ? void 0 : _a[0]) == null ? void 0 : _b.text) === "";
3375
+ const focusBlock = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1)), nextPath = slate.Path.next(editor.selection.focus.path.slice(0, 1)), nextBlock = slate.Node.has(editor, nextPath), isTextBlock = types.isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && ((_b = (_a = focusBlock.children) == null ? void 0 : _a[0]) == null ? void 0 : _b.text) === "";
3082
3376
  if (nextBlock && isTextBlock && isEmptyFocusBlock) {
3083
3377
  event.preventDefault(), event.stopPropagation(), slate.Transforms.removeNodes(editor, { match: (n) => n === focusBlock }), editor.onChange();
3084
3378
  return;
@@ -3088,7 +3382,7 @@ function createWithHotkeys(types2, portableTextEditor, hotkeysFromOptions) {
3088
3382
  const prevPath = slate.Path.previous(editor.selection.focus.path.slice(0, 1)), prevBlock = slate.Node.descendant(editor, prevPath), focusBlock = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
3089
3383
  if (prevBlock && focusBlock && slate.Editor.isVoid(editor, prevBlock) && editor.selection.focus.offset === 0) {
3090
3384
  debug$7("Preventing deleting void block above"), event.preventDefault(), event.stopPropagation();
3091
- const isTextBlock = types$1.isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && ((_d = (_c = focusBlock.children) == null ? void 0 : _c[0]) == null ? void 0 : _d.text) === "";
3385
+ const isTextBlock = types.isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && ((_d = (_c = focusBlock.children) == null ? void 0 : _c[0]) == null ? void 0 : _d.text) === "";
3092
3386
  if (!isTextBlock || isEmptyFocusBlock) {
3093
3387
  slate.Transforms.removeNodes(editor, { match: (n) => n === focusBlock }), slate.Transforms.select(editor, prevPath), editor.onChange();
3094
3388
  return;
@@ -3111,10 +3405,10 @@ function createWithHotkeys(types2, portableTextEditor, hotkeysFromOptions) {
3111
3405
  }
3112
3406
  }
3113
3407
  if ((isTab || isShiftTab) && editor.selection) {
3114
- const [focusChild] = slate.Editor.node(editor, editor.selection.focus, { depth: 2 }), [focusBlock] = types$1.isPortableTextSpan(focusChild) ? slate.Editor.node(editor, editor.selection.focus, { depth: 1 }) : [], hasAnnotationFocus = focusChild && types$1.isPortableTextTextBlock(focusBlock) && types$1.isPortableTextSpan(focusChild) && (focusChild.marks || []).filter(
3408
+ const [focusChild] = slate.Editor.node(editor, editor.selection.focus, { depth: 2 }), [focusBlock] = types.isPortableTextSpan(focusChild) ? slate.Editor.node(editor, editor.selection.focus, { depth: 1 }) : [], hasAnnotationFocus = focusChild && types.isPortableTextTextBlock(focusBlock) && types.isPortableTextSpan(focusChild) && (focusChild.marks || []).filter(
3115
3409
  (m) => (focusBlock.markDefs || []).map((def) => def._key).includes(m)
3116
3410
  ).length > 0, [start] = slate.Range.edges(editor.selection), atStartOfNode = slate.Editor.isStart(editor, start, start.path);
3117
- focusChild && types$1.isPortableTextSpan(focusChild) && (!hasAnnotationFocus || atStartOfNode) && editor.pteIncrementBlockLevels(isShiftTab) && event.preventDefault();
3411
+ focusChild && types.isPortableTextSpan(focusChild) && (!hasAnnotationFocus || atStartOfNode) && editor.pteIncrementBlockLevels(isShiftTab) && event.preventDefault();
3118
3412
  }
3119
3413
  if (isEnter && !isShiftEnter && editor.selection) {
3120
3414
  const focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = slate.Node.descendant(editor, focusBlockPath);
@@ -3122,7 +3416,7 @@ function createWithHotkeys(types2, portableTextEditor, hotkeysFromOptions) {
3122
3416
  editor.pteEndList() && event.preventDefault();
3123
3417
  return;
3124
3418
  }
3125
- if (editor.isTextBlock(focusBlock) && focusBlock.style && focusBlock.style !== types2.styles[0].value) {
3419
+ if (editor.isTextBlock(focusBlock) && focusBlock.style && focusBlock.style !== types$1.styles[0].value) {
3126
3420
  const [, end] = slate.Range.edges(editor.selection);
3127
3421
  if (slate.Editor.isEnd(editor, end, end.path)) {
3128
3422
  slate.Editor.insertNode(editor, editor.pteCreateEmptyBlock()), event.preventDefault(), editor.onChange();
@@ -3148,13 +3442,13 @@ function createWithHotkeys(types2, portableTextEditor, hotkeysFromOptions) {
3148
3442
  }, editor;
3149
3443
  };
3150
3444
  }
3151
- function validateValue(value, types2, keyGenerator) {
3445
+ function validateValue(value, types$1, keyGenerator) {
3152
3446
  let resolution = null, valid = !0;
3153
- const validChildTypes = [types2.span.name, ...types2.inlineObjects.map((t) => t.name)], validBlockTypes = [types2.block.name, ...types2.blockObjects.map((t) => t.name)];
3447
+ const validChildTypes = [types$1.span.name, ...types$1.inlineObjects.map((t) => t.name)], validBlockTypes = [types$1.block.name, ...types$1.blockObjects.map((t) => t.name)];
3154
3448
  return value === void 0 ? { valid: !0, resolution: null, value } : !Array.isArray(value) || value.length === 0 ? {
3155
3449
  valid: !1,
3156
3450
  resolution: {
3157
- patches: [patchEvent.unset([])],
3451
+ patches: [unset([])],
3158
3452
  description: "Editor value must be an array of Portable Text blocks, or undefined.",
3159
3453
  action: "Unset the value",
3160
3454
  item: value,
@@ -3167,7 +3461,7 @@ function validateValue(value, types2, keyGenerator) {
3167
3461
  } : (value.some((blk, index) => {
3168
3462
  if (!isPlainObject__default.default(blk))
3169
3463
  return resolution = {
3170
- patches: [patchEvent.unset([index])],
3464
+ patches: [unset([index])],
3171
3465
  description: `Block must be an object, got ${String(blk)}`,
3172
3466
  action: "Unset invalid item",
3173
3467
  item: blk,
@@ -3179,7 +3473,7 @@ function validateValue(value, types2, keyGenerator) {
3179
3473
  }, !0;
3180
3474
  if (!blk._key || typeof blk._key != "string")
3181
3475
  return resolution = {
3182
- patches: [patchEvent.set({ ...blk, _key: keyGenerator() }, [index])],
3476
+ patches: [set({ ...blk, _key: keyGenerator() }, [index])],
3183
3477
  description: `Block at index ${index} is missing required _key.`,
3184
3478
  action: "Set the block with a random _key value",
3185
3479
  item: blk,
@@ -3191,9 +3485,9 @@ function validateValue(value, types2, keyGenerator) {
3191
3485
  }, !0;
3192
3486
  if (!blk._type || !validBlockTypes.includes(blk._type)) {
3193
3487
  if (blk._type === "block") {
3194
- const currentBlockTypeName = types2.block.name;
3488
+ const currentBlockTypeName = types$1.block.name;
3195
3489
  return resolution = {
3196
- patches: [patchEvent.set({ ...blk, _type: currentBlockTypeName }, [{ _key: blk._key }])],
3490
+ patches: [set({ ...blk, _type: currentBlockTypeName }, [{ _key: blk._key }])],
3197
3491
  description: `Block with _key '${blk._key}' has invalid type name '${blk._type}'. According to the schema, the block type name is '${currentBlockTypeName}'`,
3198
3492
  action: `Use type '${currentBlockTypeName}'`,
3199
3493
  item: blk,
@@ -3204,18 +3498,18 @@ function validateValue(value, types2, keyGenerator) {
3204
3498
  }
3205
3499
  }, !0;
3206
3500
  }
3207
- return !blk._type && types$1.isPortableTextTextBlock({ ...blk, _type: types2.block.name }) ? (resolution = {
3208
- patches: [patchEvent.set({ ...blk, _type: types2.block.name }, [{ _key: blk._key }])],
3209
- description: `Block with _key '${blk._key}' is missing a type name. According to the schema, the block type name is '${types2.block.name}'`,
3210
- action: `Use type '${types2.block.name}'`,
3501
+ return !blk._type && types.isPortableTextTextBlock({ ...blk, _type: types$1.block.name }) ? (resolution = {
3502
+ patches: [set({ ...blk, _type: types$1.block.name }, [{ _key: blk._key }])],
3503
+ description: `Block with _key '${blk._key}' is missing a type name. According to the schema, the block type name is '${types$1.block.name}'`,
3504
+ action: `Use type '${types$1.block.name}'`,
3211
3505
  item: blk,
3212
3506
  i18n: {
3213
3507
  description: "inputs.portable-text.invalid-value.missing-block-type.description",
3214
3508
  action: "inputs.portable-text.invalid-value.missing-block-type.action",
3215
- values: { key: blk._key, expectedTypeName: types2.block.name }
3509
+ values: { key: blk._key, expectedTypeName: types$1.block.name }
3216
3510
  }
3217
3511
  }, !0) : blk._type ? (resolution = {
3218
- patches: [patchEvent.unset([{ _key: blk._key }])],
3512
+ patches: [unset([{ _key: blk._key }])],
3219
3513
  description: `Block with _key '${blk._key}' has invalid _type '${blk._type}'`,
3220
3514
  action: "Remove the block",
3221
3515
  item: blk,
@@ -3225,7 +3519,7 @@ function validateValue(value, types2, keyGenerator) {
3225
3519
  values: { key: blk._key, typeName: blk._type }
3226
3520
  }
3227
3521
  }, !0) : (resolution = {
3228
- patches: [patchEvent.unset([{ _key: blk._key }])],
3522
+ patches: [unset([{ _key: blk._key }])],
3229
3523
  description: `Block with _key '${blk._key}' is missing an _type property`,
3230
3524
  action: "Remove the block",
3231
3525
  item: blk,
@@ -3236,11 +3530,11 @@ function validateValue(value, types2, keyGenerator) {
3236
3530
  }
3237
3531
  }, !0);
3238
3532
  }
3239
- if (blk._type === types2.block.name) {
3533
+ if (blk._type === types$1.block.name) {
3240
3534
  const textBlock = blk;
3241
3535
  if (textBlock.children && !Array.isArray(textBlock.children))
3242
3536
  return resolution = {
3243
- patches: [patchEvent.set({ children: [] }, [{ _key: textBlock._key }])],
3537
+ patches: [set({ children: [] }, [{ _key: textBlock._key }])],
3244
3538
  description: `Text block with _key '${textBlock._key}' has a invalid required property 'children'.`,
3245
3539
  action: "Reset the children property",
3246
3540
  item: textBlock,
@@ -3252,7 +3546,7 @@ function validateValue(value, types2, keyGenerator) {
3252
3546
  }, !0;
3253
3547
  if (textBlock.children === void 0 || Array.isArray(textBlock.children) && textBlock.children.length === 0) {
3254
3548
  const newSpan = {
3255
- _type: types2.span.name,
3549
+ _type: types$1.span.name,
3256
3550
  _key: keyGenerator(),
3257
3551
  text: "",
3258
3552
  marks: []
@@ -3260,8 +3554,8 @@ function validateValue(value, types2, keyGenerator) {
3260
3554
  return resolution = {
3261
3555
  autoResolve: !0,
3262
3556
  patches: [
3263
- patchEvent.setIfMissing([], [{ _key: blk._key }, "children"]),
3264
- patchEvent.insert([newSpan], "after", [{ _key: blk._key }, "children", 0])
3557
+ setIfMissing([], [{ _key: blk._key }, "children"]),
3558
+ insert$1([newSpan], "after", [{ _key: blk._key }, "children", 0])
3265
3559
  ],
3266
3560
  description: `Children for text block with _key '${blk._key}' is empty.`,
3267
3561
  action: "Insert an empty text",
@@ -3275,7 +3569,7 @@ function validateValue(value, types2, keyGenerator) {
3275
3569
  }
3276
3570
  if (blk.markDefs && !Array.isArray(blk.markDefs))
3277
3571
  return resolution = {
3278
- patches: [patchEvent.set({ ...textBlock, markDefs: EMPTY_MARKDEFS }, [{ _key: textBlock._key }])],
3572
+ patches: [set({ ...textBlock, markDefs: EMPTY_MARKDEFS }, [{ _key: textBlock._key }])],
3279
3573
  description: "Block has invalid required property 'markDefs'.",
3280
3574
  action: "Add empty markDefs array",
3281
3575
  item: textBlock,
@@ -3287,7 +3581,7 @@ function validateValue(value, types2, keyGenerator) {
3287
3581
  }, !0;
3288
3582
  const allUsedMarks = uniq__default.default(
3289
3583
  flatten__default.default(
3290
- textBlock.children.filter((cld) => cld._type === types2.span.name).map((cld) => cld.marks || [])
3584
+ textBlock.children.filter((cld) => cld._type === types$1.span.name).map((cld) => cld.marks || [])
3291
3585
  )
3292
3586
  );
3293
3587
  if (Array.isArray(blk.markDefs) && blk.markDefs.length > 0) {
@@ -3298,7 +3592,7 @@ function validateValue(value, types2, keyGenerator) {
3298
3592
  return resolution = {
3299
3593
  autoResolve: !0,
3300
3594
  patches: unusedMarkDefs.map(
3301
- (markDefKey) => patchEvent.unset([{ _key: blk._key }, "markDefs", { _key: markDefKey }])
3595
+ (markDefKey) => unset([{ _key: blk._key }, "markDefs", { _key: markDefKey }])
3302
3596
  ),
3303
3597
  description: `Block contains orphaned data (unused mark definitions): ${unusedMarkDefs.join(
3304
3598
  ", "
@@ -3313,19 +3607,19 @@ function validateValue(value, types2, keyGenerator) {
3313
3607
  }, !0;
3314
3608
  }
3315
3609
  const orphanedMarks = allUsedMarks.filter(
3316
- (mark) => !types2.decorators.map((dec) => dec.value).includes(mark)
3610
+ (mark) => !types$1.decorators.map((dec) => dec.value).includes(mark)
3317
3611
  ).filter(
3318
3612
  (mark) => textBlock.markDefs === void 0 || !textBlock.markDefs.find((def) => def._key === mark)
3319
3613
  );
3320
3614
  if (orphanedMarks.length > 0) {
3321
3615
  const spanChildren = textBlock.children.filter(
3322
- (cld) => cld._type === types2.span.name && Array.isArray(cld.marks) && cld.marks.some((mark) => orphanedMarks.includes(mark))
3616
+ (cld) => cld._type === types$1.span.name && Array.isArray(cld.marks) && cld.marks.some((mark) => orphanedMarks.includes(mark))
3323
3617
  );
3324
3618
  if (spanChildren) {
3325
3619
  const orphaned = orphanedMarks.join(", ");
3326
3620
  return resolution = {
3327
3621
  autoResolve: !0,
3328
- patches: spanChildren.map((child) => patchEvent.set(
3622
+ patches: spanChildren.map((child) => set(
3329
3623
  (child.marks || []).filter((cMrk) => !orphanedMarks.includes(cMrk)),
3330
3624
  [{ _key: blk._key }, "children", { _key: child._key }, "marks"]
3331
3625
  )),
@@ -3343,7 +3637,7 @@ function validateValue(value, types2, keyGenerator) {
3343
3637
  textBlock.children.some((child, cIndex) => {
3344
3638
  if (!isPlainObject__default.default(child))
3345
3639
  return resolution = {
3346
- patches: [patchEvent.unset([{ _key: blk._key }, "children", cIndex])],
3640
+ patches: [unset([{ _key: blk._key }, "children", cIndex])],
3347
3641
  description: `Child at index '${cIndex}' in block with key '${blk._key}' is not an object.`,
3348
3642
  action: "Remove the item",
3349
3643
  item: blk,
@@ -3357,7 +3651,7 @@ function validateValue(value, types2, keyGenerator) {
3357
3651
  const newChild = { ...child, _key: keyGenerator() };
3358
3652
  return resolution = {
3359
3653
  autoResolve: !0,
3360
- patches: [patchEvent.set(newChild, [{ _key: blk._key }, "children", cIndex])],
3654
+ patches: [set(newChild, [{ _key: blk._key }, "children", cIndex])],
3361
3655
  description: `Child at index ${cIndex} is missing required _key in block with _key ${blk._key}.`,
3362
3656
  action: "Set a new random _key on the object",
3363
3657
  item: blk,
@@ -3368,9 +3662,9 @@ function validateValue(value, types2, keyGenerator) {
3368
3662
  }
3369
3663
  }, !0;
3370
3664
  }
3371
- return child._type ? validChildTypes.includes(child._type) ? child._type === types2.span.name && typeof child.text != "string" ? (resolution = {
3665
+ return child._type ? validChildTypes.includes(child._type) ? child._type === types$1.span.name && typeof child.text != "string" ? (resolution = {
3372
3666
  patches: [
3373
- patchEvent.set({ ...child, text: "" }, [{ _key: blk._key }, "children", { _key: child._key }])
3667
+ set({ ...child, text: "" }, [{ _key: blk._key }, "children", { _key: child._key }])
3374
3668
  ],
3375
3669
  description: `Child with _key '${child._key}' in block with key '${blk._key}' has missing or invalid text property!`,
3376
3670
  action: "Write an empty text property to the object",
@@ -3381,7 +3675,7 @@ function validateValue(value, types2, keyGenerator) {
3381
3675
  values: { key: blk._key, childKey: child._key }
3382
3676
  }
3383
3677
  }, !0) : !1 : (resolution = {
3384
- patches: [patchEvent.unset([{ _key: blk._key }, "children", { _key: child._key }])],
3678
+ patches: [unset([{ _key: blk._key }, "children", { _key: child._key }])],
3385
3679
  description: `Child with _key '${child._key}' in block with key '${blk._key}' has invalid '_type' property (${child._type}).`,
3386
3680
  action: "Remove the object",
3387
3681
  item: blk,
@@ -3391,7 +3685,7 @@ function validateValue(value, types2, keyGenerator) {
3391
3685
  values: { key: blk._key, childKey: child._key, childType: child._type }
3392
3686
  }
3393
3687
  }, !0) : (resolution = {
3394
- patches: [patchEvent.unset([{ _key: blk._key }, "children", { _key: child._key }])],
3688
+ patches: [unset([{ _key: blk._key }, "children", { _key: child._key }])],
3395
3689
  description: `Child with _key '${child._key}' in block with key '${blk._key}' is missing '_type' property.`,
3396
3690
  action: "Remove the object",
3397
3691
  item: blk,
@@ -4561,12 +4855,4 @@ exports.PortableTextEditor = PortableTextEditor;
4561
4855
  exports.keyGenerator = defaultKeyGenerator;
4562
4856
  exports.usePortableTextEditor = usePortableTextEditor;
4563
4857
  exports.usePortableTextEditorSelection = usePortableTextEditorSelection;
4564
- Object.keys(types).forEach(function(k) {
4565
- k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k) && Object.defineProperty(exports, k, {
4566
- enumerable: !0,
4567
- get: function() {
4568
- return types[k];
4569
- }
4570
- });
4571
- });
4572
4858
  //# sourceMappingURL=index.js.map