@portabletext/editor 1.0.4 → 1.0.5

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 = 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");
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"), patches = require("@portabletext/patches"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), 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");
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), 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);
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);
8
8
  const rootName = "sanity-pte:";
9
9
  debug__default.default(rootName);
10
10
  function debugWithName(name) {
@@ -701,1062 +701,240 @@ function compileType(rawType) {
701
701
  types: [rawType]
702
702
  }).get(rawType.name);
703
703
  }
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++);
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 = patches.diffMatchPatch(prevText, textChild.text, path);
717
+ return patch.value.length ? [patch] : [];
731
718
  }
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++;
760
- }
761
- pointer++;
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 = patches.diffMatchPatch(prevText || "", textChild.text, path);
729
+ return patch.value ? [patch] : [];
762
730
  }
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;
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 [patches.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$1 = [], 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$1.push(
751
+ patches.set(val, [{ _key: blockKey }, "children", block.children.indexOf(child), keyName])
752
+ );
753
+ } else {
754
+ const val = get__default.default(operation.newProperties, keyName);
755
+ patches$1.push(patches.set(val, [{ _key: blockKey }, "children", { _key: childKey }, keyName]));
756
+ }
757
+ }), patches$1;
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)}`);
773
764
  }
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;
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
+ patches.insert([fromSlateValue([operation.node], textBlockName)[0]], position, [
771
+ { _key: targetKey }
772
+ ])
773
+ ] : [
774
+ patches.setIfMissing(beforeValue, []),
775
+ patches.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
+ patches.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
+ ];
799
+ }
800
+ return debug$j("Something was inserted into a void block. Not producing editor patches."), [];
801
+ }
802
+ function splitNodePatch(editor, operation, beforeValue) {
803
+ const patches$1 = [], 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$1.push(patches.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$1.push(patches.unset(path));
820
+ }));
782
821
  }
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);
822
+ return patches$1;
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$1.push(
837
+ patches.insert(targetSpans, "after", [
838
+ { _key: splitBlock._key },
839
+ "children",
840
+ { _key: splitSpan._key }
841
+ ])
842
+ ), patches$1.push(
843
+ patches.set(splitSpan.text, [
844
+ { _key: splitBlock._key },
845
+ "children",
846
+ { _key: splitSpan._key },
847
+ "text"
848
+ ])
849
+ );
788
850
  }
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--));
851
+ return patches$1;
790
852
  }
791
- pointer++;
853
+ return patches$1;
792
854
  }
793
- return diffs;
794
- }
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");
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 [patches.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 ? [patches.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$1 = [], 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$1.push(patches.set(newBlock, [{ _key: newBlock._key }])), patches$1.push(patches.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$1.push(
878
+ patches.set(targetSpan.text, [{ _key: block._key }, "children", { _key: targetSpan._key }, "text"])
879
+ ), mergedSpan && patches$1.push(patches.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$1;
883
+ }
884
+ function moveNodePatch(editor, operation, beforeValue) {
885
+ const patches$1 = [], 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$1.push(patches.unset([{ _key: block._key }])), patches$1.push(
889
+ patches.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$1.push(patches.unset([{ _key: block._key }, "children", { _key: child._key }])), patches$1.push(
894
+ patches.insert([childToInsert], position, [
895
+ { _key: targetBlock._key },
896
+ "children",
897
+ { _key: targetChild._key }
898
+ ])
899
+ );
812
900
  }
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);
857
- }
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);
877
- }
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;
901
+ return patches$1;
944
902
  }
945
- let maxLines = 4e4;
946
- const chars1 = diffLinesToMunge(textA);
947
- maxLines = 65535;
948
- const chars2 = diffLinesToMunge(textB);
949
903
  return {
950
- chars1,
951
- chars2,
952
- lineArray
904
+ insertNodePatch,
905
+ insertTextPatch,
906
+ mergeNodePatch,
907
+ moveNodePatch,
908
+ removeNodePatch,
909
+ removeTextPatch,
910
+ setNodePatch,
911
+ splitNodePatch
953
912
  };
954
913
  }
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;
984
- }
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;
1068
- }
1069
- break;
1070
- }
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
1179
- };
1180
- }
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;
1230
- }
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
1242
- };
1243
- }
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()");
1256
- }
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;
1280
- }
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]);
1363
- }
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));
1372
- }
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);
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;
1477
- }
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;
1497
- }
1498
- function toInt(num) {
1499
- return parseInt(num, 10);
1500
- }
1501
- function setIfMissing(value, path = []) {
1502
- return {
1503
- type: "setIfMissing",
1504
- path,
1505
- value
1506
- };
1507
- }
1508
- function diffMatchPatch$1(currentValue, nextValue, path = []) {
1509
- const patches = make(currentValue, nextValue), patch = stringify(patches);
1510
- return { type: "diffMatchPatch", path, value: patch };
1511
- }
1512
- function insert$1(items, position, path = []) {
1513
- return {
1514
- type: "insert",
1515
- path,
1516
- position,
1517
- items
1518
- };
1519
- }
1520
- function set(value, path = []) {
1521
- return { type: "set", path, value };
1522
- }
1523
- function unset(path = []) {
1524
- return { type: "unset", path };
1525
- }
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] : [];
1540
- }
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] : [];
1552
- }
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");
1582
- }
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
- }));
1643
- }
1644
- return patches;
1645
- }
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;
1705
- }
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
- );
1722
- }
1723
- return patches;
1724
- }
1725
- return {
1726
- insertNodePatch,
1727
- insertTextPatch,
1728
- mergeNodePatch,
1729
- moveNodePatch,
1730
- removeNodePatch,
1731
- removeTextPatch,
1732
- setNodePatch,
1733
- splitNodePatch
1734
- };
1735
- }
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;
914
+ const debug$i = debugWithName("API:editable");
915
+ function createWithEditableAPI(portableTextEditor, types$1, 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;
1760
938
  }
1761
939
  },
1762
940
  marks: () => ({
@@ -2059,275 +1237,803 @@ function createWithEditableAPI(portableTextEditor, types$1, keyGenerator) {
2059
1237
  }
2060
1238
  }), slate.Editor.normalize(editor), editor.onChange();
2061
1239
  }
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);
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, types$1.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1249
+ editor.selection,
1250
+ types$1
1251
+ ), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
1252
+ }
1253
+ return ptRange;
1254
+ },
1255
+ getValue: () => fromSlateValue(editor.children, types$1.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(), types$1.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);
1265
+ }
1266
+ }), editor;
1267
+ };
1268
+ }
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
+ };
1291
+ }
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;
1299
+ };
1300
+ }
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);
1305
+ }
1306
+ function isPreservingKeys(editor) {
1307
+ return PRESERVE_KEYS.get(editor);
1308
+ }
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
+ };
1320
+ }
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
+ });
1327
+ }
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;
1337
+ }
1338
+ }
1339
+ normalizeNode(entry);
1340
+ }, editor;
1341
+ };
1342
+ }
1343
+ function isHighSurrogate(char) {
1344
+ const charCode = char.charCodeAt(0);
1345
+ return charCode >= 55296 && charCode <= 56319;
1346
+ }
1347
+ function isLowSurrogate(char) {
1348
+ const charCode = char.charCodeAt(0);
1349
+ return charCode >= 56320 && charCode <= 57343;
1350
+ }
1351
+ function cloneDiff(diff2) {
1352
+ const [type, patch] = diff2;
1353
+ return [type, patch];
1354
+ }
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;
1372
+ }
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;
1380
+ }
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;
1388
+ }
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++;
1401
+ }
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;
1412
+ }
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;
1421
+ }
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);
1427
+ }
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--));
1429
+ }
1430
+ pointer++;
1431
+ }
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");
1451
+ }
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;
1470
+ }
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);
1496
+ }
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);
2074
1516
  }
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
1517
  }
2088
- }), editor;
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
2089
1592
  };
2090
1593
  }
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
- }
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;
2108
1623
  }
2109
- }
2110
- insertBreak();
2111
- }, editor;
2112
- };
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;
2113
1632
  }
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;
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
2121
1679
  };
2122
1680
  }
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);
1681
+ function combineChar(data, char, dir) {
1682
+ return dir === 1 ? data + char : char + data;
2127
1683
  }
2128
- function isPreservingKeys(editor) {
2129
- return PRESERVE_KEYS.get(editor);
1684
+ function splitChar(data, dir) {
1685
+ return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];
2130
1686
  }
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
- };
2142
- }
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
- });
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];
1689
+ }
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;
2149
1709
  }
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
- }
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;
2160
1779
  }
2161
- normalizeNode(entry);
2162
- }, editor;
2163
- };
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;
2164
1794
  }
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;
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);
2174
1806
  }
2175
- function flatten(...values) {
2176
- return values.reduce((prev, item) => prev.concat(item), []);
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
+ };
2177
1819
  }
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;
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("");
2182
1825
  }
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;
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("");
2188
1831
  }
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}`);
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);
2214
1839
  }
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;
1840
+ return bytes;
1841
+ }
1842
+ function adjustIndiciesToUcs2(patches2, 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;
2226
1850
  }
