slate-react 0.115.0 → 0.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/chunking/children-helper.d.ts +61 -0
  2. package/dist/chunking/children-helper.d.ts.map +1 -0
  3. package/dist/chunking/chunk-tree-helper.d.ts +160 -0
  4. package/dist/chunking/chunk-tree-helper.d.ts.map +1 -0
  5. package/dist/chunking/get-chunk-tree-for-node.d.ts +16 -0
  6. package/dist/chunking/get-chunk-tree-for-node.d.ts.map +1 -0
  7. package/dist/chunking/index.d.ts +3 -0
  8. package/dist/chunking/index.d.ts.map +1 -0
  9. package/dist/chunking/reconcile-children.d.ts +19 -0
  10. package/dist/chunking/reconcile-children.d.ts.map +1 -0
  11. package/dist/chunking/types.d.ts +44 -0
  12. package/dist/chunking/types.d.ts.map +1 -0
  13. package/dist/components/chunk-tree.d.ts +13 -0
  14. package/dist/components/chunk-tree.d.ts.map +1 -0
  15. package/dist/components/editable.d.ts +13 -0
  16. package/dist/components/editable.d.ts.map +1 -1
  17. package/dist/components/element.d.ts +4 -4
  18. package/dist/components/element.d.ts.map +1 -1
  19. package/dist/components/leaf.d.ts.map +1 -1
  20. package/dist/components/slate.d.ts.map +1 -1
  21. package/dist/components/text.d.ts +1 -1
  22. package/dist/components/text.d.ts.map +1 -1
  23. package/dist/hooks/use-children.d.ts +4 -4
  24. package/dist/hooks/use-children.d.ts.map +1 -1
  25. package/dist/hooks/use-decorations.d.ts +18 -0
  26. package/dist/hooks/use-decorations.d.ts.map +1 -0
  27. package/dist/hooks/use-element.d.ts +12 -0
  28. package/dist/hooks/use-element.d.ts.map +1 -0
  29. package/dist/hooks/use-generic-selector.d.ts +20 -0
  30. package/dist/hooks/use-generic-selector.d.ts.map +1 -0
  31. package/dist/hooks/use-selected.d.ts +0 -5
  32. package/dist/hooks/use-selected.d.ts.map +1 -1
  33. package/dist/hooks/use-slate-selector.d.ts +30 -15
  34. package/dist/hooks/use-slate-selector.d.ts.map +1 -1
  35. package/dist/hooks/use-slate.d.ts +7 -14
  36. package/dist/hooks/use-slate.d.ts.map +1 -1
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.es.js +1154 -232
  40. package/dist/index.es.js.map +1 -1
  41. package/dist/index.js +1328 -343
  42. package/dist/index.js.map +1 -1
  43. package/dist/plugin/react-editor.d.ts +7 -0
  44. package/dist/plugin/react-editor.d.ts.map +1 -1
  45. package/dist/plugin/with-react.d.ts.map +1 -1
  46. package/dist/slate-react.js +1385 -346
  47. package/dist/slate-react.min.js +1 -1
  48. package/package.json +5 -4
  49. package/dist/hooks/use-decorate.d.ts +0 -11
  50. package/dist/hooks/use-decorate.d.ts.map +0 -1
@@ -2486,8 +2486,8 @@
2486
2486
  return slate.Editor.range(editor, positions[left], parentRangeBoundary);
2487
2487
  };
2488
2488
 
2489
- function ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2490
- function _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2489
+ function ownKeys$1$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2490
+ function _objectSpread$1$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2491
2491
  /**
2492
2492
  * `withDOM` adds DOM specific behaviors to the editor.
2493
2493
  *
@@ -2568,7 +2568,7 @@
2568
2568
  var pendingAction = EDITOR_TO_PENDING_ACTION.get(e);
2569
2569
  if (pendingAction !== null && pendingAction !== void 0 && pendingAction.at) {
2570
2570
  var at = slate.Point.isPoint(pendingAction === null || pendingAction === void 0 ? void 0 : pendingAction.at) ? transformPendingPoint(e, pendingAction.at, op) : transformPendingRange(e, pendingAction.at, op);
2571
- EDITOR_TO_PENDING_ACTION.set(e, at ? _objectSpread$7(_objectSpread$7({}, pendingAction), {}, {
2571
+ EDITOR_TO_PENDING_ACTION.set(e, at ? _objectSpread$1$1(_objectSpread$1$1({}, pendingAction), {}, {
2572
2572
  at
2573
2573
  }) : null);
2574
2574
  }
@@ -2902,6 +2902,8 @@
2902
2902
 
2903
2903
  var _excluded$3 = ["anchor", "focus"],
2904
2904
  _excluded2$1 = ["anchor", "focus"];
2905
+ function ownKeys$8(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2906
+ function _objectSpread$8(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$8(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2905
2907
  var shallowCompare = (obj1, obj2) => Object.keys(obj1).length === Object.keys(obj2).length && Object.keys(obj1).every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key]);
2906
2908
  var isDecorationFlagsEqual = (range, other) => {
2907
2909
  var rangeOwnProps = _objectWithoutProperties(range, _excluded$3);
@@ -2916,6 +2918,12 @@
2916
2918
  * kept in order, and the odd case where they aren't is okay to re-render for.
2917
2919
  */
2918
2920
  var isElementDecorationsEqual = (list, another) => {
2921
+ if (list === another) {
2922
+ return true;
2923
+ }
2924
+ if (!list || !another) {
2925
+ return false;
2926
+ }
2919
2927
  if (list.length !== another.length) {
2920
2928
  return false;
2921
2929
  }
@@ -2936,6 +2944,12 @@
2936
2944
  * kept in order, and the odd case where they aren't is okay to re-render for.
2937
2945
  */
2938
2946
  var isTextDecorationsEqual = (list, another) => {
2947
+ if (list === another) {
2948
+ return true;
2949
+ }
2950
+ if (!list || !another) {
2951
+ return false;
2952
+ }
2939
2953
  if (list.length !== another.length) {
2940
2954
  return false;
2941
2955
  }
@@ -2949,12 +2963,52 @@
2949
2963
  }
2950
2964
  return true;
2951
2965
  };
2966
+ /**
2967
+ * Split and group decorations by each child of a node.
2968
+ *
2969
+ * @returns An array with length equal to that of `node.children`. Each index
2970
+ * corresponds to a child of `node`, and the value is an array of decorations
2971
+ * for that child.
2972
+ */
2973
+ var splitDecorationsByChild = (editor, node, decorations) => {
2974
+ var decorationsByChild = Array.from(node.children, () => []);
2975
+ if (decorations.length === 0) {
2976
+ return decorationsByChild;
2977
+ }
2978
+ var path = DOMEditor.findPath(editor, node);
2979
+ var level = path.length;
2980
+ var ancestorRange = slate.Editor.range(editor, path);
2981
+ var cachedChildRanges = new Array(node.children.length);
2982
+ var getChildRange = index => {
2983
+ var cachedRange = cachedChildRanges[index];
2984
+ if (cachedRange) return cachedRange;
2985
+ var childRange = slate.Editor.range(editor, [...path, index]);
2986
+ cachedChildRanges[index] = childRange;
2987
+ return childRange;
2988
+ };
2989
+ for (var decoration of decorations) {
2990
+ var decorationRange = slate.Range.intersection(ancestorRange, decoration);
2991
+ if (!decorationRange) continue;
2992
+ var [startPoint, endPoint] = slate.Range.edges(decorationRange);
2993
+ var startIndex = startPoint.path[level];
2994
+ var endIndex = endPoint.path[level];
2995
+ for (var i = startIndex; i <= endIndex; i++) {
2996
+ var ds = decorationsByChild[i];
2997
+ if (!ds) continue;
2998
+ var childRange = getChildRange(i);
2999
+ var childDecorationRange = slate.Range.intersection(childRange, decoration);
3000
+ if (!childDecorationRange) continue;
3001
+ ds.push(_objectSpread$8(_objectSpread$8({}, decoration), childDecorationRange));
3002
+ }
3003
+ }
3004
+ return decorationsByChild;
3005
+ };
2952
3006
 
2953
3007
  // eslint-disable-next-line no-redeclare
2954
3008
  var ReactEditor = DOMEditor;
2955
3009
 
2956
- function ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2957
- function _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3010
+ function ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3011
+ function _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2958
3012
  // https://github.com/facebook/draft-js/blob/main/src/component/handlers/composition/DraftEditorCompositionHandler.js#L41
2959
3013
  // When using keyboard English association function, conpositionEnd triggered too fast, resulting in after `insertText` still maintain association state.
2960
3014
  var RESOLVE_DELAY = 25;
@@ -3150,7 +3204,7 @@
3150
3204
  updatePlaceholderVisibility();
3151
3205
  return;
3152
3206
  }
