@portabletext/editor 1.0.4 → 1.0.6

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.esm.js CHANGED
@@ -10,15 +10,11 @@ import { styled } from "styled-components";
10
10
  import uniq from "lodash/uniq.js";
11
11
  import { Subject } from "rxjs";
12
12
  import { Schema } from "@sanity/schema";
13
+ import { diffMatchPatch as diffMatchPatch$1, set, insert, setIfMissing, unset, applyAll } from "@portabletext/patches";
13
14
  import get from "lodash/get.js";
14
15
  import isUndefined from "lodash/isUndefined.js";
15
16
  import omitBy from "lodash/omitBy.js";
16
- import isObject from "lodash/isObject.js";
17
- import isString from "lodash/isString.js";
18
- import findIndex from "lodash/findIndex.js";
19
- import clone from "lodash/clone.js";
20
- import omit from "lodash/omit.js";
21
- import flatten$1 from "lodash/flatten.js";
17
+ import flatten from "lodash/flatten.js";
22
18
  import { isHotkey } from "is-hotkey-esm";
23
19
  import { htmlToBlocks, normalizeBlock } from "@sanity/block-tools";
24
20
  import isPlainObject from "lodash/isPlainObject.js";
@@ -721,1062 +717,240 @@ function compileType(rawType) {
721
717
  types: [rawType]
722
718
  }).get(rawType.name);
723
719
  }
724
- function isHighSurrogate(char) {
725
- const charCode = char.charCodeAt(0);
726
- return charCode >= 55296 && charCode <= 56319;
727
- }
728
- function isLowSurrogate(char) {
729
- const charCode = char.charCodeAt(0);
730
- return charCode >= 56320 && charCode <= 57343;
731
- }
732
- function cloneDiff(diff2) {
733
- const [type, patch] = diff2;
734
- return [type, patch];
735
- }
736
- function getCommonOverlap(textA, textB) {
737
- let text1 = textA, text2 = textB;
738
- const text1Length = text1.length, text2Length = text2.length;
739
- if (text1Length === 0 || text2Length === 0)
740
- return 0;
741
- text1Length > text2Length ? text1 = text1.substring(text1Length - text2Length) : text1Length < text2Length && (text2 = text2.substring(0, text1Length));
742
- const textLength = Math.min(text1Length, text2Length);
743
- if (text1 === text2)
744
- return textLength;
745
- let best = 0, length = 1;
746
- for (let found = 0; found !== -1; ) {
747
- const pattern = text1.substring(textLength - length);
748
- if (found = text2.indexOf(pattern), found === -1)
749
- return best;
750
- length += found, (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) && (best = length, length++);
720
+ const debug$j = debugWithName("operationToPatches");
721
+ debug$j.enabled = !1;
722
+ function createOperationToPatches(types) {
723
+ const textBlockName = types.block.name;
724
+ function insertTextPatch(editor, operation, beforeValue) {
725
+ debug$j.enabled && debug$j("Operation", JSON.stringify(operation, null, 2));
726
+ const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
727
+ if (!block)
728
+ throw new Error("Could not find block");
729
+ const textChild = editor.isTextBlock(block) && editor.isTextSpan(block.children[operation.path[1]]) && block.children[operation.path[1]];
730
+ if (!textChild)
731
+ throw new Error("Could not find child");
732
+ 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);
733
+ return patch.value.length ? [patch] : [];
751
734
  }
752
- return best;
753
- }
754
- function getCommonPrefix(text1, text2) {
755
- if (!text1 || !text2 || text1[0] !== text2[0])
756
- return 0;
757
- let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerStart = 0;
758
- for (; pointerMin < pointerMid; )
759
- text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid) ? (pointerMin = pointerMid, pointerStart = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
760
- return pointerMid;
761
- }
762
- function getCommonSuffix(text1, text2) {
763
- if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1])
764
- return 0;
765
- let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerEnd = 0;
766
- for (; pointerMin < pointerMid; )
767
- 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);
768
- return pointerMid;
769
- }
770
- function cleanupSemantic(rawDiffs) {
771
- let diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
772
- const equalities = [];
773
- let equalitiesLength = 0, lastEquality = null, pointer = 0, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0;
774
- for (; pointer < diffs.length; )
775
- 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++;
776
- for (hasChanges && (diffs = cleanupMerge(diffs)), diffs = cleanupSemanticLossless(diffs), pointer = 1; pointer < diffs.length; ) {
777
- if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
778
- const deletion = diffs[pointer - 1][1], insertion = diffs[pointer][1], overlapLength1 = getCommonOverlap(deletion, insertion), overlapLength2 = getCommonOverlap(insertion, deletion);
779
- 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++;
780
- }
781
- pointer++;
735
+ function removeTextPatch(editor, operation, beforeValue) {
736
+ const block = editor && editor.children[operation.path[0]];
737
+ if (!block)
738
+ throw new Error("Could not find block");
739
+ const child = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, textChild = editor.isTextSpan(child) ? child : void 0;
740
+ if (child && !textChild)
741
+ throw new Error("Expected span");
742
+ if (!textChild)
743
+ throw new Error("Could not find child");
744
+ 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);
745
+ return patch.value ? [patch] : [];
782
746
  }
783
- return diffs;
784
- }
785
- const nonAlphaNumericRegex = /[^a-zA-Z0-9]/, whitespaceRegex = /\s/, linebreakRegex = /[\r\n]/, blanklineEndRegex = /\n\r?\n$/, blanklineStartRegex = /^\r?\n\r?\n/;
786
- function cleanupSemanticLossless(rawDiffs) {
787
- const diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
788
- function diffCleanupSemanticScore(one, two) {
789
- if (!one || !two)
790
- return 6;
791
- 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);
792
- return blankLine1 || blankLine2 ? 5 : lineBreak1 || lineBreak2 ? 4 : nonAlphaNumeric1 && !whitespace1 && whitespace2 ? 3 : whitespace1 || whitespace2 ? 2 : nonAlphaNumeric1 || nonAlphaNumeric2 ? 1 : 0;
747
+ function setNodePatch(editor, operation) {
748
+ if (operation.path.length === 1) {
749
+ const block = editor.children[operation.path[0]];
750
+ if (typeof block._key != "string")
751
+ throw new Error("Expected block to have a _key");
752
+ const setNode = omitBy(
753
+ { ...editor.children[operation.path[0]], ...operation.newProperties },
754
+ isUndefined
755
+ );
756
+ return [set(fromSlateValue([setNode], textBlockName)[0], [{ _key: block._key }])];
757
+ } else if (operation.path.length === 2) {
758
+ const block = editor.children[operation.path[0]];
759
+ if (editor.isTextBlock(block)) {
760
+ const child = block.children[operation.path[1]];
761
+ if (child) {
762
+ const blockKey = block._key, childKey = child._key, patches = [], keys = Object.keys(operation.newProperties);
763
+ return keys.forEach((keyName) => {
764
+ if (keys.length === 1 && keyName === "_key") {
765
+ const val = get(operation.newProperties, keyName);
766
+ patches.push(
767
+ set(val, [{ _key: blockKey }, "children", block.children.indexOf(child), keyName])
768
+ );
769
+ } else {
770
+ const val = get(operation.newProperties, keyName);
771
+ patches.push(set(val, [{ _key: blockKey }, "children", { _key: childKey }, keyName]));
772
+ }
773
+ }), patches;
774
+ }
775
+ throw new Error("Could not find a valid child");
776
+ }
777
+ throw new Error("Could not find a valid block");
778
+ } else
779
+ throw new Error(`Unexpected path encountered: ${JSON.stringify(operation.path)}`);
793
780
  }
794
- let pointer = 1;
795
- for (; pointer < diffs.length - 1; ) {
796
- if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
797
- let equality1 = diffs[pointer - 1][1], edit = diffs[pointer][1], equality2 = diffs[pointer + 1][1];
798
- const commonOffset = getCommonSuffix(equality1, edit);
799
- if (commonOffset) {
800
- const commonString = edit.substring(edit.length - commonOffset);
801
- equality1 = equality1.substring(0, equality1.length - commonOffset), edit = commonString + edit.substring(0, edit.length - commonOffset), equality2 = commonString + equality2;
781
+ function insertNodePatch(editor, operation, beforeValue) {
782
+ const block = beforeValue[operation.path[0]], isTextBlock = editor.isTextBlock(block);
783
+ if (operation.path.length === 1) {
784
+ 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;
785
+ return targetKey ? [
786
+ insert([fromSlateValue([operation.node], textBlockName)[0]], position, [
787
+ { _key: targetKey }
788
+ ])
789
+ ] : [
790
+ setIfMissing(beforeValue, []),
791
+ insert([fromSlateValue([operation.node], textBlockName)[0]], "before", [
792
+ operation.path[0]
793
+ ])
794
+ ];
795
+ } else if (isTextBlock && operation.path.length === 2 && editor.children[operation.path[0]]) {
796
+ const position = block.children.length === 0 || !block.children[operation.path[1] - 1] ? "before" : "after", node = { ...operation.node };
797
+ !node._type && Text.isText(node) && (node._type = "span", node.marks = []);
798
+ const child = fromSlateValue(
799
+ [
800
+ {
801
+ _key: "bogus",
802
+ _type: textBlockName,
803
+ children: [node]
804
+ }
805
+ ],
806
+ textBlockName
807
+ )[0].children[0];
808
+ return [
809
+ insert([child], position, [
810
+ { _key: block._key },
811
+ "children",
812
+ block.children.length <= 1 || !block.children[operation.path[1] - 1] ? 0 : { _key: block.children[operation.path[1] - 1]._key }
813
+ ])
814
+ ];
815
+ }
816
+ return debug$j("Something was inserted into a void block. Not producing editor patches."), [];
817
+ }
818
+ function splitNodePatch(editor, operation, beforeValue) {
819
+ const patches = [], splitBlock = editor.children[operation.path[0]];
820
+ if (!editor.isTextBlock(splitBlock))
821
+ throw new Error(
822
+ `Block with path ${JSON.stringify(
823
+ operation.path[0]
824
+ )} is not a text block and can't be split`
825
+ );
826
+ if (operation.path.length === 1) {
827
+ const oldBlock = beforeValue[operation.path[0]];
828
+ if (editor.isTextBlock(oldBlock)) {
829
+ const targetValue = fromSlateValue(
830
+ [editor.children[operation.path[0] + 1]],
831
+ textBlockName
832
+ )[0];
833
+ targetValue && (patches.push(insert([targetValue], "after", [{ _key: splitBlock._key }])), oldBlock.children.slice(operation.position).forEach((span) => {
834
+ const path = [{ _key: oldBlock._key }, "children", { _key: span._key }];
835
+ patches.push(unset(path));
836
+ }));
802
837
  }
803
- let bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2, bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
804
- for (; edit.charAt(0) === equality2.charAt(0); ) {
805
- equality1 += edit.charAt(0), edit = edit.substring(1) + equality2.charAt(0), equality2 = equality2.substring(1);
806
- const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
807
- score >= bestScore && (bestScore = score, bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2);
838
+ return patches;
839
+ }
840
+ if (operation.path.length === 2) {
841
+ const splitSpan = splitBlock.children[operation.path[1]];
842
+ if (editor.isTextSpan(splitSpan)) {
843
+ const targetSpans = fromSlateValue(
844
+ [
845
+ {
846
+ ...splitBlock,
847
+ children: splitBlock.children.slice(operation.path[1] + 1, operation.path[1] + 2)
848
+ }
849
+ ],
850
+ textBlockName
851
+ )[0].children;
852
+ patches.push(
853
+ insert(targetSpans, "after", [
854
+ { _key: splitBlock._key },
855
+ "children",
856
+ { _key: splitSpan._key }
857
+ ])
858
+ ), patches.push(
859
+ set(splitSpan.text, [
860
+ { _key: splitBlock._key },
861
+ "children",
862
+ { _key: splitSpan._key },
863
+ "text"
864
+ ])
865
+ );
808
866
  }
809
- 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--));
867
+ return patches;
810
868
  }
811
- pointer++;
869
+ return patches;
812
870
  }
813
- return diffs;
814
- }
815
- function cleanupMerge(rawDiffs) {
816
- let diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
817
- diffs.push([DIFF_EQUAL, ""]);
818
- let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "", commonlength;
819
- for (; pointer < diffs.length; )
820
- switch (diffs[pointer][0]) {
821
- case DIFF_INSERT:
822
- countInsert++, textInsert += diffs[pointer][1], pointer++;
823
- break;
824
- case DIFF_DELETE:
825
- countDelete++, textDelete += diffs[pointer][1], pointer++;
826
- break;
827
- case DIFF_EQUAL:
828
- 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 = "";
829
- break;
830
- default:
831
- throw new Error("Unknown diff operation");
832
- }
833
- diffs[diffs.length - 1][1] === "" && diffs.pop();
834
- let hasChanges = !1;
835
- for (pointer = 1; pointer < diffs.length - 1; )
836
- 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++;
837
- return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
838
- }
839
- function trueCount() {
840
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)
841
- args[_key] = arguments[_key];
842
- return args.reduce((n, bool) => n + (bool ? 1 : 0), 0);
843
- }
844
- function cleanupEfficiency(rawDiffs) {
845
- let editCost = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 4, diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
846
- const equalities = [];
847
- let equalitiesLength = 0, lastEquality = null, pointer = 0, preIns = !1, preDel = !1, postIns = !1, postDel = !1;
848
- for (; pointer < diffs.length; )
849
- 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++;
850
- return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
851
- }
852
- function bisect(text1, text2, deadline) {
853
- 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);
854
- for (let x = 0; x < vLength; x++)
855
- v1[x] = -1, v2[x] = -1;
856
- v1[vOffset + 1] = 0, v2[vOffset + 1] = 0;
857
- const delta = text1Length - text2Length, front = delta % 2 !== 0;
858
- let k1start = 0, k1end = 0, k2start = 0, k2end = 0;
859
- for (let d = 0; d < maxD && !(Date.now() > deadline); d++) {
860
- for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
861
- const k1Offset = vOffset + k1;
862
- let x1;
863
- k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1] ? x1 = v1[k1Offset + 1] : x1 = v1[k1Offset - 1] + 1;
864
- let y1 = x1 - k1;
865
- for (; x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1); )
866
- x1++, y1++;
867
- if (v1[k1Offset] = x1, x1 > text1Length)
868
- k1end += 2;
869
- else if (y1 > text2Length)
870
- k1start += 2;
871
- else if (front) {
872
- const k2Offset = vOffset + delta - k1;
873
- if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
874
- const x2 = text1Length - v2[k2Offset];
875
- if (x1 >= x2)
876
- return bisectSplit(text1, text2, x1, y1, deadline);
877
- }
878
- }
879
- }
880
- for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
881
- const k2Offset = vOffset + k2;
882
- let x2;
883
- k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1] ? x2 = v2[k2Offset + 1] : x2 = v2[k2Offset - 1] + 1;
884
- let y2 = x2 - k2;
885
- for (; x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1); )
886
- x2++, y2++;
887
- if (v2[k2Offset] = x2, x2 > text1Length)
888
- k2end += 2;
889
- else if (y2 > text2Length)
890
- k2start += 2;
891
- else if (!front) {
892
- const k1Offset = vOffset + delta - k2;
893
- if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
894
- const x1 = v1[k1Offset], y1 = vOffset + x1 - k1Offset;
895
- if (x2 = text1Length - x2, x1 >= x2)
896
- return bisectSplit(text1, text2, x1, y1, deadline);
897
- }
898
- }
899
- }
900
- }
901
- return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
902
- }
903
- function bisectSplit(text1, text2, x, y, deadline) {
904
- const text1a = text1.substring(0, x), text2a = text2.substring(0, y), text1b = text1.substring(x), text2b = text2.substring(y), diffs = doDiff(text1a, text2a, {
905
- checkLines: !1,
906
- deadline
907
- }), diffsb = doDiff(text1b, text2b, {
908
- checkLines: !1,
909
- deadline
910
- });
911
- return diffs.concat(diffsb);
912
- }
913
- function findHalfMatch(text1, text2) {
914
- if ((arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1) <= 0)
915
- return null;
916
- const longText = text1.length > text2.length ? text1 : text2, shortText = text1.length > text2.length ? text2 : text1;
917
- if (longText.length < 4 || shortText.length * 2 < longText.length)
918
- return null;
919
- const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4)), halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));
920
- let halfMatch;
921
- if (halfMatch1 && halfMatch2)
922
- halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;
923
- else {
924
- if (!halfMatch1 && !halfMatch2)
925
- return null;
926
- halfMatch2 ? halfMatch1 || (halfMatch = halfMatch2) : halfMatch = halfMatch1;
927
- }
928
- if (!halfMatch)
929
- throw new Error("Unable to find a half match.");
930
- let text1A, text1B, text2A, text2B;
931
- 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]);
932
- const midCommon = halfMatch[4];
933
- return [text1A, text1B, text2A, text2B, midCommon];
934
- }
935
- function halfMatchI(longText, shortText, i) {
936
- const seed = longText.slice(i, i + Math.floor(longText.length / 4));
937
- let j = -1, bestCommon = "", bestLongTextA, bestLongTextB, bestShortTextA, bestShortTextB;
938
- for (; (j = shortText.indexOf(seed, j + 1)) !== -1; ) {
939
- const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j)), suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));
940
- 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));
871
+ function removeNodePatch(editor, operation, beforeValue) {
872
+ const block = beforeValue[operation.path[0]];
873
+ if (operation.path.length === 1) {
874
+ if (block && block._key)
875
+ return [unset([{ _key: block._key }])];
876
+ throw new Error("Block not found");
877
+ } else if (editor.isTextBlock(block) && operation.path.length === 2) {
878
+ const spanToRemove = editor.isTextBlock(block) && block.children && block.children[operation.path[1]];
879
+ return spanToRemove ? [unset([{ _key: block._key }, "children", { _key: spanToRemove._key }])] : (debug$j("Span not found in editor trying to remove node"), []);
880
+ } else
881
+ return debug$j("Not creating patch inside object block"), [];
941
882
  }