1851
+ if (!options.allowExceedingIndices && byteOffset !== target)
1852
+ throw new Error("Failed to determine byte offset");
1853
+ return idx;
2227
1854
  }
2228
- return nextValue[index] = _apply(nextValue[index], {
2229
- ...patch,
2230
- path: tail
2231
- }), nextValue;
1855
+ const adjusted = [];
1856
+ for (const patch of patches2)
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;
2232
1869
  }
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;
1870
+ function utf8len(codePoint) {
1871
+ return codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
1872
+ }
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.");
2245
1890
  }
2246
- throw new Error(`Invalid object operation: ${patch.type}`);
2247
1891
  }
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);
1892
+ return leven += Math.max(insertions, deletions), leven;
2255
1893
  }
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;
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);
1899
+ }
1900
+ function addPadding(patches2) {
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 patches2)
1906
+ p.start1 += paddingLength, p.start2 += paddingLength, p.utf8Start1 += paddingLength, p.utf8Start2 += paddingLength;
1907
+ let patch = patches2[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;
2273
1913
  }
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);
1914
+ if (patch = patches2[patches2.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;
1919
+ }
1920
+ return nullPadding;
2287
1921
  }
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;
1922
+ function splitMax(patches2) {
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 < patches2.length; x++) {
1926
+ if (patches2[x].length1 <= patchSize)
1927
+ continue;
1928
+ const bigpatch = patches2[x];
1929
+ patches2.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 || patches2.splice(++x, 0, patch);
1950
+ }
2305
1951
  }
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");
2322
1952
  }