3153
- pendingDiffs[idx] = _objectSpread$6(_objectSpread$6({}, pendingDiffs[idx]), {}, {
3207
+ pendingDiffs[idx] = _objectSpread$7(_objectSpread$7({}, pendingDiffs[idx]), {}, {
3154
3208
  diff: merged
3155
3209
  });
3156
3210
  };
@@ -3505,7 +3559,7 @@
3505
3559
  if (insertPositionHint === null) {
3506
3560
  insertPositionHint = _diff;
3507
3561
  } else if (insertPositionHint && slate.Range.isCollapsed(targetRange) && insertPositionHint.end + insertPositionHint.text.length === _start2.offset) {
3508
- insertPositionHint = _objectSpread$6(_objectSpread$6({}, insertPositionHint), {}, {
3562
+ insertPositionHint = _objectSpread$7(_objectSpread$7({}, insertPositionHint), {}, {
3509
3563
  text: insertPositionHint.text + _text
3510
3564
  });
3511
3565
  } else {
@@ -3649,8 +3703,8 @@
3649
3703
  }
3650
3704
 
3651
3705
  var _excluded$2 = ["node"];
3652
- function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3653
- function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3706
+ function ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3707
+ function _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3654
3708
  var MUTATION_OBSERVER_CONFIG$1 = {
3655
3709
  subtree: true,
3656
3710
  childList: true,
@@ -3667,7 +3721,7 @@
3667
3721
  var editor = useSlateStatic();
3668
3722
  var isMounted = useIsMounted();
3669
3723
  var _useState = React.useState(function () {
3670
- return createAndroidInputManager(_objectSpread$5({
3724
+ return createAndroidInputManager(_objectSpread$6({
3671
3725
  editor: editor
3672
3726
  }, options));
3673
3727
  }),
@@ -4180,8 +4234,8 @@
4180
4234
  return ResizeObserver;
4181
4235
  }());
4182
4236
 
4183
- function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4184
- function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4237
+ function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4238
+ function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4185
4239
  /**
4186
4240
  * Leaf content strings.
4187
4241
  */
@@ -4298,11 +4352,11 @@
4298
4352
  // be because accepting an IME suggestion when at the start of a block (no
4299
4353
  // preceding \uFEFF) removes one or more DOM elements that `toSlateRange`
4300
4354
  // depends on. (https://github.com/ianstormtaylor/slate/issues/5703)
4301
- return /*#__PURE__*/React.createElement("span", _objectSpread$4({}, attributes), !IS_ANDROID || !isLineBreak ? "\uFEFF" : null, isLineBreak ? /*#__PURE__*/React.createElement("br", null) : null);
4355
+ return /*#__PURE__*/React.createElement("span", _objectSpread$5({}, attributes), !IS_ANDROID || !isLineBreak ? "\uFEFF" : null, isLineBreak ? /*#__PURE__*/React.createElement("br", null) : null);
4302
4356
  };
4303
4357
 
4304
- function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4305
- function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4358
+ function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4359
+ function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4306
4360
  // Delay the placeholder on Android to prevent the keyboard from closing.
4307
4361
  // (https://github.com/ianstormtaylor/slate/pull/5368)
4308
4362
  var PLACEHOLDER_DELAY = IS_ANDROID ? 300 : 0;
@@ -4320,6 +4374,9 @@
4320
4374
  timeoutRef.current = null;
4321
4375
  }
4322
4376
  }
4377
+ var defaultRenderLeaf = function defaultRenderLeaf(props) {
4378
+ return /*#__PURE__*/React.createElement(DefaultLeaf, _objectSpread$4({}, props));
4379
+ };
4323
4380
  /**
4324
4381
  * Individual leaves in a text node with unique formatting.
4325
4382
  */
@@ -4330,9 +4387,7 @@
4330
4387
  parent = props.parent,
4331
4388
  renderPlaceholder = props.renderPlaceholder,
4332
4389
  _props$renderLeaf = props.renderLeaf,
4333
- renderLeaf = _props$renderLeaf === void 0 ? function (props) {
4334
- return /*#__PURE__*/React.createElement(DefaultLeaf, _objectSpread$3({}, props));
4335
- } : _props$renderLeaf,
4390
+ renderLeaf = _props$renderLeaf === void 0 ? defaultRenderLeaf : _props$renderLeaf,
4336
4391
  leafPosition = props.leafPosition;
4337
4392
  var editor = useSlateStatic();
4338
4393
  var placeholderResizeObserver = React.useRef(null);
@@ -4430,27 +4485,198 @@
4430
4485
  var DefaultLeaf = function DefaultLeaf(props) {
4431
4486
  var attributes = props.attributes,
4432
4487
  children = props.children;
4433
- return /*#__PURE__*/React.createElement("span", _objectSpread$3({}, attributes), children);
4488
+ return /*#__PURE__*/React.createElement("span", _objectSpread$4({}, attributes), children);
4434
4489
  };
4435
4490
 
4436
- function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4437
- function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4491
+ var arrayWithoutHoles = createCommonjsModule(function (module) {
4492
+ function _arrayWithoutHoles(arr) {
4493
+ if (Array.isArray(arr)) return arrayLikeToArray(arr);
4494
+ }
4495
+ module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
4496
+ });
4497
+
4498
+ unwrapExports(arrayWithoutHoles);
4499
+
4500
+ var iterableToArray = createCommonjsModule(function (module) {
4501
+ function _iterableToArray(iter) {
4502
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
4503
+ }
4504
+ module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
4505
+ });
4506
+
4507
+ unwrapExports(iterableToArray);
4508
+
4509
+ var nonIterableSpread = createCommonjsModule(function (module) {
4510
+ function _nonIterableSpread() {
4511
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
4512
+ }
4513
+ module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
4514
+ });
4515
+
4516
+ unwrapExports(nonIterableSpread);
4517
+
4518
+ var toConsumableArray = createCommonjsModule(function (module) {
4519
+ function _toConsumableArray(arr) {
4520
+ return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
4521
+ }
4522
+ module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
4523
+ });
4524
+
4525
+ var _toConsumableArray = unwrapExports(toConsumableArray);
4526
+
4527
+ /**
4528
+ * Create a selector that updates when an `update` function is called, and
4529
+ * which only causes the component to render when the result of `selector`
4530
+ * differs from the previous result according to `equalityFn`.
4531
+ *
4532
+ * If `selector` is memoized using `useCallback`, then it will only be called
4533
+ * when it changes or when `update` is called. Otherwise, `selector` will be
4534
+ * called every time the component renders.
4535
+ *
4536
+ * @example
4537
+ * const [state, update] = useGenericSelector(selector, equalityFn)
4538
+ *
4539
+ * useIsomorphicLayoutEffect(() => {
4540
+ * return addEventListener(update)
4541
+ * }, [addEventListener, update])
4542
+ *
4543
+ * return state
4544
+ */
4545
+ function useGenericSelector(selector, equalityFn) {
4546
+ var _useReducer = React.useReducer(function (s) {
4547
+ return s + 1;
4548
+ }, 0),
4549
+ _useReducer2 = _slicedToArray(_useReducer, 2),
4550
+ forceRender = _useReducer2[1];
4551
+ var latestSubscriptionCallbackError = React.useRef();
4552
+ var latestSelector = React.useRef(function () {
4553
+ return null;
4554
+ });
4555
+ var latestSelectedState = React.useRef(null);
4556
+ var selectedState;
4557
+ try {
4558
+ if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) {
4559
+ var selectorResult = selector();
4560
+ if (equalityFn(latestSelectedState.current, selectorResult)) {
4561
+ selectedState = latestSelectedState.current;
4562
+ } else {
4563
+ selectedState = selectorResult;
4564
+ }
4565
+ } else {
4566
+ selectedState = latestSelectedState.current;
4567
+ }
4568
+ } catch (err) {
4569
+ if (latestSubscriptionCallbackError.current && isError(err)) {
4570
+ err.message += "\nThe error may be correlated with this previous error:\n".concat(latestSubscriptionCallbackError.current.stack, "\n\n");
4571
+ }
4572
+ throw err;
4573
+ }
4574
+ latestSelector.current = selector;
4575
+ latestSelectedState.current = selectedState;
4576
+ latestSubscriptionCallbackError.current = undefined;
4577
+ var update = React.useCallback(function () {
4578
+ try {
4579
+ var newSelectedState = latestSelector.current();
4580
+ if (equalityFn(latestSelectedState.current, newSelectedState)) {
4581
+ return;
4582
+ }
4583
+ latestSelectedState.current = newSelectedState;
4584
+ } catch (err) {
4585
+ // we ignore all errors here, since when the component
4586
+ // is re-rendered, the selectors are called again, and
4587
+ // will throw again, if neither props nor store state
4588
+ // changed
4589
+ if (err instanceof Error) {
4590
+ latestSubscriptionCallbackError.current = err;
4591
+ } else {
4592
+ latestSubscriptionCallbackError.current = new Error(String(err));
4593
+ }
4594
+ }
4595
+ forceRender();
4596
+ // don't rerender on equalityFn change since we want to be able to define it inline
4597
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4598
+ }, []);
4599
+ return [selectedState, update];
4600
+ }
4601
+ function isError(error) {
4602
+ return error instanceof Error;
4603
+ }
4604
+
4605
+ /**
4606
+ * A React context for sharing the `decorate` prop of the editable and
4607
+ * subscribing to changes on this prop.
4608
+ */
4609
+ var DecorateContext = /*#__PURE__*/React.createContext({});
4610
+ var useDecorations = function useDecorations(node, parentDecorations) {
4611
+ var editor = useSlateStatic();
4612
+ var _useContext = React.useContext(DecorateContext),
4613
+ decorate = _useContext.decorate,
4614
+ addEventListener = _useContext.addEventListener;
4615
+ // Not memoized since we want nodes to be decorated on each render
4616
+ var selector = function selector() {
4617
+ var path = ReactEditor.findPath(editor, node);
4618
+ return decorate([node, path]);
4619
+ };
4620
+ var equalityFn = slate.Text.isText(node) ? isTextDecorationsEqual : isElementDecorationsEqual;
4621
+ var _useGenericSelector = useGenericSelector(selector, equalityFn),
4622
+ _useGenericSelector2 = _slicedToArray(_useGenericSelector, 2),
4623
+ decorations = _useGenericSelector2[0],
4624
+ update = _useGenericSelector2[1];
4625
+ useIsomorphicLayoutEffect(function () {
4626
+ var unsubscribe = addEventListener(update);
4627
+ update();
4628
+ return unsubscribe;
4629
+ }, [addEventListener, update]);
4630
+ return React.useMemo(function () {
4631
+ return [].concat(_toConsumableArray(decorations), _toConsumableArray(parentDecorations));
4632
+ }, [decorations, parentDecorations]);
4633
+ };
4634
+ var useDecorateContext = function useDecorateContext(decorateProp) {
4635
+ var eventListeners = React.useRef(new Set());
4636
+ var latestDecorate = React.useRef(decorateProp);
4637
+ useIsomorphicLayoutEffect(function () {
4638
+ latestDecorate.current = decorateProp;
4639
+ eventListeners.current.forEach(function (listener) {
4640
+ return listener();
4641
+ });
4642
+ }, [decorateProp]);
4643
+ var decorate = React.useCallback(function (entry) {
4644
+ return latestDecorate.current(entry);
4645
+ }, []);
4646
+ var addEventListener = React.useCallback(function (callback) {
4647
+ eventListeners.current.add(callback);
4648
+ return function () {
4649
+ eventListeners.current["delete"](callback);
4650
+ };
4651
+ }, []);
4652
+ return React.useMemo(function () {
4653
+ return {
4654
+ decorate: decorate,
4655
+ addEventListener: addEventListener
4656
+ };
4657
+ }, [decorate, addEventListener]);
4658
+ };
4659
+
4660
+ function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4661
+ function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4662
+ var defaultRenderText = function defaultRenderText(props) {
4663
+ return /*#__PURE__*/React.createElement(DefaultText, _objectSpread$3({}, props));
4664
+ };
4438
4665
  /**
4439
4666
  * Text.
4440
4667
  */
4441
4668
  var Text = function Text(props) {
4442
- var decorations = props.decorations,
4669
+ var parentDecorations = props.decorations,
4443
4670
  isLast = props.isLast,
4444
4671
  parent = props.parent,
4445
4672
  renderPlaceholder = props.renderPlaceholder,
4446
4673
  renderLeaf = props.renderLeaf,
4447
4674
  _props$renderText = props.renderText,
4448
- renderText = _props$renderText === void 0 ? function (props) {
4449
- return /*#__PURE__*/React.createElement(DefaultText, _objectSpread$2({}, props));
4450
- } : _props$renderText,
4675
+ renderText = _props$renderText === void 0 ? defaultRenderText : _props$renderText,
4451
4676
  text = props.text;
4452
4677
  var editor = useSlateStatic();
4453
4678
  var ref = React.useRef(null);
4679
+ var decorations = useDecorations(text, parentDecorations);
4454
4680
  var decoratedLeaves = slate.Text.decorations(text, decorations);
4455
4681
  var key = ReactEditor.findKey(editor, text);
4456
4682
  var children = [];
@@ -4501,28 +4727,30 @@
4501
4727
  var DefaultText = function DefaultText(props) {
4502
4728
  var attributes = props.attributes,
4503
4729
  children = props.children;
4504
- return /*#__PURE__*/React.createElement("span", _objectSpread$2({}, attributes), children);
4730
+ return /*#__PURE__*/React.createElement("span", _objectSpread$3({}, attributes), children);
4505
4731
  };
4506
4732
 
4507
- function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4508
- function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4733
+ function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4734
+ function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4735
+ var defaultRenderElement = function defaultRenderElement(props) {
4736
+ return /*#__PURE__*/React.createElement(DefaultElement, _objectSpread$2({}, props));
4737
+ };
4509
4738
  /**
4510
4739
  * Element.
4511
4740
  */
4512
4741
  var Element$1 = function Element(props) {
4513
- var decorations = props.decorations,
4742
+ var parentDecorations = props.decorations,
4514
4743
  element = props.element,
4515
4744
  _props$renderElement = props.renderElement,
4516
- renderElement = _props$renderElement === void 0 ? function (p) {
4517
- return /*#__PURE__*/React.createElement(DefaultElement, _objectSpread$1({}, p));
4518
- } : _props$renderElement,
4745
+ renderElement = _props$renderElement === void 0 ? defaultRenderElement : _props$renderElement,
4746
+ renderChunk = props.renderChunk,
4519
4747
  renderPlaceholder = props.renderPlaceholder,
4520
4748
  renderLeaf = props.renderLeaf,
4521
- renderText = props.renderText,
4522
- selection = props.selection;
4749
+ renderText = props.renderText;
4523
4750
  var editor = useSlateStatic();
4524
4751
  var readOnly = useReadOnly();
4525
4752
  var isInline = editor.isInline(element);
4753
+ var decorations = useDecorations(element, parentDecorations);
4526
4754
  var key = ReactEditor.findKey(editor, element);
4527
4755
  var ref = React.useCallback(function (ref) {
4528
4756
  // Update element-related weak maps with the DOM element ref.
@@ -4540,10 +4768,10 @@
4540
4768
  decorations: decorations,
4541
4769
  node: element,
4542
4770
  renderElement: renderElement,
4771
+ renderChunk: renderChunk,
4543
4772
  renderPlaceholder: renderPlaceholder,
4544
4773
  renderLeaf: renderLeaf,
4545
- renderText: renderText,
4546
- selection: selection
4774
+ renderText: renderText
4547
4775
  });
4548
4776
  // Attributes that the developer must mix into the element in their
4549
4777
  // custom node renderer component.
@@ -4599,7 +4827,7 @@
4599
4827
  });
4600
4828
  };