942
- return bestCommon.length * 2 >= longText.length ? [bestLongTextA || "", bestLongTextB || "", bestShortTextA || "", bestShortTextB || "", bestCommon || ""] : null;
943
- }
944
- function charsToLines(diffs, lineArray) {
945
- for (let x = 0; x < diffs.length; x++) {
946
- const chars = diffs[x][1], text = [];
947
- for (let y = 0; y < chars.length; y++)
948
- text[y] = lineArray[chars.charCodeAt(y)];
949
- diffs[x][1] = text.join("");
883
+ function mergeNodePatch(editor, operation, beforeValue) {
884
+ const patches = [], block = beforeValue[operation.path[0]], targetBlock = editor.children[operation.path[0]];
885
+ if (operation.path.length === 1)
886
+ if (block != null && block._key) {
887
+ const newBlock = fromSlateValue([editor.children[operation.path[0] - 1]], textBlockName)[0];
888
+ patches.push(set(newBlock, [{ _key: newBlock._key }])), patches.push(unset([{ _key: block._key }]));
889
+ } else
890
+ throw new Error("Target key not found!");
891
+ else if (operation.path.length === 2 && editor.isTextBlock(targetBlock)) {
892
+ const mergedSpan = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, targetSpan = targetBlock.children[operation.path[1] - 1];
893
+ editor.isTextSpan(targetSpan) && (patches.push(
894
+ set(targetSpan.text, [{ _key: block._key }, "children", { _key: targetSpan._key }, "text"])
895
+ ), mergedSpan && patches.push(unset([{ _key: block._key }, "children", { _key: mergedSpan._key }])));
896
+ } else
897
+ debug$j("Void nodes can't be merged, not creating any patches");
898
+ return patches;
950
899
  }
951
- }
952
- function linesToChars(textA, textB) {
953
- const lineArray = [], lineHash = {};
954
- lineArray[0] = "";
955
- function diffLinesToMunge(text) {
956
- let chars = "", lineStart = 0, lineEnd = -1, lineArrayLength = lineArray.length;
957
- for (; lineEnd < text.length - 1; ) {
958
- lineEnd = text.indexOf(`
959
- `, lineStart), lineEnd === -1 && (lineEnd = text.length - 1);
960
- let line = text.slice(lineStart, lineEnd + 1);
961
- (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;
900
+ function moveNodePatch(editor, operation, beforeValue) {
901
+ const patches = [], block = beforeValue[operation.path[0]], targetBlock = beforeValue[operation.newPath[0]];
902
+ if (operation.path.length === 1) {
903
+ const position = operation.path[0] > operation.newPath[0] ? "before" : "after";
904
+ patches.push(unset([{ _key: block._key }])), patches.push(
905
+ insert([fromSlateValue([block], textBlockName)[0]], position, [{ _key: targetBlock._key }])
906
+ );
907
+ } else if (operation.path.length === 2 && editor.isTextBlock(block) && editor.isTextBlock(targetBlock)) {
908
+ 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]];
909
+ patches.push(unset([{ _key: block._key }, "children", { _key: child._key }])), patches.push(
910
+ insert([childToInsert], position, [
911
+ { _key: targetBlock._key },
912
+ "children",
913
+ { _key: targetChild._key }
914
+ ])
915
+ );
962
916
  }
963
- return chars;
917
+ return patches;
964
918
  }
965
- let maxLines = 4e4;
966
- const chars1 = diffLinesToMunge(textA);
967
- maxLines = 65535;
968
- const chars2 = diffLinesToMunge(textB);
969
919
  return {
970
- chars1,
971
- chars2,
972
- lineArray
920
+ insertNodePatch,
921
+ insertTextPatch,
922
+ mergeNodePatch,
923
+ moveNodePatch,
924
+ removeNodePatch,
925
+ removeTextPatch,
926
+ setNodePatch,
927
+ splitNodePatch
973
928
  };
974
929
  }
975
- function doLineModeDiff(textA, textB, opts) {
976
- let text1 = textA, text2 = textB;
977
- const a = linesToChars(text1, text2);
978
- text1 = a.chars1, text2 = a.chars2;
979
- const linearray = a.lineArray;
980
- let diffs = doDiff(text1, text2, {
981
- checkLines: !1,
982
- deadline: opts.deadline
983
- });
984
- charsToLines(diffs, linearray), diffs = cleanupSemantic(diffs), diffs.push([DIFF_EQUAL, ""]);
985
- let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "";
986
- for (; pointer < diffs.length; ) {
987
- switch (diffs[pointer][0]) {
988
- case DIFF_INSERT:
989
- countInsert++, textInsert += diffs[pointer][1];
990
- break;
991
- case DIFF_DELETE:
992
- countDelete++, textDelete += diffs[pointer][1];
993
- break;
994
- case DIFF_EQUAL:
995
- if (countDelete >= 1 && countInsert >= 1) {
996
- diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert), pointer = pointer - countDelete - countInsert;
997
- const aa = doDiff(textDelete, textInsert, {
998
- checkLines: !1,
999
- deadline: opts.deadline
1000
- });
1001
- for (let j = aa.length - 1; j >= 0; j--)
1002
- diffs.splice(pointer, 0, aa[j]);
1003
- pointer += aa.length;
1004
- }
1005
- countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
1006
- break;
1007
- default:
1008
- throw new Error("Unknown diff operation.");
1009
- }
1010
- pointer++;
1011
- }
1012
- return diffs.pop(), diffs;
1013
- }
1014
- function computeDiff(text1, text2, opts) {
1015
- let diffs;
1016
- if (!text1)
1017
- return [[DIFF_INSERT, text2]];
1018
- if (!text2)
1019
- return [[DIFF_DELETE, text1]];
1020
- const longtext = text1.length > text2.length ? text1 : text2, shorttext = text1.length > text2.length ? text2 : text1, i = longtext.indexOf(shorttext);
1021
- if (i !== -1)
1022
- 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;
1023
- if (shorttext.length === 1)
1024
- return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1025
- const halfMatch = findHalfMatch(text1, text2);
1026
- if (halfMatch) {
1027
- 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);
1028
- return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
1029
- }
1030
- return opts.checkLines && text1.length > 100 && text2.length > 100 ? doLineModeDiff(text1, text2, opts) : bisect(text1, text2, opts.deadline);
1031
- }
1032
- const DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0;
1033
- function diff(textA, textB, opts) {
1034
- if (textA === null || textB === null)
1035
- throw new Error("Null input. (diff)");
1036
- const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));
1037
- return adjustDiffForSurrogatePairs(diffs), diffs;
1038
- }
1039
- function doDiff(textA, textB, options) {
1040
- let text1 = textA, text2 = textB;
1041
- if (text1 === text2)
1042
- return text1 ? [[DIFF_EQUAL, text1]] : [];
1043
- let commonlength = getCommonPrefix(text1, text2);
1044
- const commonprefix = text1.substring(0, commonlength);
1045
- text1 = text1.substring(commonlength), text2 = text2.substring(commonlength), commonlength = getCommonSuffix(text1, text2);
1046
- const commonsuffix = text1.substring(text1.length - commonlength);
1047
- text1 = text1.substring(0, text1.length - commonlength), text2 = text2.substring(0, text2.length - commonlength);
1048
- let diffs = computeDiff(text1, text2, options);
1049
- return commonprefix && diffs.unshift([DIFF_EQUAL, commonprefix]), commonsuffix && diffs.push([DIFF_EQUAL, commonsuffix]), diffs = cleanupMerge(diffs), diffs;
1050
- }
1051
- function createDeadLine(timeout) {
1052
- let t = 1;
1053
- return typeof timeout < "u" && (t = timeout <= 0 ? Number.MAX_VALUE : timeout), Date.now() + t * 1e3;
1054
- }
1055
- function createInternalOpts(opts) {
1056
- return {
1057
- checkLines: !0,
1058
- deadline: createDeadLine(opts.timeout || 1),
1059
- ...opts
1060
- };
1061
- }
1062
- function combineChar(data, char, dir) {
1063
- return dir === 1 ? data + char : char + data;
1064
- }
1065
- function splitChar(data, dir) {
1066
- return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];
1067
- }
1068
- function hasSharedChar(diffs, i, j, dir) {
1069
- 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];
1070
- }
1071
- function deisolateChar(diffs, i, dir) {
1072
- const inv = dir === 1 ? -1 : 1;
1073
- let insertIdx = null, deleteIdx = null, j = i + dir;
1074
- for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {
1075
- const [op, text2] = diffs[j];
1076
- if (text2.length !== 0) {
1077
- if (op === DIFF_INSERT) {
1078
- insertIdx === null && (insertIdx = j);
1079
- continue;
1080
- } else if (op === DIFF_DELETE) {
1081
- deleteIdx === null && (deleteIdx = j);
1082
- continue;
1083
- } else if (op === DIFF_EQUAL) {
1084
- if (insertIdx === null && deleteIdx === null) {
1085
- const [rest, char2] = splitChar(diffs[i][1], dir);
1086
- diffs[i][1] = rest, diffs[j][1] = combineChar(diffs[j][1], char2, inv);
1087
- return;
1088
- }
1089
- break;
1090
- }
1091
- }
1092
- }
1093
- if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {
1094
- const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv), [deleteText] = splitChar(diffs[deleteIdx][1], inv);
1095
- diffs[insertIdx][1] = insertText, diffs[deleteIdx][1] = deleteText, diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);
1096
- return;
1097
- }
1098
- const [text, char] = splitChar(diffs[i][1], dir);
1099
- 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);
1100
- }
1101
- function adjustDiffForSurrogatePairs(diffs) {
1102
- for (let i = 0; i < diffs.length; i++) {
1103
- const [diffType, diffText] = diffs[i];
1104
- if (diffText.length === 0) continue;
1105
- const firstChar = diffText[0], lastChar = diffText[diffText.length - 1];
1106
- isHighSurrogate(lastChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, 1), isLowSurrogate(firstChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, -1);
1107
- }
1108
- for (let i = 0; i < diffs.length; i++)
1109
- diffs[i][1].length === 0 && diffs.splice(i, 1);
1110
- }
1111
- const DEFAULT_OPTIONS = {
1112
- /**
1113
- * At what point is no match declared (0.0 = perfection, 1.0 = very loose).
1114
- */
1115
- threshold: 0.5,
1116
- /**
1117
- * How far to search for a match (0 = exact location, 1000+ = broad match).
1118
- * A match this many characters away from the expected location will add
1119
- * 1.0 to the score (0.0 is a perfect match).
1120
- */
1121
- distance: 1e3
1122
- };
1123
- function applyDefaults(options) {
1124
- return {
1125
- ...DEFAULT_OPTIONS,
1126
- ...options
1127
- };
1128
- }
1129
- const MAX_BITS$1 = 32;
1130
- function bitap(text, pattern, loc) {
1131
- let opts = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1132
- if (pattern.length > MAX_BITS$1)
1133
- throw new Error("Pattern too long for this browser.");
1134
- const options = applyDefaults(opts), s = getAlphabetFromPattern(pattern);
1135
- function getBitapScore(e, x) {
1136
- const accuracy = e / pattern.length, proximity = Math.abs(loc - x);
1137
- return options.distance ? accuracy + proximity / options.distance : proximity ? 1 : accuracy;
1138
- }
1139
- let scoreThreshold = options.threshold, bestLoc = text.indexOf(pattern, loc);
1140
- 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)));
1141
- const matchmask = 1 << pattern.length - 1;
1142
- bestLoc = -1;
1143
- let binMin, binMid, binMax = pattern.length + text.length, lastRd = [];
1144
- for (let d = 0; d < pattern.length; d++) {
1145
- for (binMin = 0, binMid = binMax; binMin < binMid; )
1146
- getBitapScore(d, loc + binMid) <= scoreThreshold ? binMin = binMid : binMax = binMid, binMid = Math.floor((binMax - binMin) / 2 + binMin);
1147
- binMax = binMid;
1148
- let start = Math.max(1, loc - binMid + 1);
1149
- const finish = Math.min(loc + binMid, text.length) + pattern.length, rd = new Array(finish + 2);
1150
- rd[finish + 1] = (1 << d) - 1;
1151
- for (let j = finish; j >= start; j--) {
1152
- const charMatch = s[text.charAt(j - 1)];
1153
- 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) {
1154
- const score = getBitapScore(d, j - 1);
1155
- if (score <= scoreThreshold)
1156
- if (scoreThreshold = score, bestLoc = j - 1, bestLoc > loc)
1157
- start = Math.max(1, 2 * loc - bestLoc);
1158
- else
1159
- break;
1160
- }
1161
- }
1162
- if (getBitapScore(d + 1, loc) > scoreThreshold)
1163
- break;
1164
- lastRd = rd;
1165
- }
1166
- return bestLoc;
1167
- }
1168
- function getAlphabetFromPattern(pattern) {
1169
- const s = {};
1170
- for (let i = 0; i < pattern.length; i++)
1171
- s[pattern.charAt(i)] = 0;
1172
- for (let i = 0; i < pattern.length; i++)
1173
- s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;
1174
- return s;
1175
- }
1176
- function match(text, pattern, searchLocation) {
1177
- if (text === null || pattern === null || searchLocation === null)
1178
- throw new Error("Null input. (match())");
1179
- const loc = Math.max(0, Math.min(searchLocation, text.length));
1180
- if (text === pattern)
1181
- return 0;
1182
- if (text.length) {
1183
- if (text.substring(loc, loc + pattern.length) === pattern)
1184
- return loc;
1185
- } else return -1;
1186
- return bitap(text, pattern, loc);
1187
- }
1188
- function createPatchObject(start1, start2) {
1189
- return {
1190
- diffs: [],
1191
- start1,
1192
- start2,
1193
- utf8Start1: start1,
1194
- utf8Start2: start2,
1195
- length1: 0,
1196
- length2: 0,
1197
- utf8Length1: 0,
1198
- utf8Length2: 0
1199
- };
1200
- }
1201
- function diffText1(diffs) {
1202
- const text = [];
1203
- for (let x = 0; x < diffs.length; x++)
1204
- diffs[x][0] !== DIFF_INSERT && (text[x] = diffs[x][1]);
1205
- return text.join("");
1206
- }
1207
- function diffText2(diffs) {
1208
- const text = [];
1209
- for (let x = 0; x < diffs.length; x++)
1210
- diffs[x][0] !== DIFF_DELETE && (text[x] = diffs[x][1]);
1211
- return text.join("");
1212
- }
1213
- function countUtf8Bytes(str) {
1214
- let bytes = 0;
1215
- for (let i = 0; i < str.length; i++) {
1216
- const codePoint = str.codePointAt(i);
1217
- if (typeof codePoint > "u")
1218
- throw new Error("Failed to get codepoint");
1219
- bytes += utf8len(codePoint);
1220
- }
1221
- return bytes;
1222
- }
1223
- function adjustIndiciesToUcs2(patches, base) {
1224
- let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, byteOffset = 0, idx = 0;
1225
- function advanceTo(target) {
1226
- for (; byteOffset < target; ) {
1227
- const codePoint = base.codePointAt(idx);
1228
- if (typeof codePoint > "u")
1229
- return idx;
1230
- byteOffset += utf8len(codePoint), codePoint > 65535 ? idx += 2 : idx += 1;
1231
- }
1232
- if (!options.allowExceedingIndices && byteOffset !== target)
1233
- throw new Error("Failed to determine byte offset");
1234
- return idx;
1235
- }
1236
- const adjusted = [];
1237
- for (const patch of patches)
1238
- adjusted.push({
1239
- diffs: patch.diffs.map((diff2) => cloneDiff(diff2)),
1240
- start1: advanceTo(patch.start1),
1241
- start2: advanceTo(patch.start2),
1242
- utf8Start1: patch.utf8Start1,
1243
- utf8Start2: patch.utf8Start2,
1244
- length1: patch.length1,
1245
- length2: patch.length2,
1246
- utf8Length1: patch.utf8Length1,
1247
- utf8Length2: patch.utf8Length2
1248
- });
1249
- return adjusted;
1250
- }
1251
- function utf8len(codePoint) {
1252
- return codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
1253
- }
1254
- const MAX_BITS = 32, DEFAULT_MARGIN = 4, DEFAULT_OPTS = {
1255
- margin: 4
1256
- };
1257
- function getDefaultOpts() {
1258
- let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1259
- return {
1260
- ...DEFAULT_OPTS,
1261
- ...opts
1262
- };
1263
- }
1264
- function make(a, b, options) {
1265
- if (typeof a == "string" && typeof b == "string") {
1266
- let diffs = diff(a, b, {
1267
- checkLines: !0
1268
- });
1269
- return diffs.length > 2 && (diffs = cleanupSemantic(diffs), diffs = cleanupEfficiency(diffs)), _make(a, diffs, getDefaultOpts(options));
1270
- }
1271
- if (a && Array.isArray(a) && typeof b > "u")
1272
- return _make(diffText1(a), a, getDefaultOpts(options));
1273
- if (typeof a == "string" && b && Array.isArray(b))
1274
- return _make(a, b, getDefaultOpts(options));
1275
- throw new Error("Unknown call format to make()");
1276
- }
1277
- function _make(textA, diffs, options) {
1278
- if (diffs.length === 0)
1279
- return [];
1280
- const patches = [];
1281
- let patch = createPatchObject(0, 0), patchDiffLength = 0, charCount1 = 0, charCount2 = 0, utf8Count1 = 0, utf8Count2 = 0, prepatchText = textA, postpatchText = textA;
1282
- for (let x = 0; x < diffs.length; x++) {
1283
- const currentDiff = diffs[x], [diffType, diffText] = currentDiff, diffTextLength = diffText.length, diffByteLength = countUtf8Bytes(diffText);
1284
- switch (!patchDiffLength && diffType !== DIFF_EQUAL && (patch.start1 = charCount1, patch.start2 = charCount2, patch.utf8Start1 = utf8Count1, patch.utf8Start2 = utf8Count2), diffType) {
1285
- case DIFF_INSERT:
1286
- patch.diffs[patchDiffLength++] = currentDiff, patch.length2 += diffTextLength, patch.utf8Length2 += diffByteLength, postpatchText = postpatchText.substring(0, charCount2) + diffText + postpatchText.substring(charCount2);
1287
- break;
1288
- case DIFF_DELETE:
1289
- patch.length1 += diffTextLength, patch.utf8Length1 += diffByteLength, patch.diffs[patchDiffLength++] = currentDiff, postpatchText = postpatchText.substring(0, charCount2) + postpatchText.substring(charCount2 + diffTextLength);
1290
- break;
1291
- case DIFF_EQUAL:
1292
- 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);
1293
- break;
1294
- default:
1295
- throw new Error("Unknown diff type");
1296
- }
1297
- diffType !== DIFF_INSERT && (charCount1 += diffTextLength, utf8Count1 += diffByteLength), diffType !== DIFF_DELETE && (charCount2 += diffTextLength, utf8Count2 += diffByteLength);
1298
- }
1299
- return patchDiffLength && (addContext(patch, prepatchText, options), patches.push(patch)), patches;
1300
- }
1301
- function addContext(patch, text, opts) {
1302
- if (text.length === 0)
1303
- return;
1304
- let pattern = text.substring(patch.start2, patch.start2 + patch.length1), padding = 0;
1305
- for (; text.indexOf(pattern) !== text.lastIndexOf(pattern) && pattern.length < MAX_BITS - opts.margin - opts.margin; )
1306
- padding += opts.margin, pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding);
1307
- padding += opts.margin;
1308
- let prefixStart = patch.start2 - padding;
1309
- prefixStart >= 1 && isLowSurrogate(text[prefixStart]) && prefixStart--;
1310
- const prefix = text.substring(prefixStart, patch.start2);
1311
- prefix && patch.diffs.unshift([DIFF_EQUAL, prefix]);
1312
- const prefixLength = prefix.length, prefixUtf8Length = countUtf8Bytes(prefix);
1313
- let suffixEnd = patch.start2 + patch.length1 + padding;
1314
- suffixEnd < text.length && isLowSurrogate(text[suffixEnd]) && suffixEnd++;
1315
- const suffix = text.substring(patch.start2 + patch.length1, suffixEnd);
1316
- suffix && patch.diffs.push([DIFF_EQUAL, suffix]);
1317
- const suffixLength = suffix.length, suffixUtf8Length = countUtf8Bytes(suffix);
1318
- 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;
1319
- }
1320
- function levenshtein(diffs) {
1321
- let leven = 0, insertions = 0, deletions = 0;
1322
- for (let x = 0; x < diffs.length; x++) {
1323
- const op = diffs[x][0], data = diffs[x][1];
1324
- switch (op) {
1325
- case DIFF_INSERT:
1326
- insertions += data.length;
1327
- break;
1328
- case DIFF_DELETE:
1329
- deletions += data.length;
1330
- break;
1331
- case DIFF_EQUAL:
1332
- leven += Math.max(insertions, deletions), insertions = 0, deletions = 0;
1333
- break;
1334
- default:
1335
- throw new Error("Unknown diff operation.");
1336
- }
1337
- }
1338
- return leven += Math.max(insertions, deletions), leven;
1339
- }
1340
- function xIndex(diffs, loc) {
1341
- let chars1 = 0, chars2 = 0, lastChars1 = 0, lastChars2 = 0, x;
1342
- 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++)
1343
- lastChars1 = chars1, lastChars2 = chars2;
1344
- return diffs.length !== x && diffs[x][0] === DIFF_DELETE ? lastChars2 : lastChars2 + (loc - lastChars1);
1345
- }
1346
- function addPadding(patches) {
1347
- const paddingLength = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1348
- let nullPadding = "";
1349
- for (let x = 1; x <= paddingLength; x++)
1350
- nullPadding += String.fromCharCode(x);
1351
- for (const p of patches)
1352
- p.start1 += paddingLength, p.start2 += paddingLength, p.utf8Start1 += paddingLength, p.utf8Start2 += paddingLength;
1353
- let patch = patches[0], diffs = patch.diffs;
1354
- if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL)
1355
- 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;
1356
- else if (paddingLength > diffs[0][1].length) {
1357
- const firstDiffLength = diffs[0][1].length, extraLength = paddingLength - firstDiffLength;
1358
- 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;
1359
- }
1360
- if (patch = patches[patches.length - 1], diffs = patch.diffs, diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL)
1361
- diffs.push([DIFF_EQUAL, nullPadding]), patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
1362
- else if (paddingLength > diffs[diffs.length - 1][1].length) {
1363
- const extraLength = paddingLength - diffs[diffs.length - 1][1].length;
1364
- diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength), patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
1365
- }
1366
- return nullPadding;
1367
- }
1368
- function splitMax(patches) {
1369
- let margin = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1370
- const patchSize = MAX_BITS;
1371
- for (let x = 0; x < patches.length; x++) {
1372
- if (patches[x].length1 <= patchSize)
1373
- continue;
1374
- const bigpatch = patches[x];
1375
- patches.splice(x--, 1);
1376
- let start1 = bigpatch.start1, start2 = bigpatch.start2, preContext = "";
1377
- for (; bigpatch.diffs.length !== 0; ) {
1378
- const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);
1379
- let empty = !0;
1380
- if (preContext !== "") {
1381
- const precontextByteCount = countUtf8Bytes(preContext);
1382
- patch.length1 = preContext.length, patch.utf8Length1 = precontextByteCount, patch.length2 = preContext.length, patch.utf8Length2 = precontextByteCount, patch.diffs.push([DIFF_EQUAL, preContext]);
1383
- }
1384
- for (; bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin; ) {
1385
- const diffType = bigpatch.diffs[0][0];
1386
- let diffText = bigpatch.diffs[0][1], diffTextByteCount = countUtf8Bytes(diffText);
1387
- if (diffType === DIFF_INSERT) {
1388
- patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length;
1389
- const diff2 = bigpatch.diffs.shift();
1390
- diff2 && patch.diffs.push(diff2), empty = !1;
1391
- } 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));
1392
- }
1393
- preContext = diffText2(patch.diffs), preContext = preContext.substring(preContext.length - margin);
1394
- const postContext = diffText1(bigpatch.diffs).substring(0, margin), postContextByteCount = countUtf8Bytes(postContext);
1395
- 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);
1396
- }
1397
- }
1398
- }
1399
- function apply$4(patches, originalText) {
1400
- let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1401
- if (typeof patches == "string")
1402
- throw new Error("Patches must be an array - pass the patch to `parsePatch()` first");
1403
- let text = originalText;
1404
- if (patches.length === 0)
1405
- return [text, []];
1406
- const parsed = adjustIndiciesToUcs2(patches, text, {
1407
- allowExceedingIndices: opts.allowExceedingIndices
1408
- }), margin = opts.margin || DEFAULT_MARGIN, deleteThreshold = opts.deleteThreshold || 0.4, nullPadding = addPadding(parsed, margin);
1409
- text = nullPadding + text + nullPadding, splitMax(parsed, margin);
1410
- let delta = 0;
1411
- const results = [];
1412
- for (let x = 0; x < parsed.length; x++) {
1413
- const expectedLoc = parsed[x].start2 + delta, text1 = diffText1(parsed[x].diffs);
1414
- let startLoc, endLoc = -1;
1415
- 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)
1416
- results[x] = !1, delta -= parsed[x].length2 - parsed[x].length1;
1417
- else {
1418
- results[x] = !0, delta = startLoc - expectedLoc;
1419
- let text2;
1420
- if (endLoc === -1 ? text2 = text.substring(startLoc, startLoc + text1.length) : text2 = text.substring(startLoc, endLoc + MAX_BITS), text1 === text2)
1421
- text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);
1422
- else {
1423
- let diffs = diff(text1, text2, {
1424
- checkLines: !1
1425
- });
1426
- if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold)
1427
- results[x] = !1;
1428
- else {
1429
- diffs = cleanupSemanticLossless(diffs);
1430
- let index1 = 0, index2 = 0;
1431
- for (let y = 0; y < parsed[x].diffs.length; y++) {
1432
- const mod = parsed[x].diffs[y];
1433
- 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);
1434
- }
1435
- }
1436
- }
1437
- }
1438
- }
1439
- return text = text.substring(nullPadding.length, text.length - nullPadding.length), [text, results];
1440
- }
1441
- function stringify(patches) {
1442
- return patches.map(stringifyPatch).join("");
1443
- }
1444
- function stringifyPatch(patch) {
1445
- const {
1446
- utf8Length1,
1447
- utf8Length2,
1448
- utf8Start1,
1449
- utf8Start2,
1450
- diffs
1451
- } = patch;
1452
- let coords1;
1453
- utf8Length1 === 0 ? coords1 = "".concat(utf8Start1, ",0") : utf8Length1 === 1 ? coords1 = "".concat(utf8Start1 + 1) : coords1 = "".concat(utf8Start1 + 1, ",").concat(utf8Length1);
1454
- let coords2;
1455
- utf8Length2 === 0 ? coords2 = "".concat(utf8Start2, ",0") : utf8Length2 === 1 ? coords2 = "".concat(utf8Start2 + 1) : coords2 = "".concat(utf8Start2 + 1, ",").concat(utf8Length2);
1456
- const text = ["@@ -".concat(coords1, " +").concat(coords2, ` @@
1457
- `)];
1458
- let op;
1459
- for (let x = 0; x < diffs.length; x++) {
1460
- switch (diffs[x][0]) {
1461
- case DIFF_INSERT:
1462
- op = "+";
1463
- break;
1464
- case DIFF_DELETE:
1465
- op = "-";
1466
- break;
1467
- case DIFF_EQUAL:
1468
- op = " ";
1469
- break;
1470
- default:
1471
- throw new Error("Unknown patch operation.");
1472
- }
1473
- text[x + 1] = "".concat(op + encodeURI(diffs[x][1]), `
1474
- `);
1475
- }
1476
- return text.join("").replace(/%20/g, " ");
1477
- }
1478
- const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
1479
- function parse(textline) {
1480
- if (!textline)
1481
- return [];
1482
- const patches = [], lines = textline.split(`
1483
- `);
1484
- let textPointer = 0;
1485
- for (; textPointer < lines.length; ) {
1486
- const m = lines[textPointer].match(patchHeader);
1487
- if (!m)
1488
- throw new Error("Invalid patch string: ".concat(lines[textPointer]));
1489
- const patch = createPatchObject(toInt(m[1]), toInt(m[3]));
1490
- 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; ) {
1491
- const currentLine = lines[textPointer], sign = currentLine.charAt(0);
1492
- if (sign === "@")
1493
- break;
1494
- if (sign === "") {
1495
- textPointer++;
1496
- continue;
1497
- }
1498
- let line;
1499
- try {
1500
- line = decodeURI(currentLine.slice(1));
1501
- } catch {
1502
- throw new Error("Illegal escape in parse: ".concat(currentLine));
1503
- }
1504
- const utf8Diff = countUtf8Bytes(line) - line.length;
1505
- if (sign === "-")
1506
- patch.diffs.push([DIFF_DELETE, line]), patch.length1 -= utf8Diff;
1507
- else if (sign === "+")
1508
- patch.diffs.push([DIFF_INSERT, line]), patch.length2 -= utf8Diff;
1509
- else if (sign === " ")
1510
- patch.diffs.push([DIFF_EQUAL, line]), patch.length1 -= utf8Diff, patch.length2 -= utf8Diff;
1511
- else
1512
- throw new Error('Invalid patch mode "'.concat(sign, '" in: ').concat(line));
1513
- textPointer++;
1514
- }
1515
- }
1516
- return patches;
1517
- }
1518
- function toInt(num) {
1519
- return parseInt(num, 10);
1520
- }
1521
- function setIfMissing(value, path = []) {
1522
- return {
1523
- type: "setIfMissing",
1524
- path,
1525
- value
1526
- };
1527
- }
1528
- function diffMatchPatch$1(currentValue, nextValue, path = []) {
1529
- const patches = make(currentValue, nextValue), patch = stringify(patches);
1530
- return { type: "diffMatchPatch", path, value: patch };
1531
- }
1532
- function insert$1(items, position, path = []) {
1533
- return {
1534
- type: "insert",
1535
- path,
1536
- position,
1537
- items
1538
- };
1539
- }
1540
- function set(value, path = []) {
1541
- return { type: "set", path, value };
1542
- }
1543
- function unset(path = []) {
1544
- return { type: "unset", path };
1545
- }
1546
- const debug$j = debugWithName("operationToPatches");
1547
- debug$j.enabled = !1;
1548
- function createOperationToPatches(types) {
1549
- const textBlockName = types.block.name;
1550
- function insertTextPatch(editor, operation, beforeValue) {
1551
- debug$j.enabled && debug$j("Operation", JSON.stringify(operation, null, 2));
1552
- const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
1553
- if (!block)
1554
- throw new Error("Could not find block");
1555
- const textChild = editor.isTextBlock(block) && editor.isTextSpan(block.children[operation.path[1]]) && block.children[operation.path[1]];
1556
- if (!textChild)
1557
- throw new Error("Could not find child");
1558
- 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);
1559
- return patch.value.length ? [patch] : [];
1560
- }
1561
- function removeTextPatch(editor, operation, beforeValue) {
1562
- const block = editor && editor.children[operation.path[0]];
1563
- if (!block)
1564
- throw new Error("Could not find block");
1565
- const child = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, textChild = editor.isTextSpan(child) ? child : void 0;
1566
- if (child && !textChild)
1567
- throw new Error("Expected span");
1568
- if (!textChild)
1569
- throw new Error("Could not find child");
1570
- 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);
1571
- return patch.value ? [patch] : [];
1572
- }
1573
- function setNodePatch(editor, operation) {
1574
- if (operation.path.length === 1) {
1575
- const block = editor.children[operation.path[0]];
1576
- if (typeof block._key != "string")
1577
- throw new Error("Expected block to have a _key");
1578
- const setNode = omitBy(
1579
- { ...editor.children[operation.path[0]], ...operation.newProperties },
1580
- isUndefined
1581
- );
1582
- return [set(fromSlateValue([setNode], textBlockName)[0], [{ _key: block._key }])];
1583
- } else if (operation.path.length === 2) {
1584
- const block = editor.children[operation.path[0]];
1585
- if (editor.isTextBlock(block)) {
1586
- const child = block.children[operation.path[1]];
1587
- if (child) {
1588
- const blockKey = block._key, childKey = child._key, patches = [], keys = Object.keys(operation.newProperties);
1589
- return keys.forEach((keyName) => {
1590
- if (keys.length === 1 && keyName === "_key") {
1591
- const val = get(operation.newProperties, keyName);
1592
- patches.push(
1593
- set(val, [{ _key: blockKey }, "children", block.children.indexOf(child), keyName])
1594
- );
1595
- } else {
1596
- const val = get(operation.newProperties, keyName);
1597
- patches.push(set(val, [{ _key: blockKey }, "children", { _key: childKey }, keyName]));
1598
- }
1599
- }), patches;
1600
- }
1601
- throw new Error("Could not find a valid child");
1602
- }
1603
- throw new Error("Could not find a valid block");
1604
- } else
1605
- throw new Error(`Unexpected path encountered: ${JSON.stringify(operation.path)}`);
1606
- }
1607
- function insertNodePatch(editor, operation, beforeValue) {
1608
- const block = beforeValue[operation.path[0]], isTextBlock = editor.isTextBlock(block);
1609
- if (operation.path.length === 1) {
1610
- 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;
1611
- return targetKey ? [
1612
- insert$1([fromSlateValue([operation.node], textBlockName)[0]], position, [
1613
- { _key: targetKey }
1614
- ])
1615
- ] : [
1616
- setIfMissing(beforeValue, []),
1617
- insert$1([fromSlateValue([operation.node], textBlockName)[0]], "before", [
1618
- operation.path[0]
1619
- ])
1620
- ];
1621
- } else if (isTextBlock && operation.path.length === 2 && editor.children[operation.path[0]]) {
1622
- const position = block.children.length === 0 || !block.children[operation.path[1] - 1] ? "before" : "after", node = { ...operation.node };
1623
- !node._type && Text.isText(node) && (node._type = "span", node.marks = []);
1624
- const child = fromSlateValue(
1625
- [
1626
- {
1627
- _key: "bogus",
1628
- _type: textBlockName,
1629
- children: [node]
1630
- }
1631
- ],
1632
- textBlockName
1633
- )[0].children[0];
1634
- return [
1635
- insert$1([child], position, [
1636
- { _key: block._key },
1637
- "children",
1638
- block.children.length <= 1 || !block.children[operation.path[1] - 1] ? 0 : { _key: block.children[operation.path[1] - 1]._key }
1639
- ])
1640
- ];
1641
- }
1642
- return debug$j("Something was inserted into a void block. Not producing editor patches."), [];
1643
- }
1644
- function splitNodePatch(editor, operation, beforeValue) {
1645
- const patches = [], splitBlock = editor.children[operation.path[0]];
1646
- if (!editor.isTextBlock(splitBlock))
1647
- throw new Error(
1648
- `Block with path ${JSON.stringify(
1649
- operation.path[0]
1650
- )} is not a text block and can't be split`
1651
- );
1652
- if (operation.path.length === 1) {
1653
- const oldBlock = beforeValue[operation.path[0]];
1654
- if (editor.isTextBlock(oldBlock)) {
1655
- const targetValue = fromSlateValue(
1656
- [editor.children[operation.path[0] + 1]],
1657
- textBlockName
1658
- )[0];
1659
- targetValue && (patches.push(insert$1([targetValue], "after", [{ _key: splitBlock._key }])), oldBlock.children.slice(operation.position).forEach((span) => {
1660
- const path = [{ _key: oldBlock._key }, "children", { _key: span._key }];
1661
- patches.push(unset(path));
1662
- }));
1663
- }
1664
- return patches;
1665
- }
1666
- if (operation.path.length === 2) {
1667
- const splitSpan = splitBlock.children[operation.path[1]];
1668
- if (editor.isTextSpan(splitSpan)) {
1669
- const targetSpans = fromSlateValue(
1670
- [
1671
- {
1672
- ...splitBlock,
1673
- children: splitBlock.children.slice(operation.path[1] + 1, operation.path[1] + 2)
1674
- }
1675
- ],
1676
- textBlockName
1677
- )[0].children;
1678
- patches.push(
1679
- insert$1(targetSpans, "after", [
1680
- { _key: splitBlock._key },
1681
- "children",
1682
- { _key: splitSpan._key }
1683
- ])
1684
- ), patches.push(
1685
- set(splitSpan.text, [
1686
- { _key: splitBlock._key },
1687
- "children",
1688
- { _key: splitSpan._key },
1689
- "text"
1690
- ])
1691
- );
1692
- }
1693
- return patches;
1694
- }
1695
- return patches;
1696
- }
1697
- function removeNodePatch(editor, operation, beforeValue) {
1698
- const block = beforeValue[operation.path[0]];
1699
- if (operation.path.length === 1) {
1700
- if (block && block._key)
1701
- return [unset([{ _key: block._key }])];
1702
- throw new Error("Block not found");
1703
- } else if (editor.isTextBlock(block) && operation.path.length === 2) {
1704
- const spanToRemove = editor.isTextBlock(block) && block.children && block.children[operation.path[1]];
1705
- return spanToRemove ? [unset([{ _key: block._key }, "children", { _key: spanToRemove._key }])] : (debug$j("Span not found in editor trying to remove node"), []);
1706
- } else
1707
- return debug$j("Not creating patch inside object block"), [];
1708
- }
1709
- function mergeNodePatch(editor, operation, beforeValue) {
1710
- const patches = [], block = beforeValue[operation.path[0]], targetBlock = editor.children[operation.path[0]];
1711
- if (operation.path.length === 1)
1712
- if (block != null && block._key) {
1713
- const newBlock = fromSlateValue([editor.children[operation.path[0] - 1]], textBlockName)[0];
1714
- patches.push(set(newBlock, [{ _key: newBlock._key }])), patches.push(unset([{ _key: block._key }]));
1715
- } else
1716
- throw new Error("Target key not found!");
1717
- else if (operation.path.length === 2 && editor.isTextBlock(targetBlock)) {
1718
- const mergedSpan = editor.isTextBlock(block) && block.children[operation.path[1]] || void 0, targetSpan = targetBlock.children[operation.path[1] - 1];
1719
- editor.isTextSpan(targetSpan) && (patches.push(
1720
- set(targetSpan.text, [{ _key: block._key }, "children", { _key: targetSpan._key }, "text"])
1721
- ), mergedSpan && patches.push(unset([{ _key: block._key }, "children", { _key: mergedSpan._key }])));
1722
- } else
1723
- debug$j("Void nodes can't be merged, not creating any patches");
1724
- return patches;
1725
- }
1726
- function moveNodePatch(editor, operation, beforeValue) {
1727
- const patches = [], block = beforeValue[operation.path[0]], targetBlock = beforeValue[operation.newPath[0]];
1728
- if (operation.path.length === 1) {
1729
- const position = operation.path[0] > operation.newPath[0] ? "before" : "after";
1730
- patches.push(unset([{ _key: block._key }])), patches.push(
1731
- insert$1([fromSlateValue([block], textBlockName)[0]], position, [{ _key: targetBlock._key }])
1732
- );
1733
- } else if (operation.path.length === 2 && editor.isTextBlock(block) && editor.isTextBlock(targetBlock)) {
1734
- 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]];
1735
- patches.push(unset([{ _key: block._key }, "children", { _key: child._key }])), patches.push(
1736
- insert$1([childToInsert], position, [
1737
- { _key: targetBlock._key },
1738
- "children",
1739
- { _key: targetChild._key }
1740
- ])
1741
- );
1742
- }
1743
- return patches;
1744
- }
1745
- return {
1746
- insertNodePatch,
1747
- insertTextPatch,
1748
- mergeNodePatch,
1749
- moveNodePatch,
1750
- removeNodePatch,
1751
- removeTextPatch,
1752
- setNodePatch,
1753
- splitNodePatch
1754
- };
1755
- }
1756
- const debug$i = debugWithName("API:editable");
1757
- function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1758
- return function(editor) {
1759
- return portableTextEditor.setEditable({
1760
- focus: () => {
1761
- ReactEditor.focus(editor);
1762
- },
1763
- blur: () => {
1764
- ReactEditor.blur(editor);
1765
- },
1766
- toggleMark: (mark) => {
1767
- editor.pteToggleMark(mark);
1768
- },
1769
- toggleList: (listStyle) => {
1770
- editor.pteToggleListItem(listStyle);
1771
- },
1772
- toggleBlockStyle: (blockStyle) => {
1773
- editor.pteToggleBlockStyle(blockStyle);
1774
- },
1775
- isMarkActive: (mark) => {
1776
- try {
1777
- return editor.pteIsMarkActive(mark);
1778
- } catch (err) {
1779
- return console.warn(err), !1;
930
+ const debug$i = debugWithName("API:editable");
931
+ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
932
+ return function(editor) {
933
+ return portableTextEditor.setEditable({
934
+ focus: () => {
935
+ ReactEditor.focus(editor);
936
+ },
937
+ blur: () => {
938
+ ReactEditor.blur(editor);
939
+ },
940
+ toggleMark: (mark) => {
941
+ editor.pteToggleMark(mark);
942
+ },
943
+ toggleList: (listStyle) => {
944
+ editor.pteToggleListItem(listStyle);
945
+ },
946
+ toggleBlockStyle: (blockStyle) => {
947
+ editor.pteToggleBlockStyle(blockStyle);
948
+ },
949
+ isMarkActive: (mark) => {
950
+ try {
951
+ return editor.pteIsMarkActive(mark);
952
+ } catch (err) {
953
+ return console.warn(err), !1;
1780
954
  }
1781
955
  },
1782
956
  marks: () => ({
@@ -2079,275 +1253,803 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
2079
1253
  }
2080
1254
  }), Editor.normalize(editor), editor.onChange();
2081
1255
  }
2082
- },
2083
- getSelection: () => {
2084
- let ptRange = null;
2085
- if (editor.selection) {
2086
- const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
2087
- if (existing)
2088
- return existing;
2089
- ptRange = toPortableTextRange(
2090
- fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
2091
- editor.selection,
2092
- types
2093
- ), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
1256
+ },
1257
+ getSelection: () => {
1258
+ let ptRange = null;
1259
+ if (editor.selection) {
1260
+ const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
1261
+ if (existing)
1262
+ return existing;
1263
+ ptRange = toPortableTextRange(
1264
+ fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1265
+ editor.selection,
1266
+ types
1267
+ ), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
1268
+ }
1269
+ return ptRange;
1270
+ },
1271
+ getValue: () => fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1272
+ isCollapsedSelection: () => !!editor.selection && Range.isCollapsed(editor.selection),
1273
+ isExpandedSelection: () => !!editor.selection && Range.isExpanded(editor.selection),
1274
+ insertBreak: () => {
1275
+ editor.insertBreak(), editor.onChange();
1276
+ },
1277
+ getFragment: () => fromSlateValue(editor.getFragment(), types.block.name),
1278
+ isSelectionsOverlapping: (selectionA, selectionB) => {
1279
+ const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
1280
+ return Range.isRange(rangeA) && Range.isRange(rangeB) && Range.includes(rangeA, rangeB);
1281
+ }
1282
+ }), editor;
1283
+ };
1284
+ }
1285
+ function createWithInsertBreak(types) {
1286
+ return function(editor) {
1287
+ const { insertBreak } = editor;
1288
+ return editor.insertBreak = () => {
1289
+ if (editor.selection) {
1290
+ const focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = Node.descendant(editor, focusBlockPath);
1291
+ if (editor.isTextBlock(focusBlock)) {
1292
+ const [, end] = Range.edges(editor.selection), isEndAtStartOfNode = Editor.isStart(editor, end, end.path), isEmptyTextBlock = focusBlock && isEqualToEmptyEditor([focusBlock], types);
1293
+ if (isEndAtStartOfNode && !isEmptyTextBlock) {
1294
+ Editor.insertNode(editor, editor.pteCreateEmptyBlock());
1295
+ const [nextBlockPath] = Path.next(focusBlockPath);
1296
+ Transforms.select(editor, {
1297
+ anchor: { path: [nextBlockPath, 0], offset: 0 },
1298
+ focus: { path: [nextBlockPath, 0], offset: 0 }
1299
+ }), editor.onChange();
1300
+ return;
1301
+ }
1302
+ }
1303
+ }
1304
+ insertBreak();
1305
+ }, editor;
1306
+ };
1307
+ }
1308
+ function createWithMaxBlocks(maxBlocks) {
1309
+ return function(editor) {
1310
+ const { apply: apply2 } = editor;
1311
+ return editor.apply = (operation) => {
1312
+ const rows = maxBlocks;
1313
+ rows > 0 && editor.children.length >= rows && (operation.type === "insert_node" || operation.type === "split_node") && operation.path.length === 1 || apply2(operation);
1314
+ }, editor;
1315
+ };
1316
+ }
1317
+ const PRESERVE_KEYS = /* @__PURE__ */ new WeakMap();
1318
+ function withPreserveKeys(editor, fn) {
1319
+ const prev = isPreservingKeys(editor);
1320
+ PRESERVE_KEYS.set(editor, !0), fn(), PRESERVE_KEYS.set(editor, prev);
1321
+ }
1322
+ function isPreservingKeys(editor) {
1323
+ return PRESERVE_KEYS.get(editor);
1324
+ }
1325
+ function createWithObjectKeys(schemaTypes, keyGenerator) {
1326
+ return function(editor) {
1327
+ PRESERVE_KEYS.set(editor, !1);
1328
+ const { apply: apply2, normalizeNode } = editor;
1329
+ return editor.apply = (operation) => {
1330
+ if (operation.type === "split_node") {
1331
+ const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.properties);
1332
+ operation.properties = {
1333
+ ...operation.properties,
1334
+ ...withNewKey ? { _key: keyGenerator() } : {}
1335
+ };
1336
+ }
1337
+ if (operation.type === "insert_node") {
1338
+ const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.node);
1339
+ Editor.isEditor(operation.node) || (operation.node = {
1340
+ ...operation.node,
1341
+ ...withNewKey ? { _key: keyGenerator() } : {}
1342
+ });
1343
+ }
1344
+ apply2(operation);
1345
+ }, editor.normalizeNode = (entry) => {
1346
+ const [node, path] = entry;
1347
+ if (Element$1.isElement(node) && node._type === schemaTypes.block.name) {
1348
+ node._key || Transforms.setNodes(editor, { _key: keyGenerator() }, { at: path });
1349
+ for (const [child, childPath] of Node.children(editor, path))
1350
+ if (!child._key) {
1351
+ Transforms.setNodes(editor, { _key: keyGenerator() }, { at: childPath });
1352
+ return;
1353
+ }
1354
+ }
1355
+ normalizeNode(entry);
1356
+ }, editor;
1357
+ };
1358
+ }
1359
+ function isHighSurrogate(char) {
1360
+ const charCode = char.charCodeAt(0);
1361
+ return charCode >= 55296 && charCode <= 56319;
1362
+ }
1363
+ function isLowSurrogate(char) {
1364
+ const charCode = char.charCodeAt(0);
1365
+ return charCode >= 56320 && charCode <= 57343;
1366
+ }
1367
+ function cloneDiff(diff2) {
1368
+ const [type, patch] = diff2;
1369
+ return [type, patch];
1370
+ }
1371
+ function getCommonOverlap(textA, textB) {
1372
+ let text1 = textA, text2 = textB;
1373
+ const text1Length = text1.length, text2Length = text2.length;
1374
+ if (text1Length === 0 || text2Length === 0)
1375
+ return 0;
1376
+ text1Length > text2Length ? text1 = text1.substring(text1Length - text2Length) : text1Length < text2Length && (text2 = text2.substring(0, text1Length));
1377
+ const textLength = Math.min(text1Length, text2Length);
1378
+ if (text1 === text2)
1379
+ return textLength;
1380
+ let best = 0, length = 1;
1381
+ for (let found = 0; found !== -1; ) {
1382
+ const pattern = text1.substring(textLength - length);
1383
+ if (found = text2.indexOf(pattern), found === -1)
1384
+ return best;
1385
+ length += found, (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) && (best = length, length++);
1386
+ }
1387
+ return best;
1388
+ }
1389
+ function getCommonPrefix(text1, text2) {
1390
+ if (!text1 || !text2 || text1[0] !== text2[0])
1391
+ return 0;
1392
+ let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerStart = 0;
1393
+ for (; pointerMin < pointerMid; )
1394
+ text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid) ? (pointerMin = pointerMid, pointerStart = pointerMin) : pointerMax = pointerMid, pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);
1395
+ return pointerMid;
1396
+ }
1397
+ function getCommonSuffix(text1, text2) {
1398
+ if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1])
1399
+ return 0;
1400
+ let pointerMin = 0, pointerMax = Math.min(text1.length, text2.length), pointerMid = pointerMax, pointerEnd = 0;
1401
+ for (; pointerMin < pointerMid; )
1402
+ 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);
1403
+ return pointerMid;
1404
+ }
1405
+ function cleanupSemantic(rawDiffs) {
1406
+ let diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
1407
+ const equalities = [];
1408
+ let equalitiesLength = 0, lastEquality = null, pointer = 0, lengthInsertions1 = 0, lengthDeletions1 = 0, lengthInsertions2 = 0, lengthDeletions2 = 0;
1409
+ for (; pointer < diffs.length; )
1410
+ 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++;
1411
+ for (hasChanges && (diffs = cleanupMerge(diffs)), diffs = cleanupSemanticLossless(diffs), pointer = 1; pointer < diffs.length; ) {
1412
+ if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {
1413
+ const deletion = diffs[pointer - 1][1], insertion = diffs[pointer][1], overlapLength1 = getCommonOverlap(deletion, insertion), overlapLength2 = getCommonOverlap(insertion, deletion);
1414
+ 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++;
1415
+ }
1416
+ pointer++;
1417
+ }
1418
+ return diffs;
1419
+ }
1420
+ const nonAlphaNumericRegex = /[^a-zA-Z0-9]/, whitespaceRegex = /\s/, linebreakRegex = /[\r\n]/, blanklineEndRegex = /\n\r?\n$/, blanklineStartRegex = /^\r?\n\r?\n/;
1421
+ function cleanupSemanticLossless(rawDiffs) {
1422
+ const diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
1423
+ function diffCleanupSemanticScore(one, two) {
1424
+ if (!one || !two)
1425
+ return 6;
1426
+ 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);
1427
+ return blankLine1 || blankLine2 ? 5 : lineBreak1 || lineBreak2 ? 4 : nonAlphaNumeric1 && !whitespace1 && whitespace2 ? 3 : whitespace1 || whitespace2 ? 2 : nonAlphaNumeric1 || nonAlphaNumeric2 ? 1 : 0;
1428
+ }
1429
+ let pointer = 1;
1430
+ for (; pointer < diffs.length - 1; ) {
1431
+ if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {
1432
+ let equality1 = diffs[pointer - 1][1], edit = diffs[pointer][1], equality2 = diffs[pointer + 1][1];
1433
+ const commonOffset = getCommonSuffix(equality1, edit);
1434
+ if (commonOffset) {
1435
+ const commonString = edit.substring(edit.length - commonOffset);
1436
+ equality1 = equality1.substring(0, equality1.length - commonOffset), edit = commonString + edit.substring(0, edit.length - commonOffset), equality2 = commonString + equality2;
1437
+ }
1438
+ let bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2, bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
1439
+ for (; edit.charAt(0) === equality2.charAt(0); ) {
1440
+ equality1 += edit.charAt(0), edit = edit.substring(1) + equality2.charAt(0), equality2 = equality2.substring(1);
1441
+ const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);
1442
+ score >= bestScore && (bestScore = score, bestEquality1 = equality1, bestEdit = edit, bestEquality2 = equality2);
1443
+ }
1444
+ 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--));
1445
+ }
1446
+ pointer++;
1447
+ }
1448
+ return diffs;
1449
+ }
1450
+ function cleanupMerge(rawDiffs) {
1451
+ let diffs = rawDiffs.map((diff2) => cloneDiff(diff2));
1452
+ diffs.push([DIFF_EQUAL, ""]);
1453
+ let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "", commonlength;
1454
+ for (; pointer < diffs.length; )
1455
+ switch (diffs[pointer][0]) {
1456
+ case DIFF_INSERT:
1457
+ countInsert++, textInsert += diffs[pointer][1], pointer++;
1458
+ break;
1459
+ case DIFF_DELETE:
1460
+ countDelete++, textDelete += diffs[pointer][1], pointer++;
1461
+ break;
1462
+ case DIFF_EQUAL:
1463
+ 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 = "";
1464
+ break;
1465
+ default:
1466
+ throw new Error("Unknown diff operation");
1467
+ }
1468
+ diffs[diffs.length - 1][1] === "" && diffs.pop();
1469
+ let hasChanges = !1;
1470
+ for (pointer = 1; pointer < diffs.length - 1; )
1471
+ 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++;
1472
+ return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
1473
+ }
1474
+ function trueCount() {
1475
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)
1476
+ args[_key] = arguments[_key];
1477
+ return args.reduce((n, bool) => n + (bool ? 1 : 0), 0);
1478
+ }
1479
+ function cleanupEfficiency(rawDiffs) {
1480
+ let editCost = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 4, diffs = rawDiffs.map((diff2) => cloneDiff(diff2)), hasChanges = !1;
1481
+ const equalities = [];
1482
+ let equalitiesLength = 0, lastEquality = null, pointer = 0, preIns = !1, preDel = !1, postIns = !1, postDel = !1;
1483
+ for (; pointer < diffs.length; )
1484
+ 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++;
1485
+ return hasChanges && (diffs = cleanupMerge(diffs)), diffs;
1486
+ }
1487
+ function bisect(text1, text2, deadline) {
1488
+ 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);
1489
+ for (let x = 0; x < vLength; x++)
1490
+ v1[x] = -1, v2[x] = -1;
1491
+ v1[vOffset + 1] = 0, v2[vOffset + 1] = 0;
1492
+ const delta = text1Length - text2Length, front = delta % 2 !== 0;
1493
+ let k1start = 0, k1end = 0, k2start = 0, k2end = 0;
1494
+ for (let d = 0; d < maxD && !(Date.now() > deadline); d++) {
1495
+ for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
1496
+ const k1Offset = vOffset + k1;
1497
+ let x1;
1498
+ k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1] ? x1 = v1[k1Offset + 1] : x1 = v1[k1Offset - 1] + 1;
1499
+ let y1 = x1 - k1;
1500
+ for (; x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1); )
1501
+ x1++, y1++;
1502
+ if (v1[k1Offset] = x1, x1 > text1Length)
1503
+ k1end += 2;
1504
+ else if (y1 > text2Length)
1505
+ k1start += 2;
1506
+ else if (front) {
1507
+ const k2Offset = vOffset + delta - k1;
1508
+ if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
1509
+ const x2 = text1Length - v2[k2Offset];
1510
+ if (x1 >= x2)
1511
+ return bisectSplit(text1, text2, x1, y1, deadline);
1512
+ }
1513
+ }
1514
+ }
1515
+ for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
1516
+ const k2Offset = vOffset + k2;
1517
+ let x2;
1518
+ k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1] ? x2 = v2[k2Offset + 1] : x2 = v2[k2Offset - 1] + 1;
1519
+ let y2 = x2 - k2;
1520
+ for (; x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1); )
1521
+ x2++, y2++;
1522
+ if (v2[k2Offset] = x2, x2 > text1Length)
1523
+ k2end += 2;
1524
+ else if (y2 > text2Length)
1525
+ k2start += 2;
1526
+ else if (!front) {
1527
+ const k1Offset = vOffset + delta - k2;
1528
+ if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
1529
+ const x1 = v1[k1Offset], y1 = vOffset + x1 - k1Offset;
1530
+ if (x2 = text1Length - x2, x1 >= x2)
1531
+ return bisectSplit(text1, text2, x1, y1, deadline);
2094
1532
  }