2323
- function applyAll(value, patches) {
2324
- return patches.reduce(_apply, value);
1953
+ function apply(patches2, originalText) {
1954
+ let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1955
+ if (typeof patches2 == "string")
1956
+ throw new Error("Patches must be an array - pass the patch to `parsePatch()` first");
1957
+ let text = originalText;
1958
+ if (patches2.length === 0)
1959
+ return [text, []];
1960
+ const parsed = adjustIndiciesToUcs2(patches2, 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];
2325
1994
  }
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);
1995
+ const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
1996
+ function parse(textline) {
1997
+ if (!textline)
1998
+ return [];
1999
+ const patches2 = [], 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 (patches2.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 patches2;
2328
2034
  }
2329
- function _apply(value, patch) {
2330
- return applyPatch(value, patch);
2035
+ function toInt(num) {
2036
+ return parseInt(num, 10);
2331
2037
  }
2332
2038
  const debug$h = debugWithName("applyPatches"), debugVerbose$3 = debug$h.enabled && !0;
2333
2039
  function createApplyPatch(schemaTypes) {
@@ -2368,7 +2074,7 @@ function diffMatchPatch(editor, patch) {
2368
2074
  return debug$h("Child not found"), !1;
2369
2075
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
2370
2076
  return !1;
2371
- const patches = parse(patch.value), [newValue] = apply$4(patches, child.text, { allowExceedingIndices: !0 }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
2077
+ const patches2 = parse(patch.value), [newValue] = apply(patches2, child.text, { allowExceedingIndices: !0 }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
2372
2078
  debugState(editor, "before");
2373
2079
  let offset = 0;
2374
2080
  for (const [op, text] of diff$1)
@@ -2457,7 +2163,7 @@ function setPatch(editor, patch) {
2457
2163
  });
2458
2164
  });
2459
2165
  } else if (block && "value" in block) {
2460
- const newVal = applyAll([block.value], [patch])[0];
2166
+ const newVal = patches.applyAll([block.value], [patch])[0];
2461
2167
  return slate.Transforms.setNodes(editor, { ...block, value: newVal }, { at: blockPath }), !0;
2462
2168
  }
2463
2169
  return debugState(editor, "after"), !0;
@@ -2539,9 +2245,9 @@ function createWithUndoRedo(options) {
2539
2245
  const remotePatches = getRemotePatches(editor);
2540
2246
  patches$ && editor.subscriptions.push(() => {
2541
2247
  debug$g("Subscribing to patches");
2542
- const sub = patches$.subscribe(({ patches, snapshot }) => {
2248
+ const sub = patches$.subscribe(({ patches: patches2, snapshot }) => {
2543
2249
  let reset = !1;
2544
- patches.forEach((patch) => {
2250
+ patches2.forEach((patch) => {
2545
2251
  if (!reset && patch.origin !== "local" && remotePatches) {
2546
2252
  if (patch.type === "unset" && patch.path.length === 0) {
2547
2253
  debug$g("Someone else cleared the content, resetting undo/redo history"), editor.history = { undos: [], redos: [] }, remotePatches.splice(0, remotePatches.length), SAVING.set(editor, !0), reset = !0;
@@ -2739,7 +2445,7 @@ function createWithPatches({
2739
2445
  schemaTypes
2740
2446
  }) {
2741
2447
  let previousChildren;
2742
- const applyPatch2 = createApplyPatch(schemaTypes);
2448
+ const applyPatch = createApplyPatch(schemaTypes);
2743
2449
  return function(editor) {
2744
2450
  IS_PROCESSING_REMOTE_CHANGES.set(editor, !1), PATCHING.set(editor, !0), previousChildren = [...editor.children];
2745
2451
  const { apply: apply2 } = editor;
@@ -2747,7 +2453,7 @@ function createWithPatches({
2747
2453
  const handleBufferedRemotePatches = () => {
2748
2454
  if (bufferedPatches.length === 0)
2749
2455
  return;
2750
- const patches = bufferedPatches;
2456
+ const patches2 = bufferedPatches;
2751
2457
  bufferedPatches = [];
2752
2458
  let changed = !1;
2753
2459
  withRemoteChanges(editor, () => {
@@ -2755,16 +2461,16 @@ function createWithPatches({
2755
2461
  withoutPatching(editor, () => {
2756
2462
  withoutSaving(editor, () => {
2757
2463
  withPreserveKeys(editor, () => {
2758
- patches.forEach((patch) => {
2759
- debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch2(editor, patch);
2464
+ patches2.forEach((patch) => {
2465
+ debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
2760
2466
  });
2761
2467
  });
2762
2468
  });
2763
2469
  });
2764
2470
  }), changed && (editor.normalize(), editor.onChange());
2765
2471
  });
2766
- }, handlePatches = ({ patches }) => {
2767
- const remotePatches = patches.filter((p) => p.origin !== "local");
2472
+ }, handlePatches = ({ patches: patches2 }) => {
2473
+ const remotePatches = patches2.filter((p) => p.origin !== "local");
2768
2474
  remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
2769
2475
  };
2770
2476
  return patches$ && editor.subscriptions.push(() => {
@@ -2776,71 +2482,71 @@ function createWithPatches({
2776
2482
  }), editor.apply = (operation) => {
2777
2483
  if (readOnly)
2778
2484
  return apply2(operation), editor;
2779
- let patches = [];
2485
+ let patches$1 = [];
2780
2486
  previousChildren = editor.children;
2781
2487
  const editorWasEmpty = isEqualToEmptyEditor(previousChildren, schemaTypes);
2782
2488
  apply2(operation);
2783
2489
  const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes);
2784
2490
  if (!isPatching(editor))
2785
2491
  return editor;
2786
- switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches.push(insert$1(previousChildren, "before", [0])), operation.type) {
2492
+ switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches$1.push(patches.insert(previousChildren, "before", [0])), operation.type) {
2787
2493
  case "insert_text":
2788
- patches = [
2789
- ...patches,
2494
+ patches$1 = [
2495
+ ...patches$1,
2790
2496
  ...patchFunctions.insertTextPatch(editor, operation, previousChildren)
2791
2497
  ];
2792
2498
  break;
2793
2499
  case "remove_text":
2794
- patches = [
2795
- ...patches,
2500
+ patches$1 = [
2501
+ ...patches$1,
2796
2502
  ...patchFunctions.removeTextPatch(editor, operation, previousChildren)
2797
2503
  ];
2798
2504
  break;
2799
2505
  case "remove_node":
2800
- patches = [
2801
- ...patches,
2506
+ patches$1 = [
2507
+ ...patches$1,
2802
2508
  ...patchFunctions.removeNodePatch(editor, operation, previousChildren)
2803
2509
  ];
2804
2510
  break;
2805
2511
  case "split_node":
2806
- patches = [
2807
- ...patches,
2512
+ patches$1 = [
2513
+ ...patches$1,
2808
2514
  ...patchFunctions.splitNodePatch(editor, operation, previousChildren)
2809
2515
  ];
2810
2516
  break;
2811
2517
  case "insert_node":
2812
- patches = [
2813
- ...patches,
2518
+ patches$1 = [
2519
+ ...patches$1,
2814
2520
  ...patchFunctions.insertNodePatch(editor, operation, previousChildren)
2815
2521
  ];
2816
2522
  break;
2817
2523
  case "set_node":
2818
- patches = [
2819
- ...patches,
2524
+ patches$1 = [
2525
+ ...patches$1,
2820
2526
  ...patchFunctions.setNodePatch(editor, operation, previousChildren)
2821
2527
  ];
2822
2528
  break;
2823
2529
  case "merge_node":
2824
- patches = [
2825
- ...patches,
2530
+ patches$1 = [
2531
+ ...patches$1,
2826
2532
  ...patchFunctions.mergeNodePatch(editor, operation, previousChildren)
2827
2533
  ];
2828
2534
  break;
2829
2535
  case "move_node":
2830
- patches = [
2831
- ...patches,
2536
+ patches$1 = [
2537
+ ...patches$1,
2832
2538
  ...patchFunctions.moveNodePatch(editor, operation, previousChildren)
2833
2539
  ];
2834
2540
  break;
2835
2541
  }
2836
- return !editorWasEmpty && editorIsEmpty && ["merge_node", "set_node", "remove_text", "remove_node"].includes(operation.type) && (patches = [...patches, unset([])], change$.next({
2542
+ return !editorWasEmpty && editorIsEmpty && ["merge_node", "set_node", "remove_text", "remove_node"].includes(operation.type) && (patches$1 = [...patches$1, patches.unset([])], change$.next({
2837
2543
  type: "unset",
2838
2544
  previousValue: fromSlateValue(
2839
2545
  previousChildren,
2840
2546
  schemaTypes.block.name,
2841
2547
  KEY_TO_VALUE_ELEMENT.get(editor)
2842
2548
  )
2843
- })), editorWasEmpty && patches.length > 0 && (patches = [setIfMissing([], []), ...patches]), patches.length > 0 && patches.forEach((patch) => {
2549
+ })), editorWasEmpty && patches$1.length > 0 && (patches$1 = [patches.setIfMissing([], []), ...patches$1]), patches$1.length > 0 && patches$1.forEach((patch) => {
2844
2550
  change$.next({
2845
2551
  type: "patch",
2846
2552
  patch: { ...patch, origin: "local" }
@@ -3448,7 +3154,7 @@ function validateValue(value, types$1, keyGenerator) {
3448
3154
  return value === void 0 ? { valid: !0, resolution: null, value } : !Array.isArray(value) || value.length === 0 ? {
3449
3155
  valid: !1,
3450
3156
  resolution: {
3451
- patches: [unset([])],
3157
+ patches: [patches.unset([])],
3452
3158
  description: "Editor value must be an array of Portable Text blocks, or undefined.",
3453
3159
  action: "Unset the value",
3454
3160
  item: value,
@@ -3461,7 +3167,7 @@ function validateValue(value, types$1, keyGenerator) {
3461
3167
  } : (value.some((blk, index) => {
3462
3168
  if (!isPlainObject__default.default(blk))
3463
3169
  return resolution = {
3464
- patches: [unset([index])],
3170
+ patches: [patches.unset([index])],
3465
3171
  description: `Block must be an object, got ${String(blk)}`,
3466
3172
  action: "Unset invalid item",
3467
3173
  item: blk,
@@ -3473,7 +3179,7 @@ function validateValue(value, types$1, keyGenerator) {
3473
3179
  }, !0;
3474
3180
  if (!blk._key || typeof blk._key != "string")
3475
3181
  return resolution = {
3476
- patches: [set({ ...blk, _key: keyGenerator() }, [index])],
3182
+ patches: [patches.set({ ...blk, _key: keyGenerator() }, [index])],
3477
3183
  description: `Block at index ${index} is missing required _key.`,
3478
3184
  action: "Set the block with a random _key value",
3479
3185
  item: blk,
@@ -3487,7 +3193,7 @@ function validateValue(value, types$1, keyGenerator) {
3487
3193
  if (blk._type === "block") {
3488
3194
  const currentBlockTypeName = types$1.block.name;
3489
3195
  return resolution = {
3490
- patches: [set({ ...blk, _type: currentBlockTypeName }, [{ _key: blk._key }])],
3196
+ patches: [patches.set({ ...blk, _type: currentBlockTypeName }, [{ _key: blk._key }])],
3491
3197
  description: `Block with _key '${blk._key}' has invalid type name '${blk._type}'. According to the schema, the block type name is '${currentBlockTypeName}'`,
3492
3198
  action: `Use type '${currentBlockTypeName}'`,
3493
3199
  item: blk,
@@ -3499,7 +3205,7 @@ function validateValue(value, types$1, keyGenerator) {
3499
3205
  }, !0;
3500
3206
  }
3501
3207
  return !blk._type && types.isPortableTextTextBlock({ ...blk, _type: types$1.block.name }) ? (resolution = {
3502
- patches: [set({ ...blk, _type: types$1.block.name }, [{ _key: blk._key }])],
3208
+ patches: [patches.set({ ...blk, _type: types$1.block.name }, [{ _key: blk._key }])],
3503
3209
  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
3210
  action: `Use type '${types$1.block.name}'`,
3505
3211
  item: blk,
@@ -3509,7 +3215,7 @@ function validateValue(value, types$1, keyGenerator) {
3509
3215
  values: { key: blk._key, expectedTypeName: types$1.block.name }
3510
3216
  }
3511
3217
  }, !0) : blk._type ? (resolution = {
3512
- patches: [unset([{ _key: blk._key }])],
3218
+ patches: [patches.unset([{ _key: blk._key }])],
3513
3219
  description: `Block with _key '${blk._key}' has invalid _type '${blk._type}'`,
3514
3220
  action: "Remove the block",
3515
3221
  item: blk,
@@ -3519,7 +3225,7 @@ function validateValue(value, types$1, keyGenerator) {
3519
3225
  values: { key: blk._key, typeName: blk._type }
3520
3226
  }
3521
3227
  }, !0) : (resolution = {
3522
- patches: [unset([{ _key: blk._key }])],
3228
+ patches: [patches.unset([{ _key: blk._key }])],
3523
3229
  description: `Block with _key '${blk._key}' is missing an _type property`,
3524
3230
  action: "Remove the block",
3525
3231
  item: blk,
@@ -3534,7 +3240,7 @@ function validateValue(value, types$1, keyGenerator) {
3534
3240
  const textBlock = blk;
3535
3241
  if (textBlock.children && !Array.isArray(textBlock.children))
3536
3242
  return resolution = {
3537
- patches: [set({ children: [] }, [{ _key: textBlock._key }])],
3243
+ patches: [patches.set({ children: [] }, [{ _key: textBlock._key }])],
3538
3244
  description: `Text block with _key '${textBlock._key}' has a invalid required property 'children'.`,
3539
3245
  action: "Reset the children property",
3540
3246
  item: textBlock,
@@ -3554,8 +3260,8 @@ function validateValue(value, types$1, keyGenerator) {
3554
3260
  return resolution = {
3555
3261
  autoResolve: !0,
3556
3262
  patches: [
3557
- setIfMissing([], [{ _key: blk._key }, "children"]),
3558
- insert$1([newSpan], "after", [{ _key: blk._key }, "children", 0])
3263
+ patches.setIfMissing([], [{ _key: blk._key }, "children"]),
3264
+ patches.insert([newSpan], "after", [{ _key: blk._key }, "children", 0])
3559
3265
  ],
3560
3266
  description: `Children for text block with _key '${blk._key}' is empty.`,
3561
3267
  action: "Insert an empty text",
@@ -3569,7 +3275,7 @@ function validateValue(value, types$1, keyGenerator) {
3569
3275
  }
3570
3276
  if (blk.markDefs && !Array.isArray(blk.markDefs))
3571
3277
  return resolution = {
3572
- patches: [set({ ...textBlock, markDefs: EMPTY_MARKDEFS }, [{ _key: textBlock._key }])],
3278
+ patches: [patches.set({ ...textBlock, markDefs: EMPTY_MARKDEFS }, [{ _key: textBlock._key }])],
3573
3279
  description: "Block has invalid required property 'markDefs'.",
3574
3280
  action: "Add empty markDefs array",
3575
3281
  item: textBlock,
@@ -3592,7 +3298,7 @@ function validateValue(value, types$1, keyGenerator) {
3592
3298
  return resolution = {
3593
3299
  autoResolve: !0,
3594
3300
  patches: unusedMarkDefs.map(
3595
- (markDefKey) => unset([{ _key: blk._key }, "markDefs", { _key: markDefKey }])
3301
+ (markDefKey) => patches.unset([{ _key: blk._key }, "markDefs", { _key: markDefKey }])
3596
3302
  ),
3597
3303
  description: `Block contains orphaned data (unused mark definitions): ${unusedMarkDefs.join(
3598
3304
  ", "
@@ -3619,7 +3325,7 @@ function validateValue(value, types$1, keyGenerator) {
3619
3325
  const orphaned = orphanedMarks.join(", ");
3620
3326
  return resolution = {
3621
3327
  autoResolve: !0,
3622
- patches: spanChildren.map((child) => set(
3328
+ patches: spanChildren.map((child) => patches.set(
3623
3329
  (child.marks || []).filter((cMrk) => !orphanedMarks.includes(cMrk)),
3624
3330
  [{ _key: blk._key }, "children", { _key: child._key }, "marks"]
3625
3331
  )),
@@ -3637,7 +3343,7 @@ function validateValue(value, types$1, keyGenerator) {
3637
3343
  textBlock.children.some((child, cIndex) => {
3638
3344
  if (!isPlainObject__default.default(child))
3639
3345
  return resolution = {
3640
- patches: [unset([{ _key: blk._key }, "children", cIndex])],
3346
+ patches: [patches.unset([{ _key: blk._key }, "children", cIndex])],
3641
3347
  description: `Child at index '${cIndex}' in block with key '${blk._key}' is not an object.`,
3642
3348
  action: "Remove the item",
3643
3349
  item: blk,
@@ -3651,7 +3357,7 @@ function validateValue(value, types$1, keyGenerator) {
3651
3357
  const newChild = { ...child, _key: keyGenerator() };
3652
3358
  return resolution = {
3653
3359
  autoResolve: !0,
3654
- patches: [set(newChild, [{ _key: blk._key }, "children", cIndex])],
3360
+ patches: [patches.set(newChild, [{ _key: blk._key }, "children", cIndex])],
3655
3361
  description: `Child at index ${cIndex} is missing required _key in block with _key ${blk._key}.`,
3656
3362
  action: "Set a new random _key on the object",
3657
3363
  item: blk,
@@ -3664,7 +3370,7 @@ function validateValue(value, types$1, keyGenerator) {
3664
3370
  }
3665
3371
  return child._type ? validChildTypes.includes(child._type) ? child._type === types$1.span.name && typeof child.text != "string" ? (resolution = {
3666
3372
  patches: [
3667
- set({ ...child, text: "" }, [{ _key: blk._key }, "children", { _key: child._key }])
3373
+ patches.set({ ...child, text: "" }, [{ _key: blk._key }, "children", { _key: child._key }])
3668
3374
  ],
3669
3375
  description: `Child with _key '${child._key}' in block with key '${blk._key}' has missing or invalid text property!`,
3670
3376
  action: "Write an empty text property to the object",
@@ -3675,7 +3381,7 @@ function validateValue(value, types$1, keyGenerator) {
3675
3381
  values: { key: blk._key, childKey: child._key }
3676
3382
  }
3677
3383
  }, !0) : !1 : (resolution = {
3678
- patches: [unset([{ _key: blk._key }, "children", { _key: child._key }])],
3384
+ patches: [patches.unset([{ _key: blk._key }, "children", { _key: child._key }])],
3679
3385
  description: `Child with _key '${child._key}' in block with key '${blk._key}' has invalid '_type' property (${child._type}).`,
3680
3386
  action: "Remove the object",
3681
3387
  item: blk,
@@ -3685,7 +3391,7 @@ function validateValue(value, types$1, keyGenerator) {
3685
3391
  values: { key: blk._key, childKey: child._key, childType: child._type }
3686
3392
  }
3687
3393
  }, !0) : (resolution = {
3688
- patches: [unset([{ _key: blk._key }, "children", { _key: child._key }])],
3394
+ patches: [patches.unset([{ _key: blk._key }, "children", { _key: child._key }])],
3689
3395
  description: `Child with _key '${child._key}' in block with key '${blk._key}' is missing '_type' property.`,
3690
3396
  action: "Remove the object",
3691
3397
  item: blk,