4601
4829
  var MemoizedElement = /*#__PURE__*/React.memo(Element$1, function (prev, next) {
4602
- return prev.element === next.element && prev.renderElement === next.renderElement && prev.renderText === next.renderText && prev.renderLeaf === next.renderLeaf && prev.renderPlaceholder === next.renderPlaceholder && isElementDecorationsEqual(prev.decorations, next.decorations) && (prev.selection === next.selection || !!prev.selection && !!next.selection && slate.Range.equals(prev.selection, next.selection));
4830
+ return prev.element === next.element && prev.renderElement === next.renderElement && prev.renderChunk === next.renderChunk && prev.renderText === next.renderText && prev.renderLeaf === next.renderLeaf && prev.renderPlaceholder === next.renderPlaceholder && isElementDecorationsEqual(prev.decorations, next.decorations);
4603
4831
  });
4604
4832
  /**
4605
4833
  * The default element renderer.
@@ -4610,40 +4838,830 @@
4610
4838
  element = props.element;
4611
4839
  var editor = useSlateStatic();
4612
4840
  var Tag = editor.isInline(element) ? 'span' : 'div';
4613
- return /*#__PURE__*/React.createElement(Tag, _objectSpread$1(_objectSpread$1({}, attributes), {}, {
4841
+ return /*#__PURE__*/React.createElement(Tag, _objectSpread$2(_objectSpread$2({}, attributes), {}, {
4614
4842
  style: {
4615
4843
  position: 'relative'
4616
4844
  }
4617
4845
  }), children);
4618
4846
  };
4619
4847
 
4848
+ var classCallCheck = createCommonjsModule(function (module) {
4849
+ function _classCallCheck(instance, Constructor) {
4850
+ if (!(instance instanceof Constructor)) {
4851
+ throw new TypeError("Cannot call a class as a function");
4852
+ }
4853
+ }
4854
+ module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
4855
+ });
4856
+
4857
+ var _classCallCheck = unwrapExports(classCallCheck);
4858
+
4859
+ var createClass = createCommonjsModule(function (module) {
4860
+ function _defineProperties(target, props) {
4861
+ for (var i = 0; i < props.length; i++) {
4862
+ var descriptor = props[i];
4863
+ descriptor.enumerable = descriptor.enumerable || false;
4864
+ descriptor.configurable = true;
4865
+ if ("value" in descriptor) descriptor.writable = true;
4866
+ Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
4867
+ }
4868
+ }
4869
+ function _createClass(Constructor, protoProps, staticProps) {
4870
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
4871
+ if (staticProps) _defineProperties(Constructor, staticProps);
4872
+ Object.defineProperty(Constructor, "prototype", {
4873
+ writable: false
4874
+ });
4875
+ return Constructor;
4876
+ }
4877
+ module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
4878
+ });
4879
+
4880
+ var _createClass = unwrapExports(createClass);
4881
+
4620
4882
  /**
4621
- * A React context for sharing the `decorate` prop of the editable.
4883
+ * Traverse and modify a chunk tree
4622
4884
  */
4623
- var DecorateContext = /*#__PURE__*/React.createContext(function () {
4624
- return [];
4625
- });
4885
+ var ChunkTreeHelper = /*#__PURE__*/function () {
4886
+ function ChunkTreeHelper(chunkTree, _ref) {
4887
+ var chunkSize = _ref.chunkSize,
4888
+ debug = _ref.debug;
4889
+ _classCallCheck(this, ChunkTreeHelper);
4890
+ /**
4891
+ * The root of the chunk tree
4892
+ */
4893
+ _defineProperty$1(this, "root", void 0);
4894
+ /**
4895
+ * The ideal size of a chunk
4896
+ */
4897
+ _defineProperty$1(this, "chunkSize", void 0);
4898
+ /**
4899
+ * Whether debug mode is enabled
4900
+ *
4901
+ * If enabled, the pointer state will be checked for internal consistency
4902
+ * after each mutating operation.
4903
+ */
4904
+ _defineProperty$1(this, "debug", void 0);
4905
+ /**
4906
+ * Whether the traversal has reached the end of the chunk tree
4907
+ *
4908
+ * When this is true, the pointerChunk and pointerIndex point to the last
4909
+ * top-level node in the chunk tree, although pointerNode returns null.
4910
+ */
4911
+ _defineProperty$1(this, "reachedEnd", void 0);
4912
+ /**
4913
+ * The chunk containing the current node
4914
+ */
4915
+ _defineProperty$1(this, "pointerChunk", void 0);
4916
+ /**
4917
+ * The index of the current node within pointerChunk
4918
+ *
4919
+ * Can be -1 to indicate that the pointer is before the start of the tree.
4920
+ */
4921
+ _defineProperty$1(this, "pointerIndex", void 0);
4922
+ /**
4923
+ * Similar to a Slate path; tracks the path of pointerChunk relative to the
4924
+ * root.
4925
+ *
4926
+ * Used to move the pointer from the current chunk to the parent chunk more
4927
+ * efficiently.
4928
+ */
4929
+ _defineProperty$1(this, "pointerIndexStack", void 0);
4930
+ /**
4931
+ * Indexing the current chunk's children has a slight time cost, which adds up
4932
+ * when traversing very large trees, so the current node is cached.
4933
+ *
4934
+ * A value of undefined means that the current node is not cached. This
4935
+ * property must be set to undefined whenever the pointer is moved, unless
4936
+ * the pointer is guaranteed to point to the same node that it did previously.
4937
+ */
4938
+ _defineProperty$1(this, "cachedPointerNode", void 0);
4939
+ this.root = chunkTree;
4940
+ this.chunkSize = chunkSize;
4941
+ // istanbul ignore next
4942
+ this.debug = debug !== null && debug !== void 0 ? debug : false;
4943
+ this.pointerChunk = chunkTree;
4944
+ this.pointerIndex = -1;
4945
+ this.pointerIndexStack = [];
4946
+ this.reachedEnd = false;
4947
+ this.validateState();
4948
+ }
4949
+ /**
4950
+ * Move the pointer to the next leaf in the chunk tree
4951
+ */
4952
+ _createClass(ChunkTreeHelper, [{
4953
+ key: "readLeaf",
4954
+ value: function readLeaf() {
4955
+ // istanbul ignore next
4956
+ if (this.reachedEnd) return null;
4957
+ // Get the next sibling or aunt node
4958
+ while (true) {
4959
+ if (this.pointerIndex + 1 < this.pointerSiblings.length) {
4960
+ this.pointerIndex++;
4961
+ this.cachedPointerNode = undefined;
4962
+ break;
4963
+ } else if (this.pointerChunk.type === 'root') {
4964
+ this.reachedEnd = true;
4965
+ return null;
4966
+ } else {
4967
+ this.exitChunk();
4968
+ }
4969
+ }
4970
+ this.validateState();
4971
+ // If the next sibling or aunt is a chunk, descend into it
4972
+ this.enterChunkUntilLeaf(false);
4973
+ return this.pointerNode;
4974
+ }
4975
+ /**
4976
+ * Move the pointer to the previous leaf in the chunk tree
4977
+ */
4978
+ }, {
4979
+ key: "returnToPreviousLeaf",
4980
+ value: function returnToPreviousLeaf() {
4981
+ // If we were at the end of the tree, descend into the end of the last
4982
+ // chunk in the tree
4983
+ if (this.reachedEnd) {
4984
+ this.reachedEnd = false;
4985
+ this.enterChunkUntilLeaf(true);
4986
+ return;
4987
+ }
4988
+ // Get the previous sibling or aunt node
4989
+ while (true) {
4990
+ if (this.pointerIndex >= 1) {
4991
+ this.pointerIndex--;
4992
+ this.cachedPointerNode = undefined;
4993
+ break;
4994
+ } else if (this.pointerChunk.type === 'root') {
4995
+ this.pointerIndex = -1;
4996
+ return;
4997
+ } else {
4998
+ this.exitChunk();
4999
+ }
5000
+ }
5001
+ this.validateState();
5002
+ // If the previous sibling or aunt is a chunk, descend into it
5003
+ this.enterChunkUntilLeaf(true);
5004
+ }
5005
+ /**
5006
+ * Insert leaves before the current leaf, leaving the pointer unchanged
5007
+ */
5008
+ }, {
5009
+ key: "insertBefore",
5010
+ value: function insertBefore(leaves) {
5011
+ this.returnToPreviousLeaf();
5012
+ this.insertAfter(leaves);
5013
+ this.readLeaf();
5014
+ }
5015
+ /**
5016
+ * Insert leaves after the current leaf, leaving the pointer on the last
5017
+ * inserted leaf
5018
+ *
5019
+ * The insertion algorithm first checks for any chunk we're currently at the
5020
+ * end of that can receive additional leaves. Next, it tries to insert leaves
5021
+ * at the starts of any subsequent chunks.
5022
+ *
5023
+ * Any remaining leaves are passed to rawInsertAfter to be chunked and
5024
+ * inserted at the highest possible level.
5025
+ */
5026
+ }, {
5027
+ key: "insertAfter",
5028
+ value: function insertAfter(leaves) {
5029
+ // istanbul ignore next
5030
+ if (leaves.length === 0) return;
5031
+ var beforeDepth = 0;
5032
+ var afterDepth = 0;
5033
+ // While at the end of a chunk, insert any leaves that will fit, and then
5034
+ // exit the chunk
5035
+ while (this.pointerChunk.type === 'chunk' && this.pointerIndex === this.pointerSiblings.length - 1) {
5036
+ var remainingCapacity = this.chunkSize - this.pointerSiblings.length;
5037
+ var toInsertCount = Math.min(remainingCapacity, leaves.length);
5038
+ if (toInsertCount > 0) {
5039
+ var leavesToInsert = leaves.splice(0, toInsertCount);
5040
+ this.rawInsertAfter(leavesToInsert, beforeDepth);
5041
+ }
5042
+ this.exitChunk();
5043
+ beforeDepth++;
5044
+ }
5045
+ if (leaves.length === 0) return;
5046
+ // Save the pointer so that we can come back here after inserting leaves
5047
+ // into the starts of subsequent blocks
5048
+ var rawInsertPointer = this.savePointer();
5049
+ // If leaves are inserted into the start of a subsequent block, then we
5050
+ // eventually need to restore the pointer to the last such inserted leaf
5051
+ var finalPointer = null;
5052
+ // Move the pointer into the chunk containing the next leaf, if it exists
5053
+ if (this.readLeaf()) {
5054
+ // While at the start of a chunk, insert any leaves that will fit, and
5055
+ // then exit the chunk
5056
+ while (this.pointerChunk.type === 'chunk' && this.pointerIndex === 0) {
5057
+ var _remainingCapacity = this.chunkSize - this.pointerSiblings.length;
5058
+ var _toInsertCount = Math.min(_remainingCapacity, leaves.length);
5059
+ if (_toInsertCount > 0) {
5060
+ var _leavesToInsert = leaves.splice(-_toInsertCount, _toInsertCount);
5061
+ // Insert the leaves at the start of the chunk
5062
+ this.pointerIndex = -1;
5063
+ this.cachedPointerNode = undefined;
5064
+ this.rawInsertAfter(_leavesToInsert, afterDepth);
5065
+ // If this is the first batch of insertions at the start of a
5066
+ // subsequent chunk, set the final pointer to the last inserted leaf
5067
+ if (!finalPointer) {
5068
+ finalPointer = this.savePointer();
5069
+ }
5070
+ }
5071
+ this.exitChunk();
5072
+ afterDepth++;
5073
+ }
5074
+ }
5075
+ this.restorePointer(rawInsertPointer);
5076
+ // If there are leaves left to insert, insert them between the end of the
5077
+ // previous chunk and the start of the first subsequent chunk, or wherever
5078
+ // the pointer ended up after the first batch of insertions
5079
+ var minDepth = Math.max(beforeDepth, afterDepth);
5080
+ this.rawInsertAfter(leaves, minDepth);
5081
+ if (finalPointer) {
5082
+ this.restorePointer(finalPointer);
5083
+ }
5084
+ this.validateState();
5085
+ }
5086
+ /**
5087
+ * Remove the current node and decrement the pointer, deleting any ancestor
5088
+ * chunk that becomes empty as a result
5089
+ */
5090
+ }, {
5091
+ key: "remove",
5092
+ value: function remove() {
5093
+ this.pointerSiblings.splice(this.pointerIndex--, 1);
5094
+ this.cachedPointerNode = undefined;
5095
+ if (this.pointerSiblings.length === 0 && this.pointerChunk.type === 'chunk') {
5096
+ this.exitChunk();
5097
+ this.remove();
5098
+ } else {
5099
+ this.invalidateChunk();
5100
+ }
5101
+ this.validateState();
5102
+ }
5103
+ /**
5104
+ * Add the current chunk and all ancestor chunks to the list of modified
5105
+ * chunks
5106
+ */
5107
+ }, {
5108
+ key: "invalidateChunk",
5109
+ value: function invalidateChunk() {
5110
+ for (var c = this.pointerChunk; c.type === 'chunk'; c = c.parent) {
5111
+ this.root.modifiedChunks.add(c);
5112
+ }
5113
+ }
5114
+ /**
5115
+ * Whether the pointer is at the start of the tree
5116
+ */
5117
+ }, {
5118
+ key: "atStart",
5119
+ get: function get() {
5120
+ return this.pointerChunk.type === 'root' && this.pointerIndex === -1;
5121
+ }
5122
+ /**
5123
+ * The siblings of the current node
5124
+ */
5125
+ }, {
5126
+ key: "pointerSiblings",
5127
+ get: function get() {
5128
+ return this.pointerChunk.children;
5129
+ }
5130
+ /**
5131
+ * Get the current node (uncached)
5132
+ *
5133
+ * If the pointer is at the start or end of the document, returns null.
5134
+ *
5135
+ * Usually, the current node is a chunk leaf, although it can be a chunk
5136
+ * while insertions are in progress.
5137
+ */
5138
+ }, {
5139
+ key: "getPointerNode",
5140
+ value: function getPointerNode() {
5141
+ if (this.reachedEnd || this.pointerIndex === -1) {
5142
+ return null;
5143
+ }
5144
+ return this.pointerSiblings[this.pointerIndex];
5145
+ }
5146
+ /**
5147
+ * Cached getter for the current node
5148
+ */
5149
+ }, {
5150
+ key: "pointerNode",
5151
+ get: function get() {
5152
+ if (this.cachedPointerNode !== undefined) return this.cachedPointerNode;
5153
+ var pointerNode = this.getPointerNode();
5154
+ this.cachedPointerNode = pointerNode;
5155
+ return pointerNode;
5156
+ }
5157
+ /**
5158
+ * Get the path of a chunk relative to the root, returning null if the chunk
5159
+ * is not connected to the root
5160
+ */
5161
+ }, {
5162
+ key: "getChunkPath",
5163
+ value: function getChunkPath(chunk) {
5164
+ var path = [];
5165
+ for (var c = chunk; c.type === 'chunk'; c = c.parent) {
5166
+ var index = c.parent.children.indexOf(c);
5167
+ // istanbul ignore next
5168
+ if (index === -1) {
5169
+ return null;
5170
+ }
5171
+ path.unshift(index);
5172
+ }
5173
+ return path;
5174
+ }
5175
+ /**
5176
+ * Save the current pointer to be restored later
5177
+ */
5178
+ }, {
5179
+ key: "savePointer",
5180
+ value: function savePointer() {
5181
+ if (this.atStart) return 'start';
5182
+ // istanbul ignore next
5183
+ if (!this.pointerNode) {
5184
+ throw new Error('Cannot save pointer when pointerNode is null');
5185
+ }
5186
+ return {
5187
+ chunk: this.pointerChunk,
5188
+ node: this.pointerNode
5189
+ };
5190
+ }
5191
+ /**
5192
+ * Restore the pointer to a previous state
5193
+ */
5194
+ }, {
5195
+ key: "restorePointer",
5196
+ value: function restorePointer(savedPointer) {
5197
+ if (savedPointer === 'start') {
5198
+ this.pointerChunk = this.root;
5199
+ this.pointerIndex = -1;
5200
+ this.pointerIndexStack = [];
5201
+ this.reachedEnd = false;
5202
+ this.cachedPointerNode = undefined;
5203
+ return;
5204
+ }
5205
+ // Since nodes may have been inserted or removed prior to the saved
5206
+ // pointer since it was saved, the index and index stack must be
5207
+ // recomputed. This is slow, but this is fine since restoring a pointer is
5208
+ // not a frequent operation.
5209
+ var chunk = savedPointer.chunk,
5210
+ node = savedPointer.node;
5211
+ var index = chunk.children.indexOf(node);
5212
+ // istanbul ignore next
5213
+ if (index === -1) {
5214
+ throw new Error('Cannot restore point because saved node is no longer in saved chunk');
5215
+ }
5216
+ var indexStack = this.getChunkPath(chunk);
5217
+ // istanbul ignore next
5218
+ if (!indexStack) {
5219
+ throw new Error('Cannot restore point because saved chunk is no longer connected to root');
5220
+ }
5221
+ this.pointerChunk = chunk;
5222
+ this.pointerIndex = index;
5223
+ this.pointerIndexStack = indexStack;
5224
+ this.reachedEnd = false;
5225
+ this.cachedPointerNode = node;
5226
+ this.validateState();
5227
+ }
5228
+ /**
5229
+ * Assuming the current node is a chunk, move the pointer into that chunk
5230
+ *
5231
+ * @param end If true, place the pointer on the last node of the chunk.
5232
+ * Otherwise, place the pointer on the first node.
5233
+ */
5234
+ }, {
5235
+ key: "enterChunk",
5236
+ value: function enterChunk(end) {
5237
+ var _this$pointerNode;
5238
+ // istanbul ignore next
5239
+ if (((_this$pointerNode = this.pointerNode) === null || _this$pointerNode === void 0 ? void 0 : _this$pointerNode.type) !== 'chunk') {
5240
+ throw new Error('Cannot enter non-chunk');
5241
+ }
5242
+ this.pointerIndexStack.push(this.pointerIndex);
5243
+ this.pointerChunk = this.pointerNode;
5244
+ this.pointerIndex = end ? this.pointerSiblings.length - 1 : 0;
5245
+ this.cachedPointerNode = undefined;
5246
+ this.validateState();
5247
+ // istanbul ignore next
5248
+ if (this.pointerChunk.children.length === 0) {
5249
+ throw new Error('Cannot enter empty chunk');
5250
+ }
5251
+ }
5252
+ /**
5253
+ * Assuming the current node is a chunk, move the pointer into that chunk
5254
+ * repeatedly until the current node is a leaf
5255
+ *
5256
+ * @param end If true, place the pointer on the last node of the chunk.
5257
+ * Otherwise, place the pointer on the first node.
5258
+ */
5259
+ }, {
5260
+ key: "enterChunkUntilLeaf",
5261
+ value: function enterChunkUntilLeaf(end) {
5262
+ while (((_this$pointerNode2 = this.pointerNode) === null || _this$pointerNode2 === void 0 ? void 0 : _this$pointerNode2.type) === 'chunk') {
5263
+ var _this$pointerNode2;
5264
+ this.enterChunk(end);
5265
+ }
5266
+ }
5267
+ /**
5268
+ * Move the pointer to the parent chunk
5269
+ */
5270
+ }, {
5271
+ key: "exitChunk",
5272
+ value: function exitChunk() {
5273
+ // istanbul ignore next
5274
+ if (this.pointerChunk.type === 'root') {
5275
+ throw new Error('Cannot exit root');
5276
+ }
5277
+ var previousPointerChunk = this.pointerChunk;
5278
+ this.pointerChunk = previousPointerChunk.parent;
5279
+ this.pointerIndex = this.pointerIndexStack.pop();
5280
+ this.cachedPointerNode = undefined;
5281
+ this.validateState();
5282
+ }
5283
+ /**
5284
+ * Insert leaves immediately after the current node, leaving the pointer on
5285
+ * the last inserted leaf
5286
+ *
5287
+ * Leaves are chunked according to the number of nodes already in the parent
5288
+ * plus the number of nodes being inserted, or the minimum depth if larger
5289
+ */
5290
+ }, {
5291
+ key: "rawInsertAfter",
5292
+ value: function rawInsertAfter(leaves, minDepth) {
5293
+ var _this = this,
5294
+ _this$pointerSiblings;
5295
+ if (leaves.length === 0) return;
5296
+ var groupIntoChunks = function groupIntoChunks(leaves, parent, perChunk) {
5297
+ if (perChunk === 1) return leaves;
5298
+ var chunks = [];
5299
+ for (var i = 0; i < _this.chunkSize; i++) {
5300
+ var chunkNodes = leaves.slice(i * perChunk, (i + 1) * perChunk);
5301
+ if (chunkNodes.length === 0) break;
5302
+ var chunk = {
5303
+ type: 'chunk',
5304
+ key: new Key(),
5305
+ parent: parent,
5306
+ children: []
5307
+ };
5308
+ chunk.children = groupIntoChunks(chunkNodes, chunk, perChunk / _this.chunkSize);
5309
+ chunks.push(chunk);
5310
+ }
5311
+ return chunks;
5312
+ };
5313
+ // Determine the chunking depth based on the number of existing nodes in
5314
+ // the chunk and the number of nodes being inserted
5315
+ var newTotal = this.pointerSiblings.length + leaves.length;
5316
+ var depthForTotal = 0;
5317
+ for (var i = this.chunkSize; i < newTotal; i *= this.chunkSize) {
5318
+ depthForTotal++;
5319
+ }
5320
+ // A depth of 0 means no chunking
5321
+ var depth = Math.max(depthForTotal, minDepth);
5322
+ var perTopLevelChunk = Math.pow(this.chunkSize, depth);
5323
+ var chunks = groupIntoChunks(leaves, this.pointerChunk, perTopLevelChunk);
5324
+ (_this$pointerSiblings = this.pointerSiblings).splice.apply(_this$pointerSiblings, [this.pointerIndex + 1, 0].concat(_toConsumableArray(chunks)));
5325
+ this.pointerIndex += chunks.length;
5326
+ this.cachedPointerNode = undefined;
5327
+ this.invalidateChunk();
5328
+ this.validateState();
5329
+ }
5330
+ /**
5331
+ * If debug mode is enabled, ensure that the state is internally consistent
5332
+ */
5333
+ // istanbul ignore next
5334
+ }, {
5335
+ key: "validateState",
5336
+ value: function validateState() {
5337
+ if (!this.debug) return;
5338
+ var validateDescendant = function validateDescendant(node) {
5339
+ if (node.type === 'chunk') {
5340
+ var parent = node.parent,
5341
+ children = node.children;
5342
+ if (!parent.children.includes(node)) {
5343
+ throw new Error("Debug: Chunk ".concat(node.key.id, " has an incorrect parent property"));
5344
+ }
5345
+ children.forEach(validateDescendant);
5346
+ }
5347
+ };
5348
+ this.root.children.forEach(validateDescendant);
5349
+ if (this.cachedPointerNode !== undefined && this.cachedPointerNode !== this.getPointerNode()) {
5350
+ throw new Error('Debug: The cached pointer is incorrect and has not been invalidated');
5351
+ }
5352
+ var actualIndexStack = this.getChunkPath(this.pointerChunk);
5353
+ if (!actualIndexStack) {
5354
+ throw new Error('Debug: The pointer chunk is not connected to the root');
5355
+ }
5356
+ if (!slate.Path.equals(this.pointerIndexStack, actualIndexStack)) {
5357
+ throw new Error("Debug: The cached index stack [".concat(this.pointerIndexStack.join(', '), "] does not match the path of the pointer chunk [").concat(actualIndexStack.join(', '), "]"));
5358
+ }
5359
+ }
5360
+ }]);
5361
+ return ChunkTreeHelper;
5362
+ }();
5363
+
5364
+ /**
5365
+ * Traverse an array of children, providing helpers useful for reconciling the
5366
+ * children array with a chunk tree
5367
+ */
5368
+ var ChildrenHelper = /*#__PURE__*/function () {
5369
+ function ChildrenHelper(editor, children) {
5370
+ _classCallCheck(this, ChildrenHelper);
5371
+ _defineProperty$1(this, "editor", void 0);
5372
+ _defineProperty$1(this, "children", void 0);
5373
+ /**
5374
+ * Sparse array of Slate node keys, each index corresponding to an index in
5375
+ * the children array
5376
+ *
5377
+ * Fetching the key for a Slate node is expensive, so we cache them here.
5378
+ */
5379
+ _defineProperty$1(this, "cachedKeys", void 0);
5380
+ /**
5381
+ * The index of the next node to be read in the children array
5382
+ */
5383
+ _defineProperty$1(this, "pointerIndex", void 0);
5384
+ this.editor = editor;
5385
+ this.children = children;
5386
+ this.cachedKeys = new Array(children.length);
5387
+ this.pointerIndex = 0;
5388
+ }
5389
+ /**
5390
+ * Read a given number of nodes, advancing the pointer by that amount
5391
+ */
5392
+ _createClass(ChildrenHelper, [{
5393
+ key: "read",
5394
+ value: function read(n) {
5395
+ // PERF: If only one child was requested (the most common case), use array
5396
+ // indexing instead of slice
5397
+ if (n === 1) {
5398
+ return [this.children[this.pointerIndex++]];
5399
+ }
5400
+ var slicedChildren = this.remaining(n);
5401
+ this.pointerIndex += n;
5402
+ return slicedChildren;
5403
+ }
5404
+ /**
5405
+ * Get the remaining children without advancing the pointer
5406
+ *
5407
+ * @param [maxChildren] Limit the number of children returned.
5408
+ */
5409
+ }, {
5410
+ key: "remaining",
5411
+ value: function remaining(maxChildren) {
5412
+ if (maxChildren === undefined) {
5413
+ return this.children.slice(this.pointerIndex);
5414
+ }
5415
+ return this.children.slice(this.pointerIndex, this.pointerIndex + maxChildren);
5416
+ }
5417
+ /**
5418
+ * Whether all children have been read
5419
+ */
5420
+ }, {
5421
+ key: "reachedEnd",
5422
+ get: function get() {
5423
+ return this.pointerIndex >= this.children.length;
5424
+ }
5425
+ /**
5426
+ * Determine whether a node with a given key appears in the unread part of the
5427
+ * children array, and return its index relative to the current pointer if so
5428
+ *
5429
+ * Searching for the node object itself using indexOf is most efficient, but
5430
+ * will fail to locate nodes that have been modified. In this case, nodes
5431
+ * should be identified by their keys instead.
5432
+ *
5433
+ * Searching an array of keys using indexOf is very inefficient since fetching
5434
+ * the keys for all children in advance is very slow. Insead, if the node
5435
+ * search fails to return a value, fetch the keys of each remaining child one
5436
+ * by one and compare it to the known key.
5437
+ */
5438
+ }, {
5439
+ key: "lookAhead",
5440
+ value: function lookAhead(node, key) {
5441
+ var elementResult = this.children.indexOf(node, this.pointerIndex);
5442
+ if (elementResult > -1) return elementResult - this.pointerIndex;
5443
+ for (var i = this.pointerIndex; i < this.children.length; i++) {
5444
+ var candidateNode = this.children[i];
5445
+ var candidateKey = this.findKey(candidateNode, i);
5446
+ if (candidateKey === key) return i - this.pointerIndex;
5447
+ }
5448
+ return -1;
5449
+ }
5450
+ /**
5451
+ * Convert an array of Slate nodes to an array of chunk leaves, each
5452
+ * containing the node and its key
5453
+ */
5454
+ }, {
5455
+ key: "toChunkLeaves",
5456
+ value: function toChunkLeaves(nodes, startIndex) {
5457
+ var _this = this;
5458
+ return nodes.map(function (node, i) {
5459
+ return {
5460
+ type: 'leaf',
5461
+ node: node,
5462
+ key: _this.findKey(node, startIndex + i),
5463
+ index: startIndex + i
5464
+ };
5465
+ });
5466
+ }
5467
+ /**
5468
+ * Get the key for a Slate node, cached using the node's index
5469
+ */
5470
+ }, {
5471
+ key: "findKey",
5472
+ value: function findKey(node, index) {
5473
+ var cachedKey = this.cachedKeys[index];
5474
+ if (cachedKey) return cachedKey;
5475
+ var key = ReactEditor.findKey(this.editor, node);
5476
+ this.cachedKeys[index] = key;
5477
+ return key;
5478
+ }
5479
+ }]);
5480
+ return ChildrenHelper;
5481
+ }();
5482
+
5483
+ /**
5484
+ * Update the chunk tree to match the children array, inserting, removing and
5485
+ * updating differing nodes
5486
+ */
5487
+ var reconcileChildren = function reconcileChildren(editor, _ref) {
5488
+ var chunkTree = _ref.chunkTree,
5489
+ children = _ref.children,
5490
+ chunkSize = _ref.chunkSize,
5491
+ _ref$rerenderChildren = _ref.rerenderChildren,
5492
+ rerenderChildren = _ref$rerenderChildren === void 0 ? [] : _ref$rerenderChildren,
5493
+ onInsert = _ref.onInsert,
5494
+ onUpdate = _ref.onUpdate,
5495
+ onIndexChange = _ref.onIndexChange,
5496
+ debug = _ref.debug;
5497
+ chunkTree.modifiedChunks.clear();
5498
+ var chunkTreeHelper = new ChunkTreeHelper(chunkTree, {
5499
+ chunkSize: chunkSize,
5500
+ debug: debug
5501
+ });
5502
+ var childrenHelper = new ChildrenHelper(editor, children);
5503
+ var treeLeaf;
5504
+ // Read leaves from the tree one by one, each one representing a single Slate
5505
+ // node. Each leaf from the tree is compared to the current node in the
5506
+ // children array to determine whether nodes have been inserted, removed or
5507
+ // updated.
5508
+ var _loop = function _loop() {
5509
+ // Check where the tree node appears in the children array. In the most
5510
+ // common case (where no insertions or removals have occurred), this will be
5511
+ // 0. If the node has been removed, this will be -1. If new nodes have been
5512
+ // inserted before the node, or if the node has been moved to a later
5513
+ // position in the same children array, this will be a positive number.
5514
+ var lookAhead = childrenHelper.lookAhead(treeLeaf.node, treeLeaf.key);
5515
+ // If the node was moved, we want to remove it and insert it later, rather
5516
+ // then re-inserting all intermediate nodes before it.
5517
+ var wasMoved = lookAhead > 0 && chunkTree.movedNodeKeys.has(treeLeaf.key);
5518
+ // If the tree leaf was moved or removed, remove it
5519
+ if (lookAhead === -1 || wasMoved) {
5520
+ chunkTreeHelper.remove();
5521
+ return 1; // continue
5522
+ }
5523
+ // Get the matching Slate node and any nodes that may have been inserted
5524
+ // prior to it. Insert these into the chunk tree.
5525
+ var insertedChildrenStartIndex = childrenHelper.pointerIndex;
5526
+ var insertedChildren = childrenHelper.read(lookAhead + 1);
5527
+ var matchingChild = insertedChildren.pop();
5528
+ if (insertedChildren.length) {
5529
+ var _leavesToInsert = childrenHelper.toChunkLeaves(insertedChildren, insertedChildrenStartIndex);
5530
+ chunkTreeHelper.insertBefore(_leavesToInsert);
5531
+ insertedChildren.forEach(function (node, relativeIndex) {
5532
+ onInsert === null || onInsert === void 0 || onInsert(node, insertedChildrenStartIndex + relativeIndex);
5533
+ });
5534
+ }
5535
+ var matchingChildIndex = childrenHelper.pointerIndex - 1;
5536
+ // Make sure the chunk tree contains the most recent version of the Slate
5537
+ // node
5538
+ if (treeLeaf.node !== matchingChild) {
5539
+ treeLeaf.node = matchingChild;
5540
+ chunkTreeHelper.invalidateChunk();
5541
+ onUpdate === null || onUpdate === void 0 || onUpdate(matchingChild, matchingChildIndex);
5542
+ }
5543
+ // Update the index if it has changed
5544
+ if (treeLeaf.index !== matchingChildIndex) {
5545
+ treeLeaf.index = matchingChildIndex;
5546
+ onIndexChange === null || onIndexChange === void 0 || onIndexChange(matchingChild, matchingChildIndex);
5547
+ }
5548
+ // Manually invalidate chunks containing specific children that we want to
5549
+ // re-render
5550
+ if (rerenderChildren.includes(matchingChildIndex)) {
5551
+ chunkTreeHelper.invalidateChunk();
5552
+ }
5553
+ };
5554
+ while (treeLeaf = chunkTreeHelper.readLeaf()) {
5555
+ if (_loop()) continue;
5556
+ }
5557
+ // If there are still Slate nodes remaining from the children array that were
5558
+ // not matched to nodes in the tree, insert them at the end of the tree
5559
+ if (!childrenHelper.reachedEnd) {
5560
+ var remainingChildren = childrenHelper.remaining();
5561
+ var leavesToInsert = childrenHelper.toChunkLeaves(remainingChildren, childrenHelper.pointerIndex);
5562
+ // Move the pointer back to the final leaf in the tree, or the start of the
5563
+ // tree if the tree is currently empty
5564
+ chunkTreeHelper.returnToPreviousLeaf();
5565
+ chunkTreeHelper.insertAfter(leavesToInsert);
5566
+ remainingChildren.forEach(function (node, relativeIndex) {
5567
+ onInsert === null || onInsert === void 0 || onInsert(node, childrenHelper.pointerIndex + relativeIndex);
5568
+ });
5569
+ }
5570
+ chunkTree.movedNodeKeys.clear();
5571
+ };
5572
+
5573
+ function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
5574
+ function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5575
+ var KEY_TO_CHUNK_TREE = new WeakMap();
4626
5576
  /**
4627
- * Get the current `decorate` prop of the editable.
5577
+ * Get or create the chunk tree for a Slate node
5578
+ *
5579
+ * If the reconcile option is provided, the chunk tree will be updated to
5580
+ * match the current children of the node. The children are chunked
5581
+ * automatically using the given chunk size.
4628
5582
  */
4629
- var useDecorate = function useDecorate() {
4630
- return React.useContext(DecorateContext);
5583
+ var getChunkTreeForNode = function getChunkTreeForNode(editor, node) {
5584
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5585
+ var key = ReactEditor.findKey(editor, node);
5586
+ var chunkTree = KEY_TO_CHUNK_TREE.get(key);
5587
+ if (!chunkTree) {
5588
+ chunkTree = {
5589
+ type: 'root',
5590
+ movedNodeKeys: new Set(),
5591
+ modifiedChunks: new Set(),
5592
+ children: []
5593
+ };
5594
+ KEY_TO_CHUNK_TREE.set(key, chunkTree);
5595
+ }
5596
+ if (options.reconcile) {
5597
+ reconcileChildren(editor, _objectSpread$1({
5598
+ chunkTree: chunkTree,
5599
+ children: node.children
5600
+ }, options.reconcile));
5601
+ }
5602
+ return chunkTree;
5603
+ };
5604
+
5605
+ var defaultRenderChunk = function defaultRenderChunk(_ref) {
5606
+ var children = _ref.children;
5607
+ return children;
5608
+ };
5609
+ var ChunkAncestor = function ChunkAncestor(props) {
5610
+ var root = props.root,
5611
+ ancestor = props.ancestor,
5612
+ renderElement = props.renderElement,
5613
+ _props$renderChunk = props.renderChunk,
5614
+ renderChunk = _props$renderChunk === void 0 ? defaultRenderChunk : _props$renderChunk;
5615
+ return ancestor.children.map(function (chunkNode) {
5616
+ if (chunkNode.type === 'chunk') {
5617
+ var key = chunkNode.key.id;
5618
+ var renderedChunk = renderChunk({
5619
+ highest: ancestor === root,
5620
+ lowest: chunkNode.children.some(function (c) {
5621
+ return c.type === 'leaf';
5622
+ }),
5623
+ attributes: {
5624
+ 'data-slate-chunk': true
5625
+ },
5626
+ children: /*#__PURE__*/React.createElement(MemoizedChunk, {
5627
+ root: root,
5628
+ ancestor: chunkNode,
5629
+ renderElement: renderElement,
5630
+ renderChunk: renderChunk
5631
+ })
5632
+ });
5633
+ return /*#__PURE__*/React.createElement(React.Fragment, {
5634
+ key: key
5635
+ }, renderedChunk);
5636
+ }
5637
+ // Only blocks containing no inlines are chunked
5638
+ var element = chunkNode.node;
5639
+ return renderElement(element, chunkNode.index, chunkNode.key);
5640
+ });
4631
5641
  };
5642
+ var ChunkTree = ChunkAncestor;
5643
+ var MemoizedChunk = /*#__PURE__*/React.memo(ChunkAncestor, function (prev, next) {
5644
+ return prev.root === next.root && prev.renderElement === next.renderElement && prev.renderChunk === next.renderChunk && !next.root.modifiedChunks.has(next.ancestor);
5645
+ });
4632
5646
 
5647
+ var ElementContext = /*#__PURE__*/React.createContext(null);
4633
5648
  /**
4634
- * A React context for sharing the `selected` state of an element.
5649
+ * Get the current element.
4635
5650
  */
4636
- var SelectedContext = /*#__PURE__*/React.createContext(false);
5651
+ var useElement = function useElement() {
5652
+ var context = React.useContext(ElementContext);
5653
+ if (!context) {
5654
+ throw new Error('The `useElement` hook must be used inside `renderElement`.');
5655
+ }
5656
+ return context;
5657
+ };
4637
5658
  /**
4638
- * Get the current `selected` state of an element.
5659
+ * Get the current element, or return null if not inside `renderElement`.
4639
5660
  */
4640
- var useSelected = function useSelected() {
4641
- return React.useContext(SelectedContext);
5661
+ var useElementIf = function useElementIf() {
5662
+ return React.useContext(ElementContext);
4642
5663
  };
4643
5664
 
4644
- function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
4645
- function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
4646
- function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
4647
5665
  /**
4648
5666
  * Children.
4649
5667
  */
@@ -4651,68 +5669,113 @@
4651
5669
  var decorations = props.decorations,
4652
5670
  node = props.node,
4653
5671
  renderElement = props.renderElement,
5672
+ renderChunk = props.renderChunk,
4654
5673
  renderPlaceholder = props.renderPlaceholder,
4655
5674
  renderText = props.renderText,
4656
- renderLeaf = props.renderLeaf,
4657
- selection = props.selection;
4658
- var decorate = useDecorate();
5675
+ renderLeaf = props.renderLeaf;
4659
5676
  var editor = useSlateStatic();
4660
5677
  IS_NODE_MAP_DIRTY.set(editor, false);
4661
- var path = ReactEditor.findPath(editor, node);
4662
- var children = [];
4663
- var isLeafBlock = slate.Element.isElement(node) && !editor.isInline(node) && slate.Editor.hasInlines(editor, node);
4664
- for (var i = 0; i < node.children.length; i++) {
4665
- var p = path.concat(i);
4666
- var n = node.children[i];
5678
+ var isEditor = slate.Editor.isEditor(node);
5679
+ var isBlock = !isEditor && slate.Element.isElement(node) && !editor.isInline(node);
5680
+ var isLeafBlock = isBlock && slate.Editor.hasInlines(editor, node);
5681
+ var chunkSize = isLeafBlock ? null : editor.getChunkSize(node);
5682
+ var chunking = !!chunkSize;
5683
+ var _useDecorationsByChil = useDecorationsByChild(editor, node, decorations),
5684
+ decorationsByChild = _useDecorationsByChil.decorationsByChild,
5685
+ childrenToRedecorate = _useDecorationsByChil.childrenToRedecorate;
5686
+ // Update the index and parent of each child.
5687
+ // PERF: If chunking is enabled, this is done while traversing the chunk tree
5688
+ // instead to eliminate unnecessary weak map operations.
5689
+ if (!chunking) {
5690
+ node.children.forEach(function (n, i) {
5691
+ NODE_TO_INDEX.set(n, i);
5692
+ NODE_TO_PARENT.set(n, node);
5693
+ });
5694
+ }
5695
+ var renderElementComponent = React.useCallback(function (n, i, cachedKey) {
5696
+ var key = cachedKey !== null && cachedKey !== void 0 ? cachedKey : ReactEditor.findKey(editor, n);
5697
+ return /*#__PURE__*/React.createElement(ElementContext.Provider, {
5698
+ key: "provider-".concat(key.id),
5699
+ value: n
5700
+ }, /*#__PURE__*/React.createElement(MemoizedElement, {
5701
+ decorations: decorationsByChild[i],
5702
+ element: n,
5703
+ key: key.id,
5704
+ renderElement: renderElement,
5705
+ renderChunk: renderChunk,
5706
+ renderPlaceholder: renderPlaceholder,
5707
+ renderLeaf: renderLeaf,
5708
+ renderText: renderText
5709
+ }));
5710
+ }, [editor, decorationsByChild, renderElement, renderChunk, renderPlaceholder, renderLeaf, renderText]);
5711
+ var renderTextComponent = function renderTextComponent(n, i) {
4667
5712
  var key = ReactEditor.findKey(editor, n);
4668
- var range = slate.Editor.range(editor, p);
4669
- var sel = selection && slate.Range.intersection(range, selection);
4670
- var ds = decorate([n, p]);
4671
- var _iterator = _createForOfIteratorHelper$1(decorations),
4672
- _step;
4673
- try {
4674
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
4675
- var dec = _step.value;
4676
- var d = slate.Range.intersection(dec, range);
4677
- if (d) {
4678
- ds.push(d);
4679
- }
5713
+ return /*#__PURE__*/React.createElement(MemoizedText, {
5714
+ decorations: decorationsByChild[i],
5715
+ key: key.id,
5716
+ isLast: i === node.children.length - 1,
5717
+ parent: node,
5718
+ renderPlaceholder: renderPlaceholder,
5719
+ renderLeaf: renderLeaf,
5720
+ renderText: renderText,
5721
+ text: n
5722
+ });
5723
+ };
5724
+ if (!chunking) {
5725
+ return node.children.map(function (n, i) {
5726
+ return slate.Text.isText(n) ? renderTextComponent(n, i) : renderElementComponent(n, i);
5727
+ });
5728
+ }
5729
+ var chunkTree = getChunkTreeForNode(editor, node, {
5730
+ reconcile: {
5731
+ chunkSize: chunkSize,
5732
+ rerenderChildren: childrenToRedecorate,
5733
+ onInsert: function onInsert(n, i) {
5734
+ NODE_TO_INDEX.set(n, i);
5735
+ NODE_TO_PARENT.set(n, node);
5736
+ },
5737
+ onUpdate: function onUpdate(n, i) {
5738
+ NODE_TO_INDEX.set(n, i);
5739
+ NODE_TO_PARENT.set(n, node);
5740
+ },
5741
+ onIndexChange: function onIndexChange(n, i) {
5742
+ NODE_TO_INDEX.set(n, i);
4680
5743
  }
4681
- } catch (err) {
4682
- _iterator.e(err);
4683
- } finally {
4684
- _iterator.f();
4685
- }
4686
- if (slate.Element.isElement(n)) {
4687
- children.push( /*#__PURE__*/React.createElement(SelectedContext.Provider, {
4688
- key: "provider-".concat(key.id),
4689
- value: !!sel
4690
- }, /*#__PURE__*/React.createElement(MemoizedElement, {
4691
- decorations: ds,
4692
- element: n,
4693
- key: key.id,
4694
- renderElement: renderElement,
4695
- renderPlaceholder: renderPlaceholder,
4696
- renderLeaf: renderLeaf,
4697
- renderText: renderText,
4698
- selection: sel
4699
- })));
4700
- } else {
4701
- children.push( /*#__PURE__*/React.createElement(MemoizedText, {
4702
- decorations: ds,
4703
- key: key.id,
4704
- isLast: isLeafBlock && i === node.children.length - 1,
4705
- parent: node,
4706
- renderPlaceholder: renderPlaceholder,
4707
- renderLeaf: renderLeaf,
4708
- renderText: renderText,
4709
- text: n
4710
- }));
4711
5744
  }
4712
- NODE_TO_INDEX.set(n, i);
4713
- NODE_TO_PARENT.set(n, node);
5745
+ });
5746
+ return /*#__PURE__*/React.createElement(ChunkTree, {
5747
+ root: chunkTree,
5748
+ ancestor: chunkTree,
5749
+ renderElement: renderElementComponent,
5750
+ renderChunk: renderChunk
5751
+ });
5752
+ };
5753
+ var useDecorationsByChild = function useDecorationsByChild(editor, node, decorations) {
5754
+ var decorationsByChild = splitDecorationsByChild(editor, node, decorations);
5755
+ // The value we return is a mutable array of `DecoratedRange[]` arrays. This
5756
+ // lets us avoid passing an immutable array of decorations for each child into
5757
+ // `ChunkTree` using props. Each `DecoratedRange[]` is only updated if the
5758
+ // decorations at that index have changed, which speeds up the equality check
5759
+ // for the `decorations` prop in the memoized `Element` and `Text` components.
5760
+ var mutableDecorationsByChild = React.useRef(decorationsByChild).current;
5761
+ // Track the list of child indices whose decorations have changed, so that we
5762
+ // can tell the chunk tree to re-render these children.
5763
+ var childrenToRedecorate = [];
5764
+ // Resize the mutable array to match the latest result
5765
+ mutableDecorationsByChild.length = decorationsByChild.length;
5766
+ for (var i = 0; i < decorationsByChild.length; i++) {
5767
+ var _mutableDecorationsBy;
5768
+ var _decorations = decorationsByChild[i];
5769
+ var previousDecorations = (_mutableDecorationsBy = mutableDecorationsByChild[i]) !== null && _mutableDecorationsBy !== void 0 ? _mutableDecorationsBy : null;
5770
+ if (!isElementDecorationsEqual(previousDecorations, _decorations)) {
5771
+ mutableDecorationsByChild[i] = _decorations;
5772
+ childrenToRedecorate.push(i);
5773
+ }
4714
5774
  }
4715
- return children;
5775
+ return {
5776
+ decorationsByChild: mutableDecorationsByChild,
5777
+ childrenToRedecorate: childrenToRedecorate
5778
+ };
4716
5779
  };
4717
5780
 
4718
5781
  /**
@@ -4726,24 +5789,153 @@
4726
5789
  return React.useContext(ReadOnlyContext);
4727
5790
  };
4728
5791
 
4729
- var SlateContext = /*#__PURE__*/React.createContext(null);
4730
5792
  /**
4731
- * Get the current editor object from the React context.
5793
+ * A React context for sharing the editor selector context in a way to control
5794
+ * re-renders.
4732
5795
  */
4733
- var useSlate = function useSlate() {
4734
- var context = React.useContext(SlateContext);
5796
+ var SlateSelectorContext = /*#__PURE__*/React.createContext({});
5797
+ var refEquality = function refEquality(a, b) {
5798
+ return a === b;
5799
+ };
5800
+ /**
5801
+ * Use redux style selectors to prevent re-rendering on every keystroke.
5802
+ *
5803
+ * Bear in mind re-rendering can only prevented if the returned value is a value
5804
+ * type or for reference types (e.g. objects and arrays) add a custom equality
5805
+ * function.
5806
+ *
5807
+ * If `selector` is memoized using `useCallback`, then it will only be called
5808
+ * when it or the editor state changes. Otherwise, `selector` will be called
5809
+ * every time the component renders.
5810
+ *
5811
+ * @example
5812
+ * const isSelectionActive = useSlateSelector(editor => Boolean(editor.selection))
5813
+ */
5814
+ function useSlateSelector(selector) {
5815
+ var equalityFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : refEquality;
5816
+ var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
5817
+ deferred = _ref.deferred;
5818
+ var context = React.useContext(SlateSelectorContext);
4735
5819
  if (!context) {
5820
+ throw new Error("The `useSlateSelector` hook must be used inside the <Slate> component's context.");
5821
+ }
5822
+ var addEventListener = context.addEventListener;
5823
+ var editor = useSlateStatic();
5824
+ var genericSelector = React.useCallback(function () {
5825
+ return selector(editor);
5826
+ }, [editor, selector]);
5827
+ var _useGenericSelector = useGenericSelector(genericSelector, equalityFn),
5828
+ _useGenericSelector2 = _slicedToArray(_useGenericSelector, 2),
5829
+ selectedState = _useGenericSelector2[0],
5830
+ update = _useGenericSelector2[1];
5831
+ useIsomorphicLayoutEffect(function () {
5832
+ var unsubscribe = addEventListener(update, {
5833
+ deferred: deferred
5834
+ });
5835
+ update();
5836
+ return unsubscribe;
5837
+ }, [addEventListener, update, deferred]);
5838
+ return selectedState;
5839
+ }
5840
+ /**
5841
+ * Create selector context with editor updating on every editor change
5842
+ */
5843
+ function useSelectorContext() {
5844
+ var eventListeners = React.useRef(new Set());
5845
+ var deferredEventListeners = React.useRef(new Set());
5846
+ var onChange = React.useCallback(function () {
5847
+ eventListeners.current.forEach(function (listener) {
5848
+ return listener();
5849
+ });
5850
+ }, []);
5851
+ var flushDeferred = React.useCallback(function () {
5852
+ deferredEventListeners.current.forEach(function (listener) {
5853
+ return listener();
5854
+ });
5855
+ deferredEventListeners.current.clear();
5856
+ }, []);
5857
+ var addEventListener = React.useCallback(function (callbackProp) {
5858
+ var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
5859
+ _ref2$deferred = _ref2.deferred,
5860
+ deferred = _ref2$deferred === void 0 ? false : _ref2$deferred;
5861
+ var callback = deferred ? function () {
5862
+ return deferredEventListeners.current.add(callbackProp);
5863
+ } : callbackProp;
5864
+ eventListeners.current.add(callback);
5865
+ return function () {
5866
+ eventListeners.current["delete"](callback);
5867
+ };
5868
+ }, []);
5869
+ var selectorContext = React.useMemo(function () {
5870
+ return {
5871
+ addEventListener: addEventListener,
5872
+ flushDeferred: flushDeferred
5873
+ };
5874
+ }, [addEventListener, flushDeferred]);
5875
+ return {
5876
+ selectorContext: selectorContext,
5877
+ onChange: onChange
5878
+ };
5879
+ }
5880
+ function useFlushDeferredSelectorsOnRender() {
5881
+ var _useContext = React.useContext(SlateSelectorContext),
5882
+ flushDeferred = _useContext.flushDeferred;
5883
+ useIsomorphicLayoutEffect(flushDeferred);
5884
+ }
5885
+
5886
+ /**
5887
+ * Get the current editor object and re-render whenever it changes.
5888
+ */
5889
+ var useSlate = function useSlate() {
5890
+ var _useContext = React.useContext(SlateSelectorContext),
5891
+ addEventListener = _useContext.addEventListener;
5892
+ var _useReducer = React.useReducer(function (s) {
5893
+ return s + 1;
5894
+ }, 0),
5895
+ _useReducer2 = _slicedToArray(_useReducer, 2),
5896
+ forceRender = _useReducer2[1];
5897
+ if (!addEventListener) {
4736
5898
  throw new Error("The `useSlate` hook must be used inside the <Slate> component's context.");
4737
5899
  }
4738
- var editor = context.editor;
4739
- return editor;
5900
+ useIsomorphicLayoutEffect(function () {
5901
+ return addEventListener(forceRender);
5902
+ }, [addEventListener]);
5903
+ return useSlateStatic();
5904
+ };
5905
+ var EDITOR_TO_V = new WeakMap();
5906
+ var getEditorVersionRef = function getEditorVersionRef(editor) {
5907
+ var v = EDITOR_TO_V.get(editor);
5908
+ if (v) {
5909
+ return v;
5910
+ }
5911
+ v = {
5912
+ current: 0
5913
+ };
5914
+ EDITOR_TO_V.set(editor, v);
5915
+ // Register the `onChange` handler exactly once per editor
5916
+ var onChange = editor.onChange;
5917
+ editor.onChange = function (options) {
5918
+ v.current++;
5919
+ onChange(options);
5920
+ };
5921
+ return v;
4740
5922
  };
5923
+ /**
5924
+ * Get the current editor object and its version, which increments on every
5925
+ * change.
5926
+ *
5927
+ * @deprecated The `v` counter is no longer used except for this hook, and may
5928
+ * be removed in a future version.
5929
+ */
4741
5930
  var useSlateWithV = function useSlateWithV() {
4742
- var context = React.useContext(SlateContext);
4743
- if (!context) {
4744
- throw new Error("The `useSlate` hook must be used inside the <Slate> component's context.");
4745
- }
4746
- return context;
5931
+ var editor = useSlate();
5932
+ var vRef = React.useMemo(function () {
5933
+ return getEditorVersionRef(editor);
5934
+ }, [editor]);
5935
+ return {
5936
+ editor: editor,
5937
+ v: vRef.current
5938
+ };
4747
5939
  };
4748
5940
 
4749
5941
  function useTrackUserInput() {
@@ -4772,40 +5964,6 @@
4772
5964
  };
4773
5965
  }
4774
5966
 
4775
- var classCallCheck = createCommonjsModule(function (module) {
4776
- function _classCallCheck(instance, Constructor) {
4777
- if (!(instance instanceof Constructor)) {
4778
- throw new TypeError("Cannot call a class as a function");
4779
- }
4780
- }
4781
- module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
4782
- });
4783
-
4784
- var _classCallCheck = unwrapExports(classCallCheck);
4785
-
4786
- var createClass = createCommonjsModule(function (module) {
4787
- function _defineProperties(target, props) {
4788
- for (var i = 0; i < props.length; i++) {
4789
- var descriptor = props[i];
4790
- descriptor.enumerable = descriptor.enumerable || false;
4791
- descriptor.configurable = true;
4792
- if ("value" in descriptor) descriptor.writable = true;
4793
- Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
4794
- }
4795
- }
4796
- function _createClass(Constructor, protoProps, staticProps) {
4797
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
4798
- if (staticProps) _defineProperties(Constructor, staticProps);
4799
- Object.defineProperty(Constructor, "prototype", {
4800
- writable: false
4801
- });
4802
- return Constructor;
4803
- }
4804
- module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
4805
- });
4806
-
4807
- var _createClass = unwrapExports(createClass);
4808
-
4809
5967
  var assertThisInitialized = createCommonjsModule(function (module) {
4810
5968
  function _assertThisInitialized(self) {
4811
5969
  if (self === void 0) {
@@ -4881,42 +6039,6 @@
4881
6039
 
4882
6040
  var _getPrototypeOf = unwrapExports(getPrototypeOf);
4883
6041
 
4884
- var arrayWithoutHoles = createCommonjsModule(function (module) {
4885
- function _arrayWithoutHoles(arr) {
4886
- if (Array.isArray(arr)) return arrayLikeToArray(arr);
4887
- }
4888
- module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
4889
- });
4890
-
4891
- unwrapExports(arrayWithoutHoles);
4892
-
4893
- var iterableToArray = createCommonjsModule(function (module) {
4894
- function _iterableToArray(iter) {
4895
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
4896
- }
4897
- module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
4898
- });
4899
-
4900
- unwrapExports(iterableToArray);
4901
-
4902
- var nonIterableSpread = createCommonjsModule(function (module) {
4903
- function _nonIterableSpread() {
4904
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
4905
- }
4906
- module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
4907
- });
4908
-
4909
- unwrapExports(nonIterableSpread);
4910
-
4911
- var toConsumableArray = createCommonjsModule(function (module) {
4912
- function _toConsumableArray(arr) {
4913
- return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
4914
- }
4915
- module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
4916
- });
4917
-
4918
- var _toConsumableArray = unwrapExports(toConsumableArray);
4919
-
4920
6042
  var createRestoreDomManager = function createRestoreDomManager(editor, receivedUserInput) {
4921
6043
  var bufferedMutations = [];
4922
6044
  var clear = function clear() {
@@ -5053,7 +6175,7 @@
5053
6175
  return React.useContext(ComposingContext);
5054
6176
  };
5055
6177
 
5056
- var _excluded$1 = ["autoFocus", "decorate", "onDOMBeforeInput", "placeholder", "readOnly", "renderElement", "renderLeaf", "renderText", "renderPlaceholder", "scrollSelectionIntoView", "style", "as", "disableDefaultStyles"],
6178
+ var _excluded$1 = ["autoFocus", "decorate", "onDOMBeforeInput", "placeholder", "readOnly", "renderElement", "renderChunk", "renderLeaf", "renderText", "renderPlaceholder", "scrollSelectionIntoView", "style", "as", "disableDefaultStyles"],
5057
6179
  _excluded2 = ["text"];
5058
6180
  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
5059
6181
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
@@ -5078,6 +6200,7 @@
5078
6200
  _props$readOnly = props.readOnly,
5079
6201
  readOnly = _props$readOnly === void 0 ? false : _props$readOnly,
5080
6202
  renderElement = props.renderElement,
6203
+ renderChunk = props.renderChunk,
5081
6204
  renderLeaf = props.renderLeaf,
5082
6205
  renderText = props.renderText,
5083
6206
  _props$renderPlacehol = props.renderPlaceholder,
@@ -5126,6 +6249,11 @@
5126
6249
  }, []);
5127
6250
  // The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
5128
6251
  // needs to be manually focused.
6252
+ //
6253
+ // If this stops working in Firefox, make sure nothing is causing this
6254
+ // component to re-render during the initial mount. If the DOM selection is
6255
+ // set by `useIsomorphicLayoutEffect` before `onDOMSelectionChange` updates
6256
+ // `editor.selection`, the DOM selection can be removed accidentally.
5129
6257
  React.useEffect(function () {
5130
6258
  if (ref.current && autoFocus) {
5131
6259
  ref.current.focus();
@@ -5677,6 +6805,7 @@
5677
6805
  };
5678
6806
  }, [scheduleOnDOMSelectionChange, state]);
5679
6807
  var decorations = decorate([editor, []]);
6808
+ var decorateContext = useDecorateContext(decorate);
5680
6809
  var showPlaceholder = placeholder && editor.children.length === 1 && Array.from(slate.Node.texts(editor)).length === 1 && slate.Node.string(editor) === '' && !isComposing;
5681
6810
  var placeHolderResizeHandler = React.useCallback(function (placeholderEl) {
5682
6811
  if (placeholderEl && showPlaceholder) {
@@ -5733,12 +6862,13 @@
5733
6862
  EDITOR_TO_PENDING_INSERTION_MARKS["delete"](editor);
5734
6863
  });
5735
6864
  });
6865
+ useFlushDeferredSelectorsOnRender();
5736
6866
  return /*#__PURE__*/React.createElement(ReadOnlyContext.Provider, {
5737
6867
  value: readOnly
5738
6868
  }, /*#__PURE__*/React.createElement(ComposingContext.Provider, {
5739
6869
  value: isComposing
5740
6870
  }, /*#__PURE__*/React.createElement(DecorateContext.Provider, {
5741
- value: decorate
6871
+ value: decorateContext
5742
6872
  }, /*#__PURE__*/React.createElement(RestoreDOM, {
5743
6873
  node: ref,
5744
6874
  receivedUserInput: receivedUserInput
@@ -6324,10 +7454,10 @@
6324
7454
  decorations: decorations,
6325
7455
  node: editor,
6326
7456
  renderElement: renderElement,
7457
+ renderChunk: renderChunk,
6327
7458
  renderPlaceholder: renderPlaceholder,
6328
7459
  renderLeaf: renderLeaf,
6329
- renderText: renderText,
6330
- selection: editor.selection
7460
+ renderText: renderText
6331
7461
  }))))));
6332
7462
  });
6333
7463
  /**
@@ -6424,130 +7554,6 @@
6424
7554
  return React.useContext(FocusedContext);
6425
7555
  };
6426
7556
 
6427
- function isError(error) {
6428
- return error instanceof Error;
6429
- }
6430
- /**
6431
- * A React context for sharing the editor selector context in a way to control rerenders
6432
- */
6433
- var SlateSelectorContext = /*#__PURE__*/React.createContext({});
6434
- var refEquality = function refEquality(a, b) {
6435
- return a === b;
6436
- };
6437
- /**
6438
- * use redux style selectors to prevent rerendering on every keystroke.
6439
- * Bear in mind rerendering can only prevented if the returned value is a value type or for reference types (e.g. objects and arrays) add a custom equality function.
6440
- *
6441
- * Example:
6442
- * ```
6443
- * const isSelectionActive = useSlateSelector(editor => Boolean(editor.selection));
6444
- * ```
6445
- */
6446
- function useSlateSelector(selector) {
6447
- var equalityFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : refEquality;
6448
- var _useReducer = React.useReducer(function (s) {
6449
- return s + 1;
6450
- }, 0),
6451
- _useReducer2 = _slicedToArray(_useReducer, 2),
6452
- forceRender = _useReducer2[1];
6453
- var context = React.useContext(SlateSelectorContext);
6454
- if (!context) {
6455
- throw new Error("The `useSlateSelector` hook must be used inside the <Slate> component's context.");
6456
- }
6457
- var getSlate = context.getSlate,
6458
- addEventListener = context.addEventListener;
6459
- var latestSubscriptionCallbackError = React.useRef();
6460
- var latestSelector = React.useRef(function () {
6461
- return null;
6462
- });
6463
- var latestSelectedState = React.useRef(null);
6464
- var selectedState;
6465
- try {
6466
- if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) {
6467
- var selectorResult = selector(getSlate());
6468
- if (equalityFn(latestSelectedState.current, selectorResult)) {
6469
- selectedState = latestSelectedState.current;
6470
- } else {
6471
- selectedState = selectorResult;
6472
- }
6473
- } else {
6474
- selectedState = latestSelectedState.current;
6475
- }
6476
- } catch (err) {
6477
- if (latestSubscriptionCallbackError.current && isError(err)) {
6478
- err.message += "\nThe error may be correlated with this previous error:\n".concat(latestSubscriptionCallbackError.current.stack, "\n\n");
6479
- }
6480
- throw err;
6481
- }
6482
- useIsomorphicLayoutEffect(function () {
6483
- latestSelector.current = selector;
6484
- latestSelectedState.current = selectedState;
6485
- latestSubscriptionCallbackError.current = undefined;
6486
- });
6487
- useIsomorphicLayoutEffect(function () {
6488
- function checkForUpdates() {
6489
- try {
6490
- var newSelectedState = latestSelector.current(getSlate());
6491
- if (equalityFn(newSelectedState, latestSelectedState.current)) {
6492
- return;
6493
- }
6494
- latestSelectedState.current = newSelectedState;
6495
- } catch (err) {
6496
- // we ignore all errors here, since when the component
6497
- // is re-rendered, the selectors are called again, and
6498
- // will throw again, if neither props nor store state
6499
- // changed
6500
- if (err instanceof Error) {
6501
- latestSubscriptionCallbackError.current = err;
6502
- } else {
6503
- latestSubscriptionCallbackError.current = new Error(String(err));
6504
- }
6505
- }
6506
- forceRender();
6507
- }
6508
- var unsubscribe = addEventListener(checkForUpdates);
6509
- checkForUpdates();
6510
- return function () {
6511
- return unsubscribe();
6512
- };
6513
- },
6514
- // don't rerender on equalityFn change since we want to be able to define it inline
6515
- [addEventListener, getSlate]);
6516
- return selectedState;
6517
- }
6518
- /**
6519
- * Create selector context with editor updating on every editor change
6520
- */
6521
- function useSelectorContext(editor) {
6522
- var eventListeners = React.useRef([]).current;
6523
- var slateRef = React.useRef({
6524
- editor: editor
6525
- }).current;
6526
- var onChange = React.useCallback(function (editor) {
6527
- slateRef.editor = editor;
6528
- eventListeners.forEach(function (listener) {
6529
- return listener(editor);
6530
- });
6531
- }, [eventListeners, slateRef]);
6532
- var selectorContext = React.useMemo(function () {
6533
- return {
6534
- getSlate: function getSlate() {
6535
- return slateRef.editor;
6536
- },
6537
- addEventListener: function addEventListener(callback) {
6538
- eventListeners.push(callback);
6539
- return function () {
6540
- eventListeners.splice(eventListeners.indexOf(callback), 1);
6541
- };
6542
- }
6543
- };
6544
- }, [eventListeners, slateRef]);
6545
- return {
6546
- selectorContext: selectorContext,
6547
- onChange: onChange
6548
- };
6549
- }
6550
-
6551
7557
  var REACT_MAJOR_VERSION = parseInt(React.version.split('.')[0], 10);
6552
7558
 
6553
7559
  var _excluded = ["editor", "children", "onChange", "onSelectionChange", "onValueChange", "initialValue"];
@@ -6563,24 +7569,18 @@
6563
7569
  onValueChange = props.onValueChange,
6564
7570
  initialValue = props.initialValue,
6565
7571
  rest = _objectWithoutProperties$1(props, _excluded);
6566
- var _React$useState = React.useState(function () {
6567
- if (!slate.Node.isNodeList(initialValue)) {
6568
- throw new Error("[Slate] initialValue is invalid! Expected a list of elements but got: ".concat(slate.Scrubber.stringify(initialValue)));
6569
- }
6570
- if (!slate.Editor.isEditor(editor)) {
6571
- throw new Error("[Slate] editor is invalid! You passed: ".concat(slate.Scrubber.stringify(editor)));
6572
- }
6573
- editor.children = initialValue;
6574
- Object.assign(editor, rest);
6575
- return {
6576
- v: 0,
6577
- editor: editor
6578
- };
6579
- }),
6580
- _React$useState2 = _slicedToArray(_React$useState, 2),
6581
- context = _React$useState2[0],
6582
- setContext = _React$useState2[1];
6583
- var _useSelectorContext = useSelectorContext(editor),
7572
+ // Run once on first mount, but before `useEffect` or render
7573
+ React.useState(function () {
7574
+ if (!slate.Node.isNodeList(initialValue)) {
7575
+ throw new Error("[Slate] initialValue is invalid! Expected a list of elements but got: ".concat(slate.Scrubber.stringify(initialValue)));
7576
+ }
7577
+ if (!slate.Editor.isEditor(editor)) {
7578
+ throw new Error("[Slate] editor is invalid! You passed: ".concat(slate.Scrubber.stringify(editor)));
7579
+ }
7580
+ editor.children = initialValue;
7581
+ Object.assign(editor, rest);
7582
+ });
7583
+ var _useSelectorContext = useSelectorContext(),
6584
7584
  selectorContext = _useSelectorContext.selectorContext,
6585
7585
  handleSelectorChange = _useSelectorContext.onChange;
6586
7586
  var onContextChange = React.useCallback(function (options) {
@@ -6595,13 +7595,7 @@
6595
7595
  default:
6596
7596
  onValueChange === null || onValueChange === void 0 || onValueChange(editor.children);
6597
7597
  }
6598
- setContext(function (prevContext) {
6599
- return {
6600
- v: prevContext.v + 1,
6601
- editor: editor
6602
- };
6603
- });
6604
- handleSelectorChange(editor);
7598
+ handleSelectorChange();
6605
7599
  }, [editor, handleSelectorChange, onChange, onSelectionChange, onValueChange]);
6606
7600
  React.useEffect(function () {
6607
7601
  EDITOR_TO_ON_CHANGE.set(editor, onContextChange);
@@ -6641,13 +7635,11 @@
6641
7635
  }, []);
6642
7636
  return /*#__PURE__*/React.createElement(SlateSelectorContext.Provider, {
6643
7637
  value: selectorContext
6644
- }, /*#__PURE__*/React.createElement(SlateContext.Provider, {
6645
- value: context
6646
7638
  }, /*#__PURE__*/React.createElement(EditorContext.Provider, {
6647
- value: context.editor
7639
+ value: editor
6648
7640
  }, /*#__PURE__*/React.createElement(FocusedContext.Provider, {
6649
7641
  value: isFocused
6650
- }, children))));
7642
+ }, children)));
6651
7643
  };