2095
- return ptRange;
2096
- },
2097
- getValue: () => fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
2098
- isCollapsedSelection: () => !!editor.selection && Range.isCollapsed(editor.selection),
2099
- isExpandedSelection: () => !!editor.selection && Range.isExpanded(editor.selection),
2100
- insertBreak: () => {
2101
- editor.insertBreak(), editor.onChange();
2102
- },
2103
- getFragment: () => fromSlateValue(editor.getFragment(), types.block.name),
2104
- isSelectionsOverlapping: (selectionA, selectionB) => {
2105
- const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
2106
- return Range.isRange(rangeA) && Range.isRange(rangeB) && Range.includes(rangeA, rangeB);
2107
1533
  }
2108
- }), editor;
1534
+ }
1535
+ }
1536
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1537
+ }
1538
+ function bisectSplit(text1, text2, x, y, deadline) {
1539
+ const text1a = text1.substring(0, x), text2a = text2.substring(0, y), text1b = text1.substring(x), text2b = text2.substring(y), diffs = doDiff(text1a, text2a, {
1540
+ checkLines: !1,
1541
+ deadline
1542
+ }), diffsb = doDiff(text1b, text2b, {
1543
+ checkLines: !1,
1544
+ deadline
1545
+ });
1546
+ return diffs.concat(diffsb);
1547
+ }
1548
+ function findHalfMatch(text1, text2) {
1549
+ if ((arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 1) <= 0)
1550
+ return null;
1551
+ const longText = text1.length > text2.length ? text1 : text2, shortText = text1.length > text2.length ? text2 : text1;
1552
+ if (longText.length < 4 || shortText.length * 2 < longText.length)
1553
+ return null;
1554
+ const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4)), halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));
1555
+ let halfMatch;
1556
+ if (halfMatch1 && halfMatch2)
1557
+ halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;
1558
+ else {
1559
+ if (!halfMatch1 && !halfMatch2)
1560
+ return null;
1561
+ halfMatch2 ? halfMatch1 || (halfMatch = halfMatch2) : halfMatch = halfMatch1;
1562
+ }
1563
+ if (!halfMatch)
1564
+ throw new Error("Unable to find a half match.");
1565
+ let text1A, text1B, text2A, text2B;
1566
+ 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]);
1567
+ const midCommon = halfMatch[4];
1568
+ return [text1A, text1B, text2A, text2B, midCommon];
1569
+ }
1570
+ function halfMatchI(longText, shortText, i) {
1571
+ const seed = longText.slice(i, i + Math.floor(longText.length / 4));
1572
+ let j = -1, bestCommon = "", bestLongTextA, bestLongTextB, bestShortTextA, bestShortTextB;
1573
+ for (; (j = shortText.indexOf(seed, j + 1)) !== -1; ) {
1574
+ const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j)), suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));
1575
+ 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));
1576
+ }
1577
+ return bestCommon.length * 2 >= longText.length ? [bestLongTextA || "", bestLongTextB || "", bestShortTextA || "", bestShortTextB || "", bestCommon || ""] : null;
1578
+ }
1579
+ function charsToLines(diffs, lineArray) {
1580
+ for (let x = 0; x < diffs.length; x++) {
1581
+ const chars = diffs[x][1], text = [];
1582
+ for (let y = 0; y < chars.length; y++)
1583
+ text[y] = lineArray[chars.charCodeAt(y)];
1584
+ diffs[x][1] = text.join("");
1585
+ }
1586
+ }
1587
+ function linesToChars(textA, textB) {
1588
+ const lineArray = [], lineHash = {};
1589
+ lineArray[0] = "";
1590
+ function diffLinesToMunge(text) {
1591
+ let chars = "", lineStart = 0, lineEnd = -1, lineArrayLength = lineArray.length;
1592
+ for (; lineEnd < text.length - 1; ) {
1593
+ lineEnd = text.indexOf(`
1594
+ `, lineStart), lineEnd === -1 && (lineEnd = text.length - 1);
1595
+ let line = text.slice(lineStart, lineEnd + 1);
1596
+ (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;
1597
+ }
1598
+ return chars;
1599
+ }
1600
+ let maxLines = 4e4;
1601
+ const chars1 = diffLinesToMunge(textA);
1602
+ maxLines = 65535;
1603
+ const chars2 = diffLinesToMunge(textB);
1604
+ return {
1605
+ chars1,
1606
+ chars2,
1607
+ lineArray
2109
1608
  };
2110
1609
  }
2111
- function createWithInsertBreak(types) {
2112
- return function(editor) {
2113
- const { insertBreak } = editor;
2114
- return editor.insertBreak = () => {
2115
- if (editor.selection) {
2116
- const focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = Node.descendant(editor, focusBlockPath);
2117
- if (editor.isTextBlock(focusBlock)) {
2118
- const [, end] = Range.edges(editor.selection), isEndAtStartOfNode = Editor.isStart(editor, end, end.path), isEmptyTextBlock = focusBlock && isEqualToEmptyEditor([focusBlock], types);
2119
- if (isEndAtStartOfNode && !isEmptyTextBlock) {
2120
- Editor.insertNode(editor, editor.pteCreateEmptyBlock());
2121
- const [nextBlockPath] = Path.next(focusBlockPath);
2122
- Transforms.select(editor, {
2123
- anchor: { path: [nextBlockPath, 0], offset: 0 },
2124
- focus: { path: [nextBlockPath, 0], offset: 0 }
2125
- }), editor.onChange();
2126
- return;
2127
- }
1610
+ function doLineModeDiff(textA, textB, opts) {
1611
+ let text1 = textA, text2 = textB;
1612
+ const a = linesToChars(text1, text2);
1613
+ text1 = a.chars1, text2 = a.chars2;
1614
+ const linearray = a.lineArray;
1615
+ let diffs = doDiff(text1, text2, {
1616
+ checkLines: !1,
1617
+ deadline: opts.deadline
1618
+ });
1619
+ charsToLines(diffs, linearray), diffs = cleanupSemantic(diffs), diffs.push([DIFF_EQUAL, ""]);
1620
+ let pointer = 0, countDelete = 0, countInsert = 0, textDelete = "", textInsert = "";
1621
+ for (; pointer < diffs.length; ) {
1622
+ switch (diffs[pointer][0]) {
1623
+ case DIFF_INSERT:
1624
+ countInsert++, textInsert += diffs[pointer][1];
1625
+ break;
1626
+ case DIFF_DELETE:
1627
+ countDelete++, textDelete += diffs[pointer][1];
1628
+ break;
1629
+ case DIFF_EQUAL:
1630
+ if (countDelete >= 1 && countInsert >= 1) {
1631
+ diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert), pointer = pointer - countDelete - countInsert;
1632
+ const aa = doDiff(textDelete, textInsert, {
1633
+ checkLines: !1,
1634
+ deadline: opts.deadline
1635
+ });
1636
+ for (let j = aa.length - 1; j >= 0; j--)
1637
+ diffs.splice(pointer, 0, aa[j]);
1638
+ pointer += aa.length;
2128
1639
  }
2129
- }
2130
- insertBreak();
2131
- }, editor;
2132
- };
1640
+ countInsert = 0, countDelete = 0, textDelete = "", textInsert = "";
1641
+ break;
1642
+ default:
1643
+ throw new Error("Unknown diff operation.");
1644
+ }
1645
+ pointer++;
1646
+ }
1647
+ return diffs.pop(), diffs;
2133
1648
  }
2134
- function createWithMaxBlocks(maxBlocks) {
2135
- return function(editor) {
2136
- const { apply: apply2 } = editor;
2137
- return editor.apply = (operation) => {
2138
- const rows = maxBlocks;
2139
- rows > 0 && editor.children.length >= rows && (operation.type === "insert_node" || operation.type === "split_node") && operation.path.length === 1 || apply2(operation);
2140
- }, editor;
1649
+ function computeDiff(text1, text2, opts) {
1650
+ let diffs;
1651
+ if (!text1)
1652
+ return [[DIFF_INSERT, text2]];
1653
+ if (!text2)
1654
+ return [[DIFF_DELETE, text1]];
1655
+ const longtext = text1.length > text2.length ? text1 : text2, shorttext = text1.length > text2.length ? text2 : text1, i = longtext.indexOf(shorttext);
1656
+ if (i !== -1)
1657
+ 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;
1658
+ if (shorttext.length === 1)
1659
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
1660
+ const halfMatch = findHalfMatch(text1, text2);
1661
+ if (halfMatch) {
1662
+ 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);
1663
+ return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);
1664
+ }
1665
+ return opts.checkLines && text1.length > 100 && text2.length > 100 ? doLineModeDiff(text1, text2, opts) : bisect(text1, text2, opts.deadline);
1666
+ }
1667
+ const DIFF_DELETE = -1, DIFF_INSERT = 1, DIFF_EQUAL = 0;
1668
+ function diff(textA, textB, opts) {
1669
+ if (textA === null || textB === null)
1670
+ throw new Error("Null input. (diff)");
1671
+ const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));
1672
+ return adjustDiffForSurrogatePairs(diffs), diffs;
1673
+ }
1674
+ function doDiff(textA, textB, options) {
1675
+ let text1 = textA, text2 = textB;
1676
+ if (text1 === text2)
1677
+ return text1 ? [[DIFF_EQUAL, text1]] : [];
1678
+ let commonlength = getCommonPrefix(text1, text2);
1679
+ const commonprefix = text1.substring(0, commonlength);
1680
+ text1 = text1.substring(commonlength), text2 = text2.substring(commonlength), commonlength = getCommonSuffix(text1, text2);
1681
+ const commonsuffix = text1.substring(text1.length - commonlength);
1682
+ text1 = text1.substring(0, text1.length - commonlength), text2 = text2.substring(0, text2.length - commonlength);
1683
+ let diffs = computeDiff(text1, text2, options);
1684
+ return commonprefix && diffs.unshift([DIFF_EQUAL, commonprefix]), commonsuffix && diffs.push([DIFF_EQUAL, commonsuffix]), diffs = cleanupMerge(diffs), diffs;
1685
+ }
1686
+ function createDeadLine(timeout) {
1687
+ let t = 1;
1688
+ return typeof timeout < "u" && (t = timeout <= 0 ? Number.MAX_VALUE : timeout), Date.now() + t * 1e3;
1689
+ }
1690
+ function createInternalOpts(opts) {
1691
+ return {
1692
+ checkLines: !0,
1693
+ deadline: createDeadLine(opts.timeout || 1),
1694
+ ...opts
2141
1695
  };
2142
1696
  }