6652
7644
 
6653
7645
  /**
@@ -6662,6 +7654,31 @@
6662
7654
  return editor;
6663
7655
  };
6664
7656
 
7657
+ /**
7658
+ * Get the current `selected` state of an element.
7659
+ */
7660
+ var useSelected = function useSelected() {
7661
+ var element = useElementIf();
7662
+ // Breaking the rules of hooks is fine here since `!element` will remain true
7663
+ // or false for the entire lifetime of the component this hook is called from.
7664
+ // TODO: Decide if we want to throw an error instead when calling
7665
+ // `useSelected` outside of an element (potentially a breaking change).
7666
+ if (!element) return false;
7667
+ // eslint-disable-next-line react-hooks/rules-of-hooks
7668
+ var selector = React.useCallback(function (editor) {
7669
+ if (!editor.selection) return false;
7670
+ var path = ReactEditor.findPath(editor, element);
7671
+ var range = slate.Editor.range(editor, path);
7672
+ return !!slate.Range.intersection(range, editor.selection);
7673
+ }, [element]);
7674
+ // eslint-disable-next-line react-hooks/rules-of-hooks
7675
+ return useSlateSelector(selector, undefined, {
7676
+ // Defer the selector until after `Editable` has rendered so that the path
7677
+ // will be accurate.
7678
+ deferred: true
7679
+ });
7680
+ };
7681
+
6665
7682
  /**
6666
7683
  * Get the current slate selection.
6667
7684
  * Only triggers a rerender when the selection actually changes
@@ -37248,7 +38265,11 @@
37248
38265
  var e = editor;
37249
38266
  e = withDOM(e, clipboardFormatKey);
37250
38267
  var _e = e,
37251
- onChange = _e.onChange;
38268
+ onChange = _e.onChange,
38269
+ apply = _e.apply;
38270
+ e.getChunkSize = function () {
38271
+ return null;
38272
+ };
37252
38273
  e.onChange = function (options) {
37253
38274
  // COMPAT: React < 18 doesn't batch `setState` hook calls, which means
37254
38275
  // that the children and selection can get out of sync for one render
@@ -37262,6 +38283,22 @@
37262
38283
  onChange(options);
37263
38284
  });
37264
38285
  };
38286
+ // On move_node, if the chunking optimization is enabled for the parent of the
38287
+ // node being moved, add the moved node to the movedNodeKeys set of the
38288
+ // parent's chunk tree.
38289
+ e.apply = function (operation) {
38290
+ if (operation.type === 'move_node') {
38291
+ var parent = slate.Node.parent(e, operation.path);
38292
+ var chunking = !!e.getChunkSize(parent);
38293
+ if (chunking) {
38294
+ var node = slate.Node.get(e, operation.path);
38295
+ var chunkTree = getChunkTreeForNode(e, parent);
38296
+ var key = ReactEditor.findKey(e, node);
38297
+ chunkTree.movedNodeKeys.add(key);
38298
+ }
38299
+ }
38300
+ apply(operation);
38301
+ };
37265
38302
  return e;
37266
38303
  };
37267
38304
 
@@ -37276,6 +38313,8 @@
37276
38313
  exports.Slate = Slate;
37277
38314
  exports.useComposing = useComposing;
37278
38315
  exports.useEditor = useEditor;
38316
+ exports.useElement = useElement;
38317
+ exports.useElementIf = useElementIf;
37279
38318
  exports.useFocused = useFocused;
37280
38319
  exports.useReadOnly = useReadOnly;
37281
38320
  exports.useSelected = useSelected;