2143
- const PRESERVE_KEYS = /* @__PURE__ */ new WeakMap();
2144
- function withPreserveKeys(editor, fn) {
2145
- const prev = isPreservingKeys(editor);
2146
- PRESERVE_KEYS.set(editor, !0), fn(), PRESERVE_KEYS.set(editor, prev);
1697
+ function combineChar(data, char, dir) {
1698
+ return dir === 1 ? data + char : char + data;
2147
1699
  }
2148
- function isPreservingKeys(editor) {
2149
- return PRESERVE_KEYS.get(editor);
1700
+ function splitChar(data, dir) {
1701
+ return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];
2150
1702
  }
2151
- function createWithObjectKeys(schemaTypes, keyGenerator) {
2152
- return function(editor) {
2153
- PRESERVE_KEYS.set(editor, !1);
2154
- const { apply: apply2, normalizeNode } = editor;
2155
- return editor.apply = (operation) => {
2156
- if (operation.type === "split_node") {
2157
- const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.properties);
2158
- operation.properties = {
2159
- ...operation.properties,
2160
- ...withNewKey ? { _key: keyGenerator() } : {}
2161
- };
2162
- }
2163
- if (operation.type === "insert_node") {
2164
- const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.node);
2165
- Editor.isEditor(operation.node) || (operation.node = {
2166
- ...operation.node,
2167
- ...withNewKey ? { _key: keyGenerator() } : {}
2168
- });
2169
- }
2170
- apply2(operation);
2171
- }, editor.normalizeNode = (entry) => {
2172
- const [node, path] = entry;
2173
- if (Element$1.isElement(node) && node._type === schemaTypes.block.name) {
2174
- node._key || Transforms.setNodes(editor, { _key: keyGenerator() }, { at: path });
2175
- for (const [child, childPath] of Node.children(editor, path))
2176
- if (!child._key) {
2177
- Transforms.setNodes(editor, { _key: keyGenerator() }, { at: childPath });
2178
- return;
2179
- }
1703
+ function hasSharedChar(diffs, i, j, dir) {
1704
+ 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];
1705
+ }
1706
+ function deisolateChar(diffs, i, dir) {
1707
+ const inv = dir === 1 ? -1 : 1;
1708
+ let insertIdx = null, deleteIdx = null, j = i + dir;
1709
+ for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {
1710
+ const [op, text2] = diffs[j];
1711
+ if (text2.length !== 0) {
1712
+ if (op === DIFF_INSERT) {
1713
+ insertIdx === null && (insertIdx = j);
1714
+ continue;
1715
+ } else if (op === DIFF_DELETE) {
1716
+ deleteIdx === null && (deleteIdx = j);
1717
+ continue;
1718
+ } else if (op === DIFF_EQUAL) {
1719
+ if (insertIdx === null && deleteIdx === null) {
1720
+ const [rest, char2] = splitChar(diffs[i][1], dir);
1721
+ diffs[i][1] = rest, diffs[j][1] = combineChar(diffs[j][1], char2, inv);
1722
+ return;
1723
+ }
1724
+ break;
2180
1725
  }
2181
- normalizeNode(entry);
2182
- }, editor;
1726
+ }
1727
+ }
1728
+ if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {
1729
+ const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv), [deleteText] = splitChar(diffs[deleteIdx][1], inv);
1730
+ diffs[insertIdx][1] = insertText, diffs[deleteIdx][1] = deleteText, diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);
1731
+ return;
1732
+ }
1733
+ const [text, char] = splitChar(diffs[i][1], dir);
1734
+ 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);
1735
+ }
1736
+ function adjustDiffForSurrogatePairs(diffs) {
1737
+ for (let i = 0; i < diffs.length; i++) {
1738
+ const [diffType, diffText] = diffs[i];
1739
+ if (diffText.length === 0) continue;
1740
+ const firstChar = diffText[0], lastChar = diffText[diffText.length - 1];
1741
+ isHighSurrogate(lastChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, 1), isLowSurrogate(firstChar) && diffType === DIFF_EQUAL && deisolateChar(diffs, i, -1);
1742
+ }
1743
+ for (let i = 0; i < diffs.length; i++)
1744
+ diffs[i][1].length === 0 && diffs.splice(i, 1);
1745
+ }
1746
+ const DEFAULT_OPTIONS = {
1747
+ /**
1748
+ * At what point is no match declared (0.0 = perfection, 1.0 = very loose).
1749
+ */
1750
+ threshold: 0.5,
1751
+ /**
1752
+ * How far to search for a match (0 = exact location, 1000+ = broad match).
1753
+ * A match this many characters away from the expected location will add
1754
+ * 1.0 to the score (0.0 is a perfect match).
1755
+ */
1756
+ distance: 1e3
1757
+ };
1758
+ function applyDefaults(options) {
1759
+ return {
1760
+ ...DEFAULT_OPTIONS,
1761
+ ...options
2183
1762
  };
2184
1763
  }
2185
- const BEFORE = "before", AFTER = "after";
2186
- function insert(array, position, index, ...args) {
2187
- if (position !== BEFORE && position !== AFTER)
2188
- throw new Error(`Invalid position "${position}", must be either ${BEFORE} or ${AFTER}`);
2189
- const items = flatten(...args);
2190
- if (array.length === 0)
2191
- return items;
2192
- const len = array.length, idx = Math.abs((len + index) % len) % len, normalizedIdx = position === "after" ? idx + 1 : idx, copy = array.slice();
2193
- return copy.splice(normalizedIdx, 0, ...flatten(items)), copy;
1764
+ const MAX_BITS$1 = 32;
1765
+ function bitap(text, pattern, loc) {
1766
+ let opts = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
1767
+ if (pattern.length > MAX_BITS$1)
1768
+ throw new Error("Pattern too long for this browser.");
1769
+ const options = applyDefaults(opts), s = getAlphabetFromPattern(pattern);
1770
+ function getBitapScore(e, x) {
1771
+ const accuracy = e / pattern.length, proximity = Math.abs(loc - x);
1772
+ return options.distance ? accuracy + proximity / options.distance : proximity ? 1 : accuracy;
1773
+ }
1774
+ let scoreThreshold = options.threshold, bestLoc = text.indexOf(pattern, loc);
1775
+ 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)));
1776
+ const matchmask = 1 << pattern.length - 1;
1777
+ bestLoc = -1;
1778
+ let binMin, binMid, binMax = pattern.length + text.length, lastRd = [];
1779
+ for (let d = 0; d < pattern.length; d++) {
1780
+ for (binMin = 0, binMid = binMax; binMin < binMid; )
1781
+ getBitapScore(d, loc + binMid) <= scoreThreshold ? binMin = binMid : binMax = binMid, binMid = Math.floor((binMax - binMin) / 2 + binMin);
1782
+ binMax = binMid;
1783
+ let start = Math.max(1, loc - binMid + 1);
1784
+ const finish = Math.min(loc + binMid, text.length) + pattern.length, rd = new Array(finish + 2);
1785
+ rd[finish + 1] = (1 << d) - 1;
1786
+ for (let j = finish; j >= start; j--) {
1787
+ const charMatch = s[text.charAt(j - 1)];
1788
+ 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) {
1789
+ const score = getBitapScore(d, j - 1);
1790
+ if (score <= scoreThreshold)
1791
+ if (scoreThreshold = score, bestLoc = j - 1, bestLoc > loc)
1792
+ start = Math.max(1, 2 * loc - bestLoc);
1793
+ else
1794
+ break;
1795
+ }
1796
+ }
1797
+ if (getBitapScore(d + 1, loc) > scoreThreshold)
1798
+ break;
1799
+ lastRd = rd;
1800
+ }
1801
+ return bestLoc;
1802
+ }
1803
+ function getAlphabetFromPattern(pattern) {
1804
+ const s = {};
1805
+ for (let i = 0; i < pattern.length; i++)
1806
+ s[pattern.charAt(i)] = 0;
1807
+ for (let i = 0; i < pattern.length; i++)
1808
+ s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;
1809
+ return s;
1810
+ }
1811
+ function match(text, pattern, searchLocation) {
1812
+ if (text === null || pattern === null || searchLocation === null)
1813
+ throw new Error("Null input. (match())");
1814
+ const loc = Math.max(0, Math.min(searchLocation, text.length));
1815
+ if (text === pattern)
1816
+ return 0;
1817
+ if (text.length) {
1818
+ if (text.substring(loc, loc + pattern.length) === pattern)
1819
+ return loc;
1820
+ } else return -1;
1821
+ return bitap(text, pattern, loc);
2194
1822
  }
2195
- function flatten(...values) {
2196
- return values.reduce((prev, item) => prev.concat(item), []);
1823
+ function createPatchObject(start1, start2) {
1824
+ return {
1825
+ diffs: [],
1826
+ start1,
1827
+ start2,
1828
+ utf8Start1: start1,
1829
+ utf8Start2: start2,
1830
+ length1: 0,
1831
+ length2: 0,
1832
+ utf8Length1: 0,
1833
+ utf8Length2: 0
1834
+ };
2197
1835
  }
2198
- const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
2199
- function move(arr, from, to) {
2200
- const nextValue = arr.slice(), val = nextValue[from];
2201
- return nextValue.splice(from, 1), nextValue.splice(to, 0, val), nextValue;
1836
+ function diffText1(diffs) {
1837
+ const text = [];
1838
+ for (let x = 0; x < diffs.length; x++)
1839
+ diffs[x][0] !== DIFF_INSERT && (text[x] = diffs[x][1]);
1840
+ return text.join("");
2202
1841
  }
2203
- function findTargetIndex(array, pathSegment) {
2204
- if (typeof pathSegment == "number")
2205
- return pathSegment;
2206
- const index = findIndex(array, pathSegment);
2207
- return index === -1 ? !1 : index;
1842
+ function diffText2(diffs) {
1843
+ const text = [];
1844
+ for (let x = 0; x < diffs.length; x++)
1845
+ diffs[x][0] !== DIFF_DELETE && (text[x] = diffs[x][1]);
1846
+ return text.join("");
2208
1847
  }
2209
- function apply$3(value, patch) {
2210
- const nextValue = value.slice();
2211
- if (patch.path.length === 0) {
2212
- if (patch.type === "setIfMissing") {
2213
- if (!Array.isArray(patch.value))
2214
- throw new Error("Cannot set value of an array to a non-array");
2215
- return value === void 0 ? patch.value : value;
2216
- } else if (patch.type === "set") {
2217
- if (!Array.isArray(patch.value))
2218
- throw new Error("Cannot set value of an array to a non-array");
2219
- return patch.value;
2220
- } else {
2221
- if (patch.type === "unset")
2222
- return;
2223
- if (patch.type === "move") {
2224
- if (!patch.value || !hasOwn(patch.value, "from") || !hasOwn(patch.value, "to"))
2225
- throw new Error(
2226
- `Invalid value of 'move' patch. Expected a value with "from" and "to" indexes, instead got: ${JSON.stringify(
2227
- patch.value
2228
- )}`
2229
- );
2230
- return move(nextValue, patch.value.from, patch.value.to);
2231
- }
2232
- }
2233
- throw new Error(`Invalid array operation: ${patch.type}`);
1848
+ function countUtf8Bytes(str) {
1849
+ let bytes = 0;
1850
+ for (let i = 0; i < str.length; i++) {
1851
+ const codePoint = str.codePointAt(i);
1852
+ if (typeof codePoint > "u")
1853
+ throw new Error("Failed to get codepoint");
1854
+ bytes += utf8len(codePoint);
2234
1855
  }
2235
- const [head, ...tail] = patch.path, index = findTargetIndex(value, head);
2236
- if (index === !1)
2237
- return nextValue;
2238
- if (tail.length === 0) {
2239
- if (patch.type === "insert") {
2240
- const { position, items } = patch;
2241
- return insert(value, position, index, items);
2242
- } else if (patch.type === "unset") {
2243
- if (typeof index != "number")
2244
- throw new Error(`Expected array index to be a number, instead got "${index}"`);
2245
- return nextValue.splice(index, 1), nextValue;
1856
+ return bytes;
1857
+ }
1858
+ function adjustIndiciesToUcs2(patches, base) {
1859
+ let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}, byteOffset = 0, idx = 0;
1860
+ function advanceTo(target) {
1861
+ for (; byteOffset < target; ) {
1862
+ const codePoint = base.codePointAt(idx);
1863
+ if (typeof codePoint > "u")
1864
+ return idx;
1865
+ byteOffset += utf8len(codePoint), codePoint > 65535 ? idx += 2 : idx += 1;
2246
1866
  }
1867
+ if (!options.allowExceedingIndices && byteOffset !== target)
1868
+ throw new Error("Failed to determine byte offset");
1869
+ return idx;
2247
1870
  }
2248
- return nextValue[index] = _apply(nextValue[index], {
2249
- ...patch,
2250
- path: tail
2251
- }), nextValue;
1871
+ const adjusted = [];
1872
+ for (const patch of patches)
1873
+ adjusted.push({
1874
+ diffs: patch.diffs.map((diff2) => cloneDiff(diff2)),
1875
+ start1: advanceTo(patch.start1),
1876
+ start2: advanceTo(patch.start2),
1877
+ utf8Start1: patch.utf8Start1,
1878
+ utf8Start2: patch.utf8Start2,
1879
+ length1: patch.length1,
1880
+ length2: patch.length2,
1881
+ utf8Length1: patch.utf8Length1,
1882
+ utf8Length2: patch.utf8Length2
1883
+ });
1884
+ return adjusted;
2252
1885
  }
2253
- function apply$2(value, patch) {
2254
- const nextValue = clone(value);
2255
- if (patch.path.length === 0) {
2256
- if (patch.type === "set") {
2257
- if (!isObject(patch.value))
2258
- throw new Error("Cannot set value of an object to a non-object");
2259
- return patch.value;
2260
- } else {
2261
- if (patch.type === "unset")
2262
- return;
2263
- if (patch.type === "setIfMissing")
2264
- return value === void 0 ? patch.value : value;
1886
+ function utf8len(codePoint) {
1887
+ return codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
1888
+ }
1889
+ const MAX_BITS = 32, DEFAULT_MARGIN = 4;
1890
+ function levenshtein(diffs) {
1891
+ let leven = 0, insertions = 0, deletions = 0;
1892
+ for (let x = 0; x < diffs.length; x++) {
1893
+ const op = diffs[x][0], data = diffs[x][1];
1894
+ switch (op) {
1895
+ case DIFF_INSERT:
1896
+ insertions += data.length;
1897
+ break;
1898
+ case DIFF_DELETE:
1899
+ deletions += data.length;
1900
+ break;
1901
+ case DIFF_EQUAL:
1902
+ leven += Math.max(insertions, deletions), insertions = 0, deletions = 0;
1903
+ break;
1904
+ default:
1905
+ throw new Error("Unknown diff operation.");
2265
1906
  }
2266
- throw new Error(`Invalid object operation: ${patch.type}`);
2267
1907
  }
2268
- const [head, ...tail] = patch.path;
2269
- if (typeof head != "string")
2270
- throw new Error(`Expected field name to be a string, instad got: ${head}`);
2271
- return tail.length === 0 && patch.type === "unset" ? omit(nextValue, head) : (nextValue[head] = _apply(nextValue[head], {
2272
- ...patch,
2273
- path: tail
2274
- }), nextValue);
1908
+ return leven += Math.max(insertions, deletions), leven;
2275
1909
  }
2276
- const OPERATIONS$1 = {
2277
- replace(_currentValue, nextValue) {
2278
- return nextValue;
2279
- },
2280
- set(_currentValue, nextValue) {
2281
- return nextValue;
2282
- },
2283
- setIfMissing(currentValue, nextValue) {
2284
- return currentValue === void 0 ? nextValue : currentValue;
2285
- },
2286
- unset(_currentValue, _nextValue) {
2287
- },
2288
- inc(currentValue, nextValue) {
2289
- return currentValue + nextValue;
2290
- },
2291
- dec(currentValue, nextValue) {
2292
- return currentValue - nextValue;
1910
+ function xIndex(diffs, loc) {
1911
+ let chars1 = 0, chars2 = 0, lastChars1 = 0, lastChars2 = 0, x;
1912
+ 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++)
1913
+ lastChars1 = chars1, lastChars2 = chars2;
1914
+ return diffs.length !== x && diffs[x][0] === DIFF_DELETE ? lastChars2 : lastChars2 + (loc - lastChars1);
1915
+ }
1916
+ function addPadding(patches) {
1917
+ const paddingLength = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1918
+ let nullPadding = "";
1919
+ for (let x = 1; x <= paddingLength; x++)
1920
+ nullPadding += String.fromCharCode(x);
1921
+ for (const p of patches)
1922
+ p.start1 += paddingLength, p.start2 += paddingLength, p.utf8Start1 += paddingLength, p.utf8Start2 += paddingLength;
1923
+ let patch = patches[0], diffs = patch.diffs;
1924
+ if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL)
1925
+ 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;
1926
+ else if (paddingLength > diffs[0][1].length) {
1927
+ const firstDiffLength = diffs[0][1].length, extraLength = paddingLength - firstDiffLength;
1928
+ 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;
2293
1929
  }
2294
- }, SUPPORTED_PATCH_TYPES$1 = Object.keys(OPERATIONS$1);
2295
- function apply$1(value, patch) {
2296
- if (!SUPPORTED_PATCH_TYPES$1.includes(patch.type))
2297
- throw new Error(
2298
- `Received patch of unsupported type: "${JSON.stringify(
2299
- patch.type
2300
- )}" for primitives. This is most likely a bug.`
2301
- );
2302
- if (patch.path.length > 0)
2303
- throw new Error(
2304
- `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)}"`
2305
- );
2306
- return OPERATIONS$1[patch.type](value, patch.value);
1930
+ if (patch = patches[patches.length - 1], diffs = patch.diffs, diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL)
1931
+ diffs.push([DIFF_EQUAL, nullPadding]), patch.length1 += paddingLength, patch.length2 += paddingLength, patch.utf8Length1 += paddingLength, patch.utf8Length2 += paddingLength;
1932
+ else if (paddingLength > diffs[diffs.length - 1][1].length) {
1933
+ const extraLength = paddingLength - diffs[diffs.length - 1][1].length;
1934
+ diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength), patch.length1 += extraLength, patch.length2 += extraLength, patch.utf8Length1 += extraLength, patch.utf8Length2 += extraLength;
1935
+ }
1936
+ return nullPadding;
2307
1937
  }
2308
- const OPERATIONS = {
2309
- replace(_currentValue, nextValue) {
2310
- return nextValue;
2311
- },
2312
- set(_currentValue, nextValue) {
2313
- return nextValue;
2314
- },
2315
- setIfMissing(currentValue, nextValue) {
2316
- return currentValue === void 0 ? nextValue : currentValue;
2317
- },
2318
- unset(_currentValue, _nextValue) {
2319
- },
2320
- diffMatchPatch(currentValue, nextValue) {
2321
- const [result] = apply$4(parse(nextValue), currentValue, {
2322
- allowExceedingIndices: !0
2323
- });
2324
- return result;
1938
+ function splitMax(patches) {
1939
+ let margin = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_MARGIN;
1940
+ const patchSize = MAX_BITS;
1941
+ for (let x = 0; x < patches.length; x++) {
1942
+ if (patches[x].length1 <= patchSize)
1943
+ continue;
1944
+ const bigpatch = patches[x];
1945
+ patches.splice(x--, 1);
1946
+ let start1 = bigpatch.start1, start2 = bigpatch.start2, preContext = "";
1947
+ for (; bigpatch.diffs.length !== 0; ) {
1948
+ const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);
1949
+ let empty = !0;
1950
+ if (preContext !== "") {
1951
+ const precontextByteCount = countUtf8Bytes(preContext);
1952
+ patch.length1 = preContext.length, patch.utf8Length1 = precontextByteCount, patch.length2 = preContext.length, patch.utf8Length2 = precontextByteCount, patch.diffs.push([DIFF_EQUAL, preContext]);
1953
+ }
1954
+ for (; bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin; ) {
1955
+ const diffType = bigpatch.diffs[0][0];
1956
+ let diffText = bigpatch.diffs[0][1], diffTextByteCount = countUtf8Bytes(diffText);
1957
+ if (diffType === DIFF_INSERT) {
1958
+ patch.length2 += diffText.length, patch.utf8Length2 += diffTextByteCount, start2 += diffText.length;
1959
+ const diff2 = bigpatch.diffs.shift();
1960
+ diff2 && patch.diffs.push(diff2), empty = !1;
1961
+ } 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));
1962
+ }
1963
+ preContext = diffText2(patch.diffs), preContext = preContext.substring(preContext.length - margin);
1964
+ const postContext = diffText1(bigpatch.diffs).substring(0, margin), postContextByteCount = countUtf8Bytes(postContext);
1965
+ 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);
1966
+ }
2325
1967
  }
2326
- }, SUPPORTED_PATCH_TYPES = Object.keys(OPERATIONS);
2327
- function apply(value, patch) {
2328
- if (!SUPPORTED_PATCH_TYPES.includes(patch.type))
2329
- throw new Error(
2330
- `Received patch of unsupported type: "${JSON.stringify(
2331
- patch.type
2332
- )}" for string. This is most likely a bug.`
2333
- );
2334
- if (patch.path.length > 0)
2335
- throw new Error(
2336
- `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)}"`
2337
- );
2338
- const func = OPERATIONS[patch.type];
2339
- if (func)
2340
- return func(value, patch.value);
2341
- throw new Error("Unknown patch type");
2342
1968
  }
2343
- function applyAll(value, patches) {
2344
- return patches.reduce(_apply, value);
1969
+ function apply(patches, originalText) {
1970
+ let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1971
+ if (typeof patches == "string")
1972
+ throw new Error("Patches must be an array - pass the patch to `parsePatch()` first");
1973
+ let text = originalText;
1974
+ if (patches.length === 0)
1975
+ return [text, []];
1976
+ const parsed = adjustIndiciesToUcs2(patches, text, {
1977
+ allowExceedingIndices: opts.allowExceedingIndices
1978
+ }), margin = opts.margin || DEFAULT_MARGIN, deleteThreshold = opts.deleteThreshold || 0.4, nullPadding = addPadding(parsed, margin);
1979
+ text = nullPadding + text + nullPadding, splitMax(parsed, margin);
1980
+ let delta = 0;
1981
+ const results = [];
1982
+ for (let x = 0; x < parsed.length; x++) {
1983
+ const expectedLoc = parsed[x].start2 + delta, text1 = diffText1(parsed[x].diffs);
1984
+ let startLoc, endLoc = -1;
1985
+ 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)
1986
+ results[x] = !1, delta -= parsed[x].length2 - parsed[x].length1;
1987
+ else {
1988
+ results[x] = !0, delta = startLoc - expectedLoc;
1989
+ let text2;
1990
+ if (endLoc === -1 ? text2 = text.substring(startLoc, startLoc + text1.length) : text2 = text.substring(startLoc, endLoc + MAX_BITS), text1 === text2)
1991
+ text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);
1992
+ else {
1993
+ let diffs = diff(text1, text2, {
1994
+ checkLines: !1
1995
+ });
1996
+ if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold)
1997
+ results[x] = !1;
1998
+ else {
1999
+ diffs = cleanupSemanticLossless(diffs);
2000
+ let index1 = 0, index2 = 0;
2001
+ for (let y = 0; y < parsed[x].diffs.length; y++) {
2002
+ const mod = parsed[x].diffs[y];
2003
+ 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);
2004
+ }
2005
+ }
2006
+ }
2007
+ }
2008
+ }
2009
+ return text = text.substring(nullPadding.length, text.length - nullPadding.length), [text, results];
2345
2010
  }
2346
- function applyPatch(value, patch) {
2347
- return Array.isArray(value) ? apply$3(value, patch) : isString(value) ? apply(value, patch) : isObject(value) ? apply$2(value, patch) : apply$1(value, patch);
2011
+ const patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
2012
+ function parse(textline) {
2013
+ if (!textline)
2014
+ return [];
2015
+ const patches = [], lines = textline.split(`
2016
+ `);
2017
+ let textPointer = 0;
2018
+ for (; textPointer < lines.length; ) {
2019
+ const m = lines[textPointer].match(patchHeader);
2020
+ if (!m)
2021
+ throw new Error("Invalid patch string: ".concat(lines[textPointer]));
2022
+ const patch = createPatchObject(toInt(m[1]), toInt(m[3]));
2023
+ 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; ) {
2024
+ const currentLine = lines[textPointer], sign = currentLine.charAt(0);
2025
+ if (sign === "@")
2026
+ break;
2027
+ if (sign === "") {
2028
+ textPointer++;
2029
+ continue;
2030
+ }
2031
+ let line;
2032
+ try {
2033
+ line = decodeURI(currentLine.slice(1));
2034
+ } catch {
2035
+ throw new Error("Illegal escape in parse: ".concat(currentLine));
2036
+ }
2037
+ const utf8Diff = countUtf8Bytes(line) - line.length;
2038
+ if (sign === "-")
2039
+ patch.diffs.push([DIFF_DELETE, line]), patch.length1 -= utf8Diff;
2040
+ else if (sign === "+")
2041
+ patch.diffs.push([DIFF_INSERT, line]), patch.length2 -= utf8Diff;
2042
+ else if (sign === " ")
2043
+ patch.diffs.push([DIFF_EQUAL, line]), patch.length1 -= utf8Diff, patch.length2 -= utf8Diff;
2044
+ else
2045
+ throw new Error('Invalid patch mode "'.concat(sign, '" in: ').concat(line));
2046
+ textPointer++;
2047
+ }
2048
+ }
2049
+ return patches;
2348
2050
  }
2349
- function _apply(value, patch) {
2350
- return applyPatch(value, patch);
2051
+ function toInt(num) {
2052
+ return parseInt(num, 10);
2351
2053
  }
2352
2054
  const debug$h = debugWithName("applyPatches"), debugVerbose$3 = debug$h.enabled && !0;
2353
2055
  function createApplyPatch(schemaTypes) {
@@ -2388,7 +2090,7 @@ function diffMatchPatch(editor, patch) {
2388
2090
  return debug$h("Child not found"), !1;
2389
2091
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !Text.isText(child))
2390
2092
  return !1;
2391
- const patches = parse(patch.value), [newValue] = apply$4(patches, child.text, { allowExceedingIndices: !0 }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
2093
+ const patches = parse(patch.value), [newValue] = apply(patches, child.text, { allowExceedingIndices: !0 }), diff$1 = cleanupEfficiency(diff(child.text, newValue), 5);
2392
2094
  debugState(editor, "before");
2393
2095
  let offset = 0;
2394
2096
  for (const [op, text] of diff$1)
@@ -2608,7 +2310,7 @@ function createWithUndoRedo(options) {
2608
2310
  const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
2609
2311
  let transformedOperations = step.operations;
2610
2312
  otherPatches.forEach((item) => {
2611
- transformedOperations = flatten$1(
2313
+ transformedOperations = flatten(
2612
2314
  transformedOperations.map(
2613
2315
  (op) => transformOperation(editor, item.patch, op, item.snapshot, item.previousSnapshot)
2614
2316
  )
@@ -2641,7 +2343,7 @@ function createWithUndoRedo(options) {
2641
2343
  const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
2642
2344
  let transformedOperations = step.operations;
2643
2345
  otherPatches.forEach((item) => {
2644
- transformedOperations = flatten$1(
2346
+ transformedOperations = flatten(
2645
2347
  transformedOperations.map(
2646
2348
  (op) => transformOperation(editor, item.patch, op, item.snapshot, item.previousSnapshot)
2647
2349
  )
@@ -2759,7 +2461,7 @@ function createWithPatches({
2759
2461
  schemaTypes
2760
2462
  }) {
2761
2463
  let previousChildren;
2762
- const applyPatch2 = createApplyPatch(schemaTypes);
2464
+ const applyPatch = createApplyPatch(schemaTypes);
2763
2465
  return function(editor) {
2764
2466
  IS_PROCESSING_REMOTE_CHANGES.set(editor, !1), PATCHING.set(editor, !0), previousChildren = [...editor.children];
2765
2467
  const { apply: apply2 } = editor;
@@ -2776,7 +2478,7 @@ function createWithPatches({
2776
2478
  withoutSaving(editor, () => {
2777
2479
  withPreserveKeys(editor, () => {
2778
2480
  patches.forEach((patch) => {
2779
- debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch2(editor, patch);
2481
+ debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
2780
2482
  });
2781
2483
  });
2782
2484
  });
@@ -2803,7 +2505,7 @@ function createWithPatches({
2803
2505
  const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes);
2804
2506
  if (!isPatching(editor))
2805
2507
  return editor;
2806
- switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches.push(insert$1(previousChildren, "before", [0])), operation.type) {
2508
+ switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches.push(insert(previousChildren, "before", [0])), operation.type) {
2807
2509
  case "insert_text":
2808
2510
  patches = [
2809
2511
  ...patches,
@@ -3575,7 +3277,7 @@ function validateValue(value, types, keyGenerator) {
3575
3277
  autoResolve: !0,
3576
3278
  patches: [
3577
3279
  setIfMissing([], [{ _key: blk._key }, "children"]),
3578
- insert$1([newSpan], "after", [{ _key: blk._key }, "children", 0])
3280
+ insert([newSpan], "after", [{ _key: blk._key }, "children", 0])
3579
3281
  ],
3580
3282
  description: `Children for text block with _key '${blk._key}' is empty.`,
3581
3283
  action: "Insert an empty text",
@@ -3600,7 +3302,7 @@ function validateValue(value, types, keyGenerator) {
3600
3302
  }
3601
3303
  }, !0;
3602
3304
  const allUsedMarks = uniq(
3603
- flatten$1(
3305
+ flatten(
3604
3306
  textBlock.children.filter((cld) => cld._type === types.span.name).map((cld) => cld.marks || [])
3605
3307
  )
3606
3308
  );