@portabletext/editor 1.18.7 → 1.20.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 (43) hide show
  1. package/lib/_chunks-cjs/behavior.core.cjs +52 -35
  2. package/lib/_chunks-cjs/behavior.core.cjs.map +1 -1
  3. package/lib/_chunks-cjs/selector.is-selection-collapsed.cjs.map +1 -1
  4. package/lib/_chunks-es/behavior.core.js +52 -35
  5. package/lib/_chunks-es/behavior.core.js.map +1 -1
  6. package/lib/_chunks-es/selector.is-selection-collapsed.js.map +1 -1
  7. package/lib/behaviors/index.cjs +1 -0
  8. package/lib/behaviors/index.cjs.map +1 -1
  9. package/lib/behaviors/index.d.cts +78 -86
  10. package/lib/behaviors/index.d.ts +78 -86
  11. package/lib/behaviors/index.js +3 -2
  12. package/lib/behaviors/index.js.map +1 -1
  13. package/lib/index.cjs +277 -422
  14. package/lib/index.cjs.map +1 -1
  15. package/lib/index.d.cts +488 -1127
  16. package/lib/index.d.ts +488 -1127
  17. package/lib/index.js +279 -425
  18. package/lib/index.js.map +1 -1
  19. package/lib/selectors/index.cjs +12 -9
  20. package/lib/selectors/index.cjs.map +1 -1
  21. package/lib/selectors/index.js +12 -9
  22. package/lib/selectors/index.js.map +1 -1
  23. package/package.json +5 -7
  24. package/src/behavior-actions/behavior.actions.ts +28 -36
  25. package/src/behaviors/behavior.core.decorators.ts +36 -42
  26. package/src/behaviors/behavior.core.ts +4 -3
  27. package/src/behaviors/behavior.types.ts +40 -26
  28. package/src/behaviors/index.ts +1 -0
  29. package/src/editor/PortableTextEditor.tsx +14 -16
  30. package/src/editor/__tests__/self-solving.test.tsx +4 -11
  31. package/src/editor/components/Element.tsx +17 -23
  32. package/src/editor/create-editor.ts +18 -3
  33. package/src/editor/editor-machine.ts +67 -45
  34. package/src/editor/nodes/DefaultObject.tsx +2 -2
  35. package/src/editor/plugins/create-with-event-listeners.ts +44 -57
  36. package/src/editor/plugins/createWithHotKeys.ts +1 -11
  37. package/src/editor/plugins/createWithPortableTextMarkModel.ts +12 -1
  38. package/src/editor/plugins/createWithPortableTextSelections.ts +1 -5
  39. package/src/editor/with-applying-behavior-actions.ts +15 -0
  40. package/src/selectors/selector.get-selected-spans.test.ts +122 -0
  41. package/src/selectors/selector.get-selected-spans.ts +3 -1
  42. package/src/selectors/selector.is-active-decorator.test.ts +65 -0
  43. package/src/editor/nodes/index.ts +0 -189
package/lib/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var schema = require("@sanity/schema"), types = require("@sanity/types"), startCase = require("lodash.startcase"), jsxRuntime = require("react/jsx-runtime"), react = require("@xstate/react"), isEqual = require("lodash/isEqual.js"), noop = require("lodash/noop.js"), React = require("react"), slate = require("slate"), slateReact = require("slate-react"), debug$l = require("debug"), reactCompilerRuntime = require("react-compiler-runtime"), styledComponents = require("styled-components"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), useEffectEvent = require("use-effect-event"), xstate = require("xstate"), patches = require("@portabletext/patches"), flatten = require("lodash/flatten.js"), isPlainObject = require("lodash/isPlainObject.js"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), selector_isSelectionCollapsed = require("./_chunks-cjs/selector.is-selection-collapsed.cjs"), behavior_core = require("./_chunks-cjs/behavior.core.cjs"), getRandomValues = require("get-random-values-esm"), blockTools = require("@sanity/block-tools");
3
+ var schema = require("@sanity/schema"), types = require("@sanity/types"), startCase = require("lodash.startcase"), jsxRuntime = require("react/jsx-runtime"), react = require("@xstate/react"), isEqual = require("lodash/isEqual.js"), noop = require("lodash/noop.js"), React = require("react"), slate = require("slate"), slateReact = require("slate-react"), debug$k = require("debug"), reactCompilerRuntime = require("react-compiler-runtime"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), useEffectEvent = require("use-effect-event"), xstate = require("xstate"), patches = require("@portabletext/patches"), flatten = require("lodash/flatten.js"), isPlainObject = require("lodash/isPlainObject.js"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), selector_isSelectionCollapsed = require("./_chunks-cjs/selector.is-selection-collapsed.cjs"), behavior_core = require("./_chunks-cjs/behavior.core.cjs"), getRandomValues = require("get-random-values-esm"), blockTools = require("@sanity/block-tools");
4
4
  function _interopDefaultCompat(e) {
5
5
  return e && typeof e == "object" && "default" in e ? e : { default: e };
6
6
  }
7
- var startCase__default = /* @__PURE__ */ _interopDefaultCompat(startCase), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop), React__default = /* @__PURE__ */ _interopDefaultCompat(React), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$l), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues);
7
+ var startCase__default = /* @__PURE__ */ _interopDefaultCompat(startCase), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop), React__default = /* @__PURE__ */ _interopDefaultCompat(React), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$k), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues);
8
8
  function createEditorSchema(portableTextType) {
9
9
  if (!portableTextType)
10
10
  throw new Error("Parameter 'portabletextType' missing (required)");
@@ -194,7 +194,7 @@ function toSlateRange(selection, editor) {
194
194
  path: toSlatePath(selection.focus.path, editor),
195
195
  offset: selection.focus.offset
196
196
  };
197
- return focus.path.length === 0 || anchor.path.length === 0 ? null : anchor && focus ? {
197
+ return focus.path.length === 0 || anchor.path.length === 0 ? null : focus ? {
198
198
  anchor,
199
199
  focus
200
200
  } : null;
@@ -357,172 +357,20 @@ function isEqualToEmptyEditor(children, schemaTypes) {
357
357
  const IS_PROCESSING_REMOTE_CHANGES = /* @__PURE__ */ new WeakMap(), IS_DRAGGING = /* @__PURE__ */ new WeakMap(), IS_DRAGGING_BLOCK_ELEMENT = /* @__PURE__ */ new WeakMap(), IS_DRAGGING_ELEMENT_TARGET = /* @__PURE__ */ new WeakMap(), IS_DRAGGING_BLOCK_TARGET_POSITION = /* @__PURE__ */ new WeakMap(), KEY_TO_SLATE_ELEMENT = /* @__PURE__ */ new WeakMap(), KEY_TO_VALUE_ELEMENT = /* @__PURE__ */ new WeakMap(), SLATE_TO_PORTABLE_TEXT_RANGE = /* @__PURE__ */ new WeakMap(), DefaultObject = (props) => {
358
358
  const $ = reactCompilerRuntime.c(4);
359
359
  let t0;
360
- $[0] !== props.value ? (t0 = JSON.stringify(props.value, null, 2), $[0] = props.value, $[1] = t0) : t0 = $[1];
360
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
361
+ userSelect: "none"
362
+ }, $[0] = t0) : t0 = $[0];
361
363
  let t1;
362
- return $[2] !== t0 ? (t1 = /* @__PURE__ */ jsxRuntime.jsx("div", { children: /* @__PURE__ */ jsxRuntime.jsx("pre", { children: t0 }) }), $[2] = t0, $[3] = t1) : t1 = $[3], t1;
364
+ return $[1] !== props.value._key || $[2] !== props.value._type ? (t1 = /* @__PURE__ */ jsxRuntime.jsxs("div", { style: t0, children: [
365
+ "[",
366
+ props.value._type,
367
+ ": ",
368
+ props.value._key,
369
+ "]"
370
+ ] }), $[1] = props.value._key, $[2] = props.value._type, $[3] = t1) : t1 = $[3], t1;
363
371
  };
364
372
  DefaultObject.displayName = "DefaultObject";
365
- const DefaultBlockObject = styledComponents.styled.div`
366
- user-select: none;
367
- border: ${(props) => props.selected ? "1px solid blue" : "1px solid transparent"};
368
- `;
369
- styledComponents.styled.span`
370
- background: #999;
371
- border: ${(props) => props.selected ? "1px solid blue" : "1px solid transparent"};
372
- `;
373
- const DefaultListItem = styledComponents.styled.div`
374
- &.pt-list-item {
375
- width: fit-content;
376
- position: relative;
377
- display: block;
378
-
379
- /* Important 'transform' in order to force refresh the ::before and ::after rules
380
- in Webkit: https://stackoverflow.com/a/21947628/831480
381
- */
382
- transform: translateZ(0);
383
- margin-left: ${(props) => getLeftPositionForListLevel(props.listLevel)};
384
- }
385
- &.pt-list-item > .pt-list-item-inner {
386
- display: flex;
387
- margin: 0;
388
- padding: 0;
389
- &:before {
390
- justify-content: flex-start;
391
- vertical-align: top;
392
- }
393
- }
394
- &.pt-list-item-bullet > .pt-list-item-inner:before {
395
- content: '${(props) => getContentForListLevelAndStyle(props.listLevel, props.listStyle)}';
396
- font-size: 0.4375rem; /* 7px */
397
- line-height: 1.5rem; /* Same as body text */
398
- /* Optical alignment */
399
- position: relative;
400
- }
401
- }
402
- &.pt-list-item-bullet > .pt-list-item-inner {
403
- &:before {
404
- min-width: 1.5rem; /* Make sure space between bullet and text never shrinks */
405
- }
406
- }
407
- &.pt-list-item-number {
408
- counter-increment: ${(props) => getCounterIncrementForListLevel(props.listLevel)};
409
- counter-reset: ${(props) => getCounterResetForListLevel(props.listLevel)};
410
- }
411
- & + :not(.pt-list-item-number) {
412
- counter-reset: listItemNumber;
413
- }
414
- &.pt-list-item-number > .pt-list-item-inner:before {
415
- content: ${(props) => getCounterContentForListLevel(props.listLevel)};
416
- min-width: 1.5rem; /* Make sure space between number and text never shrinks */
417
- /* Optical alignment */
418
- position: relative;
419
- top: 1px;
420
- }
421
- `, DefaultListItemInner = styledComponents.styled.div``;
422
- function getLeftPositionForListLevel(level) {
423
- switch (Number(level)) {
424
- case 1:
425
- return "1.5em";
426
- case 2:
427
- return "3em";
428
- case 3:
429
- return "4.5em";
430
- case 4:
431
- return "6em";
432
- case 5:
433
- return "7.5em";
434
- case 6:
435
- return "9em";
436
- case 7:
437
- return "10.5em";
438
- case 8:
439
- return "12em";
440
- case 9:
441
- return "13.5em";
442
- case 10:
443
- return "15em";
444
- default:
445
- return "0em";
446
- }
447
- }
448
- const bullets = ["\u25CF", "\u25CB", "\u25A0"];
449
- function getContentForListLevelAndStyle(level, style) {
450
- const normalizedLevel = (level - 1) % 3;
451
- return style === "bullet" ? bullets[normalizedLevel] : "*";
452
- }
453
- function getCounterIncrementForListLevel(level) {
454
- switch (level) {
455
- case 1:
456
- return "listItemNumber";
457
- case 2:
458
- return "listItemAlpha";
459
- case 3:
460
- return "listItemRoman";
461
- case 4:
462
- return "listItemNumberNext";
463
- case 5:
464
- return "listItemLetterNext";
465
- case 6:
466
- return "listItemRomanNext";
467
- case 7:
468
- return "listItemNumberNextNext";
469
- case 8:
470
- return "listItemAlphaNextNext";
471
- case 9:
472
- return "listItemRomanNextNext";
473
- default:
474
- return "listItemNumberNextNextNext";
475
- }
476
- }
477
- function getCounterResetForListLevel(level) {
478
- switch (level) {
479
- case 1:
480
- return "listItemAlpha";
481
- case 2:
482
- return "listItemRoman";
483
- case 3:
484
- return "listItemNumberNext";
485
- case 4:
486
- return "listItemLetterNext";
487
- case 5:
488
- return "listItemRomanNext";
489
- case 6:
490
- return "listItemNumberNextNext";
491
- case 7:
492
- return "listItemAlphaNextNext";
493
- case 8:
494
- return "listItemRomanNextNext";
495
- case 9:
496
- return "listItemNumberNextNextNext";
497
- default:
498
- return "listItemNumberNextNextNext";
499
- }
500
- }
501
- function getCounterContentForListLevel(level) {
502
- switch (level) {
503
- case 1:
504
- return "counter(listItemNumber) '. '";
505
- case 2:
506
- return "counter(listItemAlpha, lower-alpha) '. '";
507
- case 3:
508
- return "counter(listItemRoman, lower-roman) '. '";
509
- case 4:
510
- return "counter(listItemNumberNext) '. '";
511
- case 5:
512
- return "counter(listItemLetterNext, lower-alpha) '. '";
513
- case 6:
514
- return "counter(listItemRomanNext, lower-roman) '. '";
515
- case 7:
516
- return "counter(listItemNumberNextNext) '. '";
517
- case 8:
518
- return "counter(listItemAlphaNextNext, lower-alpha) '. '";
519
- case 9:
520
- return "counter(listItemRomanNextNext, lower-roman) '. '";
521
- default:
522
- return "counter(listItemNumberNextNextNext) '. '";
523
- }
524
- }
525
- const debug$k = debugWithName("components:DraggableBlock"), DraggableBlock = (t0) => {
373
+ const debug$j = debugWithName("components:DraggableBlock"), DraggableBlock = (t0) => {
526
374
  const $ = reactCompilerRuntime.c(51), {
527
375
  children,
528
376
  element,
@@ -560,39 +408,39 @@ const debug$k = debugWithName("components:DraggableBlock"), DraggableBlock = (t0
560
408
  $[16] !== editor || $[17] !== element ? (t9 = (event_0) => {
561
409
  const targetBlock = IS_DRAGGING_ELEMENT_TARGET.get(editor);
562
410
  if (targetBlock) {
563
- IS_DRAGGING.set(editor, !1), event_0.preventDefault(), event_0.stopPropagation(), IS_DRAGGING_ELEMENT_TARGET.delete(editor), dragGhostRef.current && (debug$k("Removing drag ghost"), document.body.removeChild(dragGhostRef.current));
411
+ IS_DRAGGING.set(editor, !1), event_0.preventDefault(), event_0.stopPropagation(), IS_DRAGGING_ELEMENT_TARGET.delete(editor), dragGhostRef.current && (debug$j("Removing drag ghost"), document.body.removeChild(dragGhostRef.current));
564
412
  const dragPosition = IS_DRAGGING_BLOCK_TARGET_POSITION.get(editor);
565
413
  IS_DRAGGING_BLOCK_TARGET_POSITION.delete(editor);
566
414
  let targetPath = slateReact.ReactEditor.findPath(editor, targetBlock);
567
415
  const myPath = slateReact.ReactEditor.findPath(editor, element), isBefore = slate.Path.isBefore(myPath, targetPath);
568
416
  if (dragPosition === "bottom" && !isBefore) {
569
417
  if (targetPath[0] >= editor.children.length - 1) {
570
- debug$k("target is already at the bottom, not moving");
418
+ debug$j("target is already at the bottom, not moving");
571
419
  return;
572
420
  }
573
421
  const originalPath = targetPath;
574
- targetPath = slate.Path.next(targetPath), debug$k(`Adjusting targetPath from ${JSON.stringify(originalPath)} to ${JSON.stringify(targetPath)}`);
422
+ targetPath = slate.Path.next(targetPath), debug$j(`Adjusting targetPath from ${JSON.stringify(originalPath)} to ${JSON.stringify(targetPath)}`);
575
423
  }
576
424
  if (dragPosition === "top" && isBefore && targetPath[0] !== editor.children.length - 1) {
577
425
  const originalPath_0 = targetPath;
578
- targetPath = slate.Path.previous(targetPath), debug$k(`Adjusting targetPath from ${JSON.stringify(originalPath_0)} to ${JSON.stringify(targetPath)}`);
426
+ targetPath = slate.Path.previous(targetPath), debug$j(`Adjusting targetPath from ${JSON.stringify(originalPath_0)} to ${JSON.stringify(targetPath)}`);
579
427
  }
580
428
  if (slate.Path.equals(targetPath, myPath)) {
581
- event_0.preventDefault(), debug$k("targetPath and myPath is the same, not moving");
429
+ event_0.preventDefault(), debug$j("targetPath and myPath is the same, not moving");
582
430
  return;
583
431
  }
584
- debug$k(`Moving element ${element._key} from path ${JSON.stringify(myPath)} to ${JSON.stringify(targetPath)} (${dragPosition})`), slate.Transforms.moveNodes(editor, {
432
+ debug$j(`Moving element ${element._key} from path ${JSON.stringify(myPath)} to ${JSON.stringify(targetPath)} (${dragPosition})`), slate.Transforms.moveNodes(editor, {
585
433
  at: myPath,
586
434
  to: targetPath
587
435
  }), editor.onChange();
588
436
  return;
589
437
  }
590
- debug$k("No target element, not doing anything");
438
+ debug$j("No target element, not doing anything");
591
439
  }, $[16] = editor, $[17] = element, $[18] = t9) : t9 = $[18];
592
440
  const handleDragEnd = t9;
593
441
  let t10;
594
442
  $[19] !== editor || $[20] !== element ? (t10 = (event_1) => {
595
- IS_DRAGGING_BLOCK_ELEMENT.get(editor) && (debug$k("On drop (prevented)", element), event_1.preventDefault(), event_1.stopPropagation(), setIsDragOver(!1));
443
+ IS_DRAGGING_BLOCK_ELEMENT.get(editor) && (debug$j("On drop (prevented)", element), event_1.preventDefault(), event_1.stopPropagation(), setIsDragOver(!1));
596
444
  }, $[19] = editor, $[20] = element, $[21] = t10) : t10 = $[21];
597
445
  const handleDrop = t10;
598
446
  let t11;
@@ -609,10 +457,10 @@ const debug$k = debugWithName("components:DraggableBlock"), DraggableBlock = (t0
609
457
  let t12;
610
458
  $[26] !== blockElement || $[27] !== editor || $[28] !== handleDrag || $[29] !== isInline || $[30] !== isVoid ? (t12 = (event_3) => {
611
459
  if (!isVoid || isInline) {
612
- debug$k("Not dragging block"), IS_DRAGGING_BLOCK_ELEMENT.delete(editor), IS_DRAGGING.set(editor, !1);
460
+ debug$j("Not dragging block"), IS_DRAGGING_BLOCK_ELEMENT.delete(editor), IS_DRAGGING.set(editor, !1);
613
461
  return;
614
462
  }
615
- if (debug$k("Drag start"), IS_DRAGGING.set(editor, !0), event_3.dataTransfer && (event_3.dataTransfer.setData("application/portable-text", "something"), event_3.dataTransfer.effectAllowed = "move"), blockElement && blockElement instanceof HTMLElement) {
463
+ if (debug$j("Drag start"), IS_DRAGGING.set(editor, !0), event_3.dataTransfer && (event_3.dataTransfer.setData("application/portable-text", "something"), event_3.dataTransfer.effectAllowed = "move"), blockElement && blockElement instanceof HTMLElement) {
616
464
  let dragGhost = blockElement.cloneNode(!0);
617
465
  const customGhost = dragGhost.querySelector("[data-pt-drag-ghost-element]");
618
466
  if (customGhost && (dragGhost = customGhost), dragGhost.setAttribute("data-dragged", ""), document.body) {
@@ -727,7 +575,7 @@ const EMPTY_ANNOTATIONS = [], inlineBlockStyle = {
727
575
  let level;
728
576
  if (isListItem && (typeof element.level == "number" && (level = element.level), className += ` pt-list-item pt-list-item-${element.listItem} pt-list-item-level-${level || 1}`), editor.isListBlock(value) && isListItem && element.listItem) {
729
577
  const listType = schemaTypes.lists.find((item_0) => item_0.value === element.listItem);
730
- renderListItem && listType ? renderedBlock = renderListItem({
578
+ renderListItem && listType && (renderedBlock = renderListItem({
731
579
  block: value,
732
580
  children: renderedBlock,
733
581
  focused,
@@ -737,7 +585,7 @@ const EMPTY_ANNOTATIONS = [], inlineBlockStyle = {
737
585
  schemaType: listType,
738
586
  level: value.level || 1,
739
587
  editorElementRef: blockRef
740
- }) : renderedBlock = /* @__PURE__ */ jsxRuntime.jsx(DefaultListItem, { listStyle: value.listItem || schemaTypes.lists[0].value, listLevel: value.level || 1, children: /* @__PURE__ */ jsxRuntime.jsx(DefaultListItemInner, { children: renderedBlock }) });
588
+ }));
741
589
  }
742
590
  const renderProps = Object.defineProperty({
743
591
  children: renderedBlock,
@@ -783,10 +631,7 @@ const EMPTY_ANNOTATIONS = [], inlineBlockStyle = {
783
631
  }
784
632
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { ...attributes, className, children: [
785
633
  children,
786
- /* @__PURE__ */ jsxRuntime.jsxs(DraggableBlock, { element, readOnly, blockRef, children: [
787
- renderedBlockFromProps && /* @__PURE__ */ jsxRuntime.jsx("div", { ref: blockRef, contentEditable: !1, children: renderedBlockFromProps }),
788
- !renderedBlockFromProps && /* @__PURE__ */ jsxRuntime.jsx(DefaultBlockObject, { selected, children: /* @__PURE__ */ jsxRuntime.jsx(DefaultObject, { value }) })
789
- ] })
634
+ /* @__PURE__ */ jsxRuntime.jsx(DraggableBlock, { element, readOnly, blockRef, children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: blockRef, contentEditable: !1, children: renderedBlockFromProps || /* @__PURE__ */ jsxRuntime.jsx(DefaultObject, { value }) }) })
790
635
  ] }, element._key);
791
636
  };
792
637
  Element.displayName = "Element";
@@ -1887,7 +1732,7 @@ function isRedoing(editor) {
1887
1732
  function setIsRedoing(editor, isRedoing2) {
1888
1733
  IS_REDOING.set(editor, isRedoing2);
1889
1734
  }
1890
- const debug$j = debugWithName("plugin:withUndoRedo"), debugVerbose$3 = debug$j.enabled && !1, SAVING = /* @__PURE__ */ new WeakMap(), REMOTE_PATCHES = /* @__PURE__ */ new WeakMap(), UNDO_STEP_LIMIT = 1e3, isSaving = (editor) => {
1735
+ const debug$i = debugWithName("plugin:withUndoRedo"), SAVING = /* @__PURE__ */ new WeakMap(), REMOTE_PATCHES = /* @__PURE__ */ new WeakMap(), UNDO_STEP_LIMIT = 1e3, isSaving = (editor) => {
1891
1736
  const state = SAVING.get(editor);
1892
1737
  return state === void 0 ? !0 : state;
1893
1738
  }, getRemotePatches = (editor) => (REMOTE_PATCHES.get(editor) || REMOTE_PATCHES.set(editor, []), REMOTE_PATCHES.get(editor) || []);
@@ -1900,7 +1745,7 @@ function createWithUndoRedo(options) {
1900
1745
  let previousSnapshot = fromSlateValue(editor.children, blockSchemaType.name);
1901
1746
  const remotePatches = getRemotePatches(editor);
1902
1747
  options.subscriptions.push(() => {
1903
- debug$j("Subscribing to patches");
1748
+ debug$i("Subscribing to patches");
1904
1749
  const sub = editorActor.on("patches", ({
1905
1750
  patches: patches2,
1906
1751
  snapshot
@@ -1909,7 +1754,7 @@ function createWithUndoRedo(options) {
1909
1754
  patches2.forEach((patch) => {
1910
1755
  if (!reset && patch.origin !== "local" && remotePatches) {
1911
1756
  if (patch.type === "unset" && patch.path.length === 0) {
1912
- debug$j("Someone else cleared the content, resetting undo/redo history"), editor.history = {
1757
+ debug$i("Someone else cleared the content, resetting undo/redo history"), editor.history = {
1913
1758
  undos: [],
1914
1759
  redos: []
1915
1760
  }, remotePatches.splice(0, remotePatches.length), SAVING.set(editor, !0), reset = !0;
@@ -1925,7 +1770,7 @@ function createWithUndoRedo(options) {
1925
1770
  }), previousSnapshot = snapshot;
1926
1771
  });
1927
1772
  return () => {
1928
- debug$j("Unsubscribing to patches"), sub.unsubscribe();
1773
+ debug$i("Unsubscribing to patches"), sub.unsubscribe();
1929
1774
  };
1930
1775
  }), editor.history = {
1931
1776
  undos: [],
@@ -1964,7 +1809,7 @@ function createWithUndoRedo(options) {
1964
1809
  operations: [...editor.selection === null ? [] : [createSelectOperation(editor)], op],
1965
1810
  timestamp: /* @__PURE__ */ new Date()
1966
1811
  };
1967
- undos.push(newStep), debug$j("Created new undo step", step);
1812
+ undos.push(newStep), debug$i("Created new undo step", step);
1968
1813
  }
1969
1814
  for (; undos.length > UNDO_STEP_LIMIT; )
1970
1815
  undos.shift();
@@ -1981,7 +1826,7 @@ function createWithUndoRedo(options) {
1981
1826
  } = editor.history;
1982
1827
  if (undos.length > 0) {
1983
1828
  const step = undos[undos.length - 1];
1984
- if (debug$j("Undoing", step), step.operations.length > 0) {
1829
+ if (debug$i("Undoing", step), step.operations.length > 0) {
1985
1830
  const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
1986
1831
  let transformedOperations = step.operations;
1987
1832
  otherPatches.forEach((item) => {
@@ -1999,7 +1844,7 @@ function createWithUndoRedo(options) {
1999
1844
  });
2000
1845
  }), editor.normalize(), editor.onChange();
2001
1846
  } catch (err) {
2002
- debug$j("Could not perform undo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
1847
+ debug$i("Could not perform undo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
2003
1848
  undos: [],
2004
1849
  redos: []
2005
1850
  }, SAVING.set(editor, !0), setIsUndoing(editor, !1), editor.onChange();
@@ -2018,7 +1863,7 @@ function createWithUndoRedo(options) {
2018
1863
  } = editor.history;
2019
1864
  if (redos.length > 0) {
2020
1865
  const step = redos[redos.length - 1];
2021
- if (debug$j("Redoing", step), step.operations.length > 0) {
1866
+ if (debug$i("Redoing", step), step.operations.length > 0) {
2022
1867
  const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
2023
1868
  let transformedOperations = step.operations;
2024
1869
  otherPatches.forEach((item) => {
@@ -2035,7 +1880,7 @@ function createWithUndoRedo(options) {
2035
1880
  });
2036
1881
  }), editor.normalize(), editor.onChange();
2037
1882
  } catch (err) {
2038
- debug$j("Could not perform redo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
1883
+ debug$i("Could not perform redo step", err), remotePatches.splice(0, remotePatches.length), slate.Transforms.deselect(editor), editor.history = {
2039
1884
  undos: [],
2040
1885
  redos: []
2041
1886
  }, SAVING.set(editor, !0), setIsRedoing(editor, !1), editor.onChange();
@@ -2048,7 +1893,6 @@ function createWithUndoRedo(options) {
2048
1893
  };
2049
1894
  }
2050
1895
  function transformOperation(editor, patch, operation, snapshot, previousSnapshot) {
2051
- debugVerbose$3 && (debug$j(`Adjusting '${operation.type}' operation paths for '${patch.type}' patch`), debug$j(`Operation ${JSON.stringify(operation)}`), debug$j(`Patch ${JSON.stringify(patch)}`));
2052
1896
  const transformedOperation = {
2053
1897
  ...operation
2054
1898
  };
@@ -2056,16 +1900,16 @@ function transformOperation(editor, patch, operation, snapshot, previousSnapshot
2056
1900
  const insertBlockIndex = (snapshot || []).findIndex((blk) => isEqual__default.default({
2057
1901
  _key: blk._key
2058
1902
  }, patch.path[0]));
2059
- return debug$j(`Adjusting block path (+${patch.items.length}) for '${transformedOperation.type}' operation and patch '${patch.type}'`), [adjustBlockPath(transformedOperation, patch.items.length, insertBlockIndex)];
1903
+ return debug$i(`Adjusting block path (+${patch.items.length}) for '${transformedOperation.type}' operation and patch '${patch.type}'`), [adjustBlockPath(transformedOperation, patch.items.length, insertBlockIndex)];
2060
1904
  }
2061
1905
  if (patch.type === "unset" && patch.path.length === 1) {
2062
1906
  const unsetBlockIndex = (previousSnapshot || []).findIndex((blk) => isEqual__default.default({
2063
1907
  _key: blk._key
2064
1908
  }, patch.path[0]));
2065
- return "path" in transformedOperation && Array.isArray(transformedOperation.path) && transformedOperation.path[0] === unsetBlockIndex ? (debug$j("Skipping transformation that targeted removed block"), []) : (debugVerbose$3 && (debug$j(`Selection ${JSON.stringify(editor.selection)}`), debug$j(`Adjusting block path (-1) for '${transformedOperation.type}' operation and patch '${patch.type}'`)), [adjustBlockPath(transformedOperation, -1, unsetBlockIndex)]);
1909
+ return "path" in transformedOperation && Array.isArray(transformedOperation.path) && transformedOperation.path[0] === unsetBlockIndex ? (debug$i("Skipping transformation that targeted removed block"), []) : [adjustBlockPath(transformedOperation, -1, unsetBlockIndex)];
2066
1910
  }
2067
1911
  if (patch.type === "unset" && patch.path.length === 0)
2068
- return debug$j(`Adjusting selection for unset everything patch and ${operation.type} operation`), [];
1912
+ return debug$i(`Adjusting selection for unset everything patch and ${operation.type} operation`), [];
2069
1913
  if (patch.type === "diffMatchPatch") {
2070
1914
  const operationTargetBlock = findOperationTargetBlock(editor, transformedOperation);
2071
1915
  return !operationTargetBlock || !isEqual__default.default({
@@ -2345,7 +2189,7 @@ const syncValueCallback = ({
2345
2189
  }
2346
2190
  }
2347
2191
  }
2348
- }), debug$i = debugWithName("hook:useSyncValue");
2192
+ }), debug$h = debugWithName("hook:useSyncValue");
2349
2193
  async function updateValue({
2350
2194
  context,
2351
2195
  sendBack,
@@ -2355,7 +2199,7 @@ async function updateValue({
2355
2199
  }) {
2356
2200
  let isChanged = !1, isValid = !0;
2357
2201
  const hadSelection = !!slateEditor.selection;
2358
- if ((!value || value.length === 0) && (debug$i("Value is empty"), slate.Editor.withoutNormalizing(slateEditor, () => {
2202
+ if ((!value || value.length === 0) && (debug$h("Value is empty"), slate.Editor.withoutNormalizing(slateEditor, () => {
2359
2203
  withoutSaving(slateEditor, () => {
2360
2204
  withoutPatching(slateEditor, () => {
2361
2205
  hadSelection && slate.Transforms.deselect(slateEditor);
@@ -2411,14 +2255,14 @@ async function updateValue({
2411
2255
  });
2412
2256
  }
2413
2257
  if (!isValid) {
2414
- debug$i("Invalid value, returning"), sendBack({
2258
+ debug$h("Invalid value, returning"), sendBack({
2415
2259
  type: "done syncing",
2416
2260
  value
2417
2261
  });
2418
2262
  return;
2419
2263
  }
2420
2264
  if (isChanged) {
2421
- debug$i("Server value changed, syncing editor");
2265
+ debug$h("Server value changed, syncing editor");
2422
2266
  try {
2423
2267
  slateEditor.onChange();
2424
2268
  } catch (err) {
@@ -2446,7 +2290,7 @@ async function updateValue({
2446
2290
  value
2447
2291
  });
2448
2292
  } else
2449
- debug$i("Server value and editor value is equal, no need to sync.");
2293
+ debug$h("Server value and editor value is equal, no need to sync.");
2450
2294
  sendBack({
2451
2295
  type: "done syncing",
2452
2296
  value
@@ -2480,7 +2324,7 @@ function syncBlock({
2480
2324
  type: "patch",
2481
2325
  patch
2482
2326
  });
2483
- })), validation.valid || validation.resolution?.autoResolve ? (oldBlock._key === currentBlock._key ? (debug$i.enabled && debug$i("Updating block", oldBlock, currentBlock), _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex)) : (debug$i.enabled && debug$i("Replacing block", oldBlock, currentBlock), _replaceBlock(slateEditor, currentBlock, currentBlockIndex)), blockChanged = !0) : (sendBack({
2327
+ })), validation.valid || validation.resolution?.autoResolve ? (oldBlock._key === currentBlock._key ? (debug$h.enabled && debug$h("Updating block", oldBlock, currentBlock), _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex)) : (debug$h.enabled && debug$h("Replacing block", oldBlock, currentBlock), _replaceBlock(slateEditor, currentBlock, currentBlockIndex)), blockChanged = !0) : (sendBack({
2484
2328
  type: "invalid value",
2485
2329
  resolution: validation.resolution,
2486
2330
  value
@@ -2488,9 +2332,9 @@ function syncBlock({
2488
2332
  }
2489
2333
  if (!oldBlock && blockValid) {
2490
2334
  const validationValue = [value[currentBlockIndex]], validation = validateValue(validationValue, context.schema, context.keyGenerator);
2491
- debug$i.enabled && debug$i("Validating and inserting new block in the end of the value", currentBlock), validation.valid || validation.resolution?.autoResolve ? slate.Transforms.insertNodes(slateEditor, currentBlock, {
2335
+ debug$h.enabled && debug$h("Validating and inserting new block in the end of the value", currentBlock), validation.valid || validation.resolution?.autoResolve ? slate.Transforms.insertNodes(slateEditor, currentBlock, {
2492
2336
  at: [currentBlockIndex]
2493
- }) : (debug$i("Invalid", validation), sendBack({
2337
+ }) : (debug$h("Invalid", validation), sendBack({
2494
2338
  type: "invalid value",
2495
2339
  resolution: validation.resolution,
2496
2340
  value
@@ -2518,14 +2362,14 @@ function _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex) {
2518
2362
  const oldBlockChildrenLength = oldBlock.children.length;
2519
2363
  currentBlock.children.length < oldBlockChildrenLength && Array.from(Array(oldBlockChildrenLength - currentBlock.children.length)).forEach((_, index) => {
2520
2364
  const childIndex = oldBlockChildrenLength - 1 - index;
2521
- childIndex > 0 && (debug$i("Removing child"), slate.Transforms.removeNodes(slateEditor, {
2365
+ childIndex > 0 && (debug$h("Removing child"), slate.Transforms.removeNodes(slateEditor, {
2522
2366
  at: [currentBlockIndex, childIndex]
2523
2367
  }));
2524
2368
  }), currentBlock.children.forEach((currentBlockChild, currentBlockChildIndex) => {
2525
2369
  const oldBlockChild = oldBlock.children[currentBlockChildIndex], isChildChanged = !isEqual__default.default(currentBlockChild, oldBlockChild), isTextChanged = !isEqual__default.default(currentBlockChild.text, oldBlockChild?.text), path = [currentBlockIndex, currentBlockChildIndex];
2526
2370
  if (isChildChanged)
2527
2371
  if (currentBlockChild._key === oldBlockChild?._key) {
2528
- debug$i("Updating changed child", currentBlockChild, oldBlockChild), slate.Transforms.setNodes(slateEditor, currentBlockChild, {
2372
+ debug$h("Updating changed child", currentBlockChild, oldBlockChild), slate.Transforms.setNodes(slateEditor, currentBlockChild, {
2529
2373
  at: path
2530
2374
  });
2531
2375
  const isSpanNode = slate.Text.isText(currentBlockChild) && currentBlockChild._type === "span" && slate.Text.isText(oldBlockChild) && oldBlockChild._type === "span";
@@ -2542,23 +2386,23 @@ function _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex) {
2542
2386
  }
2543
2387
  }), slate.Transforms.insertText(slateEditor, currentBlockChild.text, {
2544
2388
  at: path
2545
- }), slateEditor.onChange()) : isSpanNode || (debug$i("Updating changed inline object child", currentBlockChild), slate.Transforms.setNodes(slateEditor, {
2389
+ }), slateEditor.onChange()) : isSpanNode || (debug$h("Updating changed inline object child", currentBlockChild), slate.Transforms.setNodes(slateEditor, {
2546
2390
  _key: VOID_CHILD_KEY
2547
2391
  }, {
2548
2392
  at: [...path, 0],
2549
2393
  voids: !0
2550
2394
  }));
2551
- } else oldBlockChild ? (debug$i("Replacing child", currentBlockChild), slate.Transforms.removeNodes(slateEditor, {
2395
+ } else oldBlockChild ? (debug$h("Replacing child", currentBlockChild), slate.Transforms.removeNodes(slateEditor, {
2552
2396
  at: [currentBlockIndex, currentBlockChildIndex]
2553
2397
  }), slate.Transforms.insertNodes(slateEditor, currentBlockChild, {
2554
2398
  at: [currentBlockIndex, currentBlockChildIndex]
2555
- }), slateEditor.onChange()) : oldBlockChild || (debug$i("Inserting new child", currentBlockChild), slate.Transforms.insertNodes(slateEditor, currentBlockChild, {
2399
+ }), slateEditor.onChange()) : oldBlockChild || (debug$h("Inserting new child", currentBlockChild), slate.Transforms.insertNodes(slateEditor, currentBlockChild, {
2556
2400
  at: [currentBlockIndex, currentBlockChildIndex]
2557
2401
  }), slateEditor.onChange());
2558
2402
  });
2559
2403
  }
2560
2404
  }
2561
- const debug$h = debugWithName("component:PortableTextEditor:Synchronizer");
2405
+ const debug$g = debugWithName("component:PortableTextEditor:Synchronizer");
2562
2406
  function Synchronizer(props) {
2563
2407
  const $ = reactCompilerRuntime.c(40), {
2564
2408
  editorActor,
@@ -2629,19 +2473,19 @@ function Synchronizer(props) {
2629
2473
  }, t12 = [syncActorRef, readOnly], $[25] = readOnly, $[26] = syncActorRef, $[27] = t11, $[28] = t12) : (t11 = $[27], t12 = $[28]), React.useEffect(t11, t12);
2630
2474
  let t13, t14;
2631
2475
  $[29] !== syncActorRef || $[30] !== value ? (t13 = () => {
2632
- debug$h("Value from props changed, syncing new value"), syncActorRef.send({
2476
+ debug$g("Value from props changed, syncing new value"), syncActorRef.send({
2633
2477
  type: "update value",
2634
2478
  value
2635
2479
  });
2636
2480
  }, t14 = [syncActorRef, value], $[29] = syncActorRef, $[30] = value, $[31] = t13, $[32] = t14) : (t13 = $[31], t14 = $[32]), React.useEffect(t13, t14);
2637
2481
  let t15;
2638
2482
  $[33] !== editorActor || $[34] !== mutationActorRef ? (t15 = () => {
2639
- debug$h("Subscribing to patch events");
2483
+ debug$g("Subscribing to patch events");
2640
2484
  const sub = editorActor.on("patch", (event_1) => {
2641
2485
  mutationActorRef.send(event_1);
2642
2486
  });
2643
2487
  return () => {
2644
- debug$h("Unsubscribing to patch events"), sub.unsubscribe();
2488
+ debug$g("Unsubscribing to patch events"), sub.unsubscribe();
2645
2489
  };
2646
2490
  }, $[33] = editorActor, $[34] = mutationActorRef, $[35] = t15) : t15 = $[35];
2647
2491
  let t16;
@@ -2656,11 +2500,11 @@ function _temp(s) {
2656
2500
  return s.context.value;
2657
2501
  }
2658
2502
  Synchronizer.displayName = "Synchronizer";
2659
- const debug$g = debugWithName("operationToPatches");
2503
+ const debug$f = debugWithName("operationToPatches");
2660
2504
  function createOperationToPatches(types2) {
2661
2505
  const textBlockName = types2.block.name;
2662
2506
  function insertTextPatch(editor, operation, beforeValue) {
2663
- debug$g.enabled && debug$g("Operation", JSON.stringify(operation, null, 2));
2507
+ debug$f.enabled && debug$f("Operation", JSON.stringify(operation, null, 2));
2664
2508
  const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
2665
2509
  if (!block)
2666
2510
  throw new Error("Could not find block");
@@ -2753,7 +2597,7 @@ function createOperationToPatches(types2) {
2753
2597
  _key: block.children[operation.path[1] - 1]._key
2754
2598
  }])];
2755
2599
  }
2756
- return debug$g("Something was inserted into a void block. Not producing editor patches."), [];
2600
+ return debug$f("Something was inserted into a void block. Not producing editor patches."), [];
2757
2601
  }
2758
2602
  function splitNodePatch(editor, operation, beforeValue) {
2759
2603
  const patches$1 = [], splitBlock = editor.children[operation.path[0]];
@@ -2811,9 +2655,9 @@ function createOperationToPatches(types2) {
2811
2655
  _key: block._key
2812
2656
  }, "children", {
2813
2657
  _key: spanToRemove._key
2814
- }])] : (debug$g("Span not found in editor trying to remove node"), []);
2658
+ }])] : (debug$f("Span not found in editor trying to remove node"), []);
2815
2659
  } else
2816
- return debug$g("Not creating patch inside object block"), [];
2660
+ return debug$f("Not creating patch inside object block"), [];
2817
2661
  }
2818
2662
  function mergeNodePatch(editor, operation, beforeValue) {
2819
2663
  const patches$1 = [], block = beforeValue[operation.path[0]], updatedBlock = editor.children[operation.path[0]];
@@ -2839,7 +2683,7 @@ function createOperationToPatches(types2) {
2839
2683
  _key: removedSpan._key
2840
2684
  }])) : console.warn(`Multiple spans have \`_key\` ${removedSpan._key}. It's ambiguous which one to remove.`, JSON.stringify(block, null, 2)));
2841
2685
  } else
2842
- debug$g("Void nodes can't be merged, not creating any patches");
2686
+ debug$f("Void nodes can't be merged, not creating any patches");
2843
2687
  return patches$1;
2844
2688
  }
2845
2689
  function moveNodePatch(editor, operation, beforeValue) {
@@ -2878,9 +2722,19 @@ function createOperationToPatches(types2) {
2878
2722
  splitNodePatch
2879
2723
  };
2880
2724
  }
2725
+ const IS_APPLYING_BEHAVIOR_ACTIONS = /* @__PURE__ */ new WeakMap();
2726
+ function withApplyingBehaviorActions(editor, fn) {
2727
+ const prev = isApplyingBehaviorActions(editor);
2728
+ IS_APPLYING_BEHAVIOR_ACTIONS.set(editor, !0), fn(), IS_APPLYING_BEHAVIOR_ACTIONS.set(editor, prev);
2729
+ }
2730
+ function isApplyingBehaviorActions(editor) {
2731
+ return IS_APPLYING_BEHAVIOR_ACTIONS.get(editor) ?? !1;
2732
+ }
2881
2733
  function createWithEventListeners(editorActor, subscriptions) {
2882
2734
  return function(editor) {
2883
- return editorActor.getSnapshot().context.maxBlocks !== void 0 || (subscriptions.push(() => {
2735
+ if (editorActor.getSnapshot().context.maxBlocks !== void 0)
2736
+ return editor;
2737
+ subscriptions.push(() => {
2884
2738
  const subscription = editorActor.on("*", (event) => {
2885
2739
  switch (event.type) {
2886
2740
  case "annotation.add": {
@@ -2905,17 +2759,6 @@ function createWithEventListeners(editorActor, subscriptions) {
2905
2759
  });
2906
2760
  break;
2907
2761
  }
2908
- case "annotation.toggle": {
2909
- editorActor.send({
2910
- type: "behavior event",
2911
- behaviorEvent: {
2912
- type: "annotation.toggle",
2913
- annotation: event.annotation
2914
- },
2915
- editor
2916
- });
2917
- break;
2918
- }
2919
2762
  case "blur": {
2920
2763
  editorActor.send({
2921
2764
  type: "behavior event",
@@ -2926,28 +2769,6 @@ function createWithEventListeners(editorActor, subscriptions) {
2926
2769
  });
2927
2770
  break;
2928
2771
  }
2929
- case "decorator.add": {
2930
- editorActor.send({
2931
- type: "behavior event",
2932
- behaviorEvent: {
2933
- type: "decorator.add",
2934
- decorator: event.decorator
2935
- },
2936
- editor
2937
- });
2938
- break;
2939
- }
2940
- case "decorator.remove": {
2941
- editorActor.send({
2942
- type: "behavior event",
2943
- behaviorEvent: {
2944
- type: "decorator.remove",
2945
- decorator: event.decorator
2946
- },
2947
- editor
2948
- });
2949
- break;
2950
- }
2951
2772
  case "decorator.toggle": {
2952
2773
  editorActor.send({
2953
2774
  type: "behavior event",
@@ -3003,6 +2824,17 @@ function createWithEventListeners(editorActor, subscriptions) {
3003
2824
  });
3004
2825
  break;
3005
2826
  }
2827
+ case "select": {
2828
+ editorActor.send({
2829
+ type: "behavior event",
2830
+ behaviorEvent: {
2831
+ type: "select",
2832
+ selection: event.selection
2833
+ },
2834
+ editor
2835
+ });
2836
+ break;
2837
+ }
3006
2838
  case "style.toggle": {
3007
2839
  editorActor.send({
3008
2840
  type: "behavior event",
@@ -3019,25 +2851,11 @@ function createWithEventListeners(editorActor, subscriptions) {
3019
2851
  return () => {
3020
2852
  subscription.unsubscribe();
3021
2853
  };
3022
- }), editor.addMark = (mark) => {
3023
- editorActor.send({
3024
- type: "behavior event",
3025
- behaviorEvent: {
3026
- type: "decorator.add",
3027
- decorator: mark
3028
- },
3029
- editor
3030
- });
3031
- }, editor.removeMark = (mark) => {
3032
- editorActor.send({
3033
- type: "behavior event",
3034
- behaviorEvent: {
3035
- type: "decorator.remove",
3036
- decorator: mark
3037
- },
3038
- editor
3039
- });
3040
- }, editor.deleteBackward = (unit) => {
2854
+ });
2855
+ const {
2856
+ select
2857
+ } = editor;
2858
+ return editor.deleteBackward = (unit) => {
3041
2859
  editorActor.send({
3042
2860
  type: "behavior event",
3043
2861
  behaviorEvent: {
@@ -3081,7 +2899,21 @@ function createWithEventListeners(editorActor, subscriptions) {
3081
2899
  },
3082
2900
  editor
3083
2901
  });
3084
- }), editor;
2902
+ }, editor.select = (location) => {
2903
+ if (isApplyingBehaviorActions(editor)) {
2904
+ select(location);
2905
+ return;
2906
+ }
2907
+ const range = slate.Editor.range(editor, location);
2908
+ editorActor.send({
2909
+ type: "behavior event",
2910
+ behaviorEvent: {
2911
+ type: "select",
2912
+ selection: toPortableTextRange(fromSlateValue(editor.children, editorActor.getSnapshot().context.schema.block.name, KEY_TO_VALUE_ELEMENT.get(editor)), range, editorActor.getSnapshot().context.schema)
2913
+ },
2914
+ editor
2915
+ });
2916
+ }, editor;
3085
2917
  };
3086
2918
  }
3087
2919
  function createWithMaxBlocks(editorActor) {
@@ -3178,13 +3010,13 @@ function createWithObjectKeys(editorActor, schemaTypes) {
3178
3010
  }, editor;
3179
3011
  };
3180
3012
  }
3181
- const debug$f = debugWithName("applyPatches"), debugVerbose$2 = debug$f.enabled && !0;
3013
+ const debug$e = debugWithName("applyPatches"), debugVerbose = debug$e.enabled && !0;
3182
3014
  function createApplyPatch(schemaTypes) {
3183
3015
  return (editor, patch) => {
3184
3016
  let changed = !1;
3185
- debugVerbose$2 && (debug$f(`
3017
+ debugVerbose && (debug$e(`
3186
3018
 
3187
- NEW PATCH =============================================================`), debug$f(JSON.stringify(patch, null, 2)));
3019
+ NEW PATCH =============================================================`), debug$e(JSON.stringify(patch, null, 2)));
3188
3020
  try {
3189
3021
  switch (patch.type) {
3190
3022
  case "insert":
@@ -3200,7 +3032,7 @@ NEW PATCH =============================================================`), debug
3200
3032
  changed = diffMatchPatch(editor, patch);
3201
3033
  break;
3202
3034
  default:
3203
- debug$f("Unhandled patch", patch.type);
3035
+ debug$e("Unhandled patch", patch.type);
3204
3036
  }
3205
3037
  } catch (err) {
3206
3038
  console.error(err);
@@ -3215,9 +3047,9 @@ function diffMatchPatch(editor, patch) {
3215
3047
  childPath
3216
3048
  } = findBlockAndChildFromPath(editor, patch.path);
3217
3049
  if (!block)
3218
- return debug$f("Block not found"), !1;
3050
+ return debug$e("Block not found"), !1;
3219
3051
  if (!child || !childPath)
3220
- return debug$f("Child not found"), !1;
3052
+ return debug$e("Child not found"), !1;
3221
3053
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
3222
3054
  return !1;
3223
3055
  const patches2 = parse(patch.value), [newValue] = apply(patches2, child.text, {
@@ -3247,9 +3079,9 @@ function insertPatch(editor, patch, schemaTypes) {
3247
3079
  childPath: targetChildPath
3248
3080
  } = findBlockAndChildFromPath(editor, patch.path);
3249
3081
  if (!targetBlock || !targetBlockPath)
3250
- return debug$f("Block not found"), !1;
3082
+ return debug$e("Block not found"), !1;
3251
3083
  if (patch.path.length > 1 && patch.path[1] !== "children")
3252
- return debug$f("Ignoring patch targeting void value"), !1;
3084
+ return debug$e("Ignoring patch targeting void value"), !1;
3253
3085
  if (patch.path.length === 1) {
3254
3086
  const {
3255
3087
  items: items2,
@@ -3257,7 +3089,7 @@ function insertPatch(editor, patch, schemaTypes) {
3257
3089
  } = patch, blocksToInsert = toSlateValue(items2, {
3258
3090
  schemaTypes
3259
3091
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetBlockIndex = targetBlockPath[0], normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex;
3260
- return debug$f(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
3092
+ return debug$e(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
3261
3093
  at: [normalizedIdx2]
3262
3094
  }), debugState(editor, "after"), !0;
3263
3095
  }
@@ -3266,14 +3098,14 @@ function insertPatch(editor, patch, schemaTypes) {
3266
3098
  position
3267
3099
  } = patch;
3268
3100
  if (!targetChild || !targetChildPath)
3269
- return debug$f("Child not found"), !1;
3101
+ return debug$e("Child not found"), !1;
3270
3102
  const childrenToInsert = targetBlock && toSlateValue([{
3271
3103
  ...targetBlock,
3272
3104
  children: items
3273
3105
  }], {
3274
3106
  schemaTypes
3275
3107
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetChildIndex = targetChildPath[1], normalizedIdx = position === "after" ? targetChildIndex + 1 : targetChildIndex, childInsertPath = [targetChildPath[0], normalizedIdx];
3276
- return debug$f(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
3108
+ return debug$e(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
3277
3109
  at: childInsertPath
3278
3110
  }), debugState(editor, "after"), !0;
3279
3111
  }
@@ -3287,14 +3119,14 @@ function setPatch(editor, patch) {
3287
3119
  childPath
3288
3120
  } = findBlockAndChildFromPath(editor, patch.path);
3289
3121
  if (!block)
3290
- return debug$f("Block not found"), !1;
3122
+ return debug$e("Block not found"), !1;
3291
3123
  const isTextBlock = editor.isTextBlock(block);
3292
3124
  if (isTextBlock && patch.path.length > 1 && patch.path[1] !== "children")
3293
- return debug$f("Ignoring setting void value"), !1;
3125
+ return debug$e("Ignoring setting void value"), !1;
3294
3126
  if (debugState(editor, "before"), isTextBlock && child && childPath) {
3295
3127
  if (slate.Text.isText(value) && slate.Text.isText(child)) {
3296
3128
  const newText = child.text;
3297
- value.text !== newText && (debug$f("Setting text property"), editor.apply({
3129
+ value.text !== newText && (debug$e("Setting text property"), editor.apply({
3298
3130
  type: "remove_text",
3299
3131
  path: childPath,
3300
3132
  offset: 0,
@@ -3306,7 +3138,7 @@ function setPatch(editor, patch) {
3306
3138
  text: value.text
3307
3139
  }), editor.onChange());
3308
3140
  } else
3309
- debug$f("Setting non-text property"), editor.apply({
3141
+ debug$e("Setting non-text property"), editor.apply({
3310
3142
  type: "set_node",
3311
3143
  path: childPath,
3312
3144
  properties: {},
@@ -3314,7 +3146,7 @@ function setPatch(editor, patch) {
3314
3146
  });
3315
3147
  return !0;
3316
3148
  } else if (slate.Element.isElement(block) && patch.path.length === 1 && blockPath) {
3317
- debug$f("Setting block property");
3149
+ debug$e("Setting block property");
3318
3150
  const {
3319
3151
  children,
3320
3152
  ...nextRest
@@ -3331,7 +3163,7 @@ function setPatch(editor, patch) {
3331
3163
  ...prevRest
3332
3164
  },
3333
3165
  newProperties: nextRest
3334
- }), debug$f("Setting children"), block.children.forEach((c, cIndex) => {
3166
+ }), debug$e("Setting children"), block.children.forEach((c, cIndex) => {
3335
3167
  editor.apply({
3336
3168
  type: "remove_node",
3337
3169
  path: blockPath.concat(block.children.length - 1 - cIndex),
@@ -3357,7 +3189,7 @@ function setPatch(editor, patch) {
3357
3189
  }
3358
3190
  function unsetPatch(editor, patch) {
3359
3191
  if (patch.path.length === 0) {
3360
- debug$f("Removing everything"), debugState(editor, "before");
3192
+ debug$e("Removing everything"), debugState(editor, "before");
3361
3193
  const previousSelection = editor.selection;
3362
3194
  return slate.Transforms.deselect(editor), editor.children.forEach((_child, i) => {
3363
3195
  slate.Transforms.removeNodes(editor, {
@@ -3384,13 +3216,13 @@ function unsetPatch(editor, patch) {
3384
3216
  } = findBlockAndChildFromPath(editor, patch.path);
3385
3217
  if (patch.path.length === 1) {
3386
3218
  if (!block || !blockPath)
3387
- return debug$f("Block not found"), !1;
3219
+ return debug$e("Block not found"), !1;
3388
3220
  const blockIndex = blockPath[0];
3389
- return debug$f(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
3221
+ return debug$e(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
3390
3222
  at: [blockIndex]
3391
3223
  }), debugState(editor, "after"), !0;
3392
3224
  }
3393
- return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$f("Child not found"), !1) : (debug$f(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose$2 && debug$f(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
3225
+ return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$e("Child not found"), !1) : (debug$e(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose && debug$e(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
3394
3226
  at: childPath
3395
3227
  }), debugState(editor, "after"), !0) : !1;
3396
3228
  }
@@ -3398,7 +3230,7 @@ function isKeyedSegment(segment) {
3398
3230
  return typeof segment == "object" && "_key" in segment;
3399
3231
  }
3400
3232
  function debugState(editor, stateName) {
3401
- debugVerbose$2 && (debug$f(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$f(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3233
+ debugVerbose && (debug$e(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$e(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3402
3234
  }
3403
3235
  function findBlockFromPath(editor, path) {
3404
3236
  let blockIndex = -1;
@@ -3440,7 +3272,7 @@ function findBlockAndChildFromPath(editor, path) {
3440
3272
  childPath: void 0
3441
3273
  };
3442
3274
  }
3443
- const debug$e = debugWithName("plugin:withPatches");
3275
+ const debug$d = debugWithName("plugin:withPatches");
3444
3276
  function createWithPatches({
3445
3277
  editorActor,
3446
3278
  patchFunctions,
@@ -3466,7 +3298,7 @@ function createWithPatches({
3466
3298
  withoutPatching(editor, () => {
3467
3299
  withoutSaving(editor, () => {
3468
3300
  patches2.forEach((patch) => {
3469
- debug$e.enabled && debug$e(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3301
+ debug$d.enabled && debug$d(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3470
3302
  });
3471
3303
  });
3472
3304
  });
@@ -3479,10 +3311,10 @@ function createWithPatches({
3479
3311
  remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
3480
3312
  };
3481
3313
  return subscriptions.push(() => {
3482
- debug$e("Subscribing to remote patches");
3314
+ debug$d("Subscribing to remote patches");
3483
3315
  const sub = editorActor.on("patches", handlePatches);
3484
3316
  return () => {
3485
- debug$e("Unsubscribing to remote patches"), sub.unsubscribe();
3317
+ debug$d("Unsubscribing to remote patches"), sub.unsubscribe();
3486
3318
  };
3487
3319
  }), editor.apply = (operation) => {
3488
3320
  let patches$1 = [];
@@ -3533,7 +3365,7 @@ function createWithPatches({
3533
3365
  }, editor;
3534
3366
  };
3535
3367
  }
3536
- const debug$d = debugWithName("plugin:withPlaceholderBlock");
3368
+ const debug$c = debugWithName("plugin:withPlaceholderBlock");
3537
3369
  function createWithPlaceholderBlock(editorActor) {
3538
3370
  return function(editor) {
3539
3371
  const {
@@ -3558,7 +3390,7 @@ function createWithPlaceholderBlock(editorActor) {
3558
3390
  const node = op.node;
3559
3391
  if (op.path[0] === 0 && slate.Editor.isVoid(editor, node)) {
3560
3392
  const nextPath = slate.Path.next(op.path);
3561
- editor.children[nextPath[0]] || (debug$d("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
3393
+ editor.children[nextPath[0]] || (debug$c("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
3562
3394
  decorators: []
3563
3395
  })));
3564
3396
  }
@@ -3567,7 +3399,7 @@ function createWithPlaceholderBlock(editorActor) {
3567
3399
  }, editor;
3568
3400
  };
3569
3401
  }
3570
- const debug$c = debugWithName("plugin:withPortableTextBlockStyle");
3402
+ const debug$b = debugWithName("plugin:withPortableTextBlockStyle");
3571
3403
  function createWithPortableTextBlockStyle(editorActor, types2) {
3572
3404
  const defaultStyle = types2.styles[0].value;
3573
3405
  return function(editor) {
@@ -3580,7 +3412,7 @@ function createWithPortableTextBlockStyle(editorActor, types2) {
3580
3412
  if (op.type === "split_node" && op.path.length === 1 && editor.isTextBlock(op.properties) && op.properties.style !== defaultStyle && op.path[0] === path[0] && !slate.Path.equals(path, op.path)) {
3581
3413
  const [child] = slate.Editor.node(editor, [op.path[0] + 1, 0]);
3582
3414
  if (slate.Text.isText(child) && child.text === "") {
3583
- debug$c(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3415
+ debug$b(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3584
3416
  type: "normalizing"
3585
3417
  }), slate.Transforms.setNodes(editor, {
3586
3418
  style: defaultStyle
@@ -3640,7 +3472,7 @@ function getNextSpan({
3640
3472
  }
3641
3473
  return nextSpan;
3642
3474
  }
3643
- const debug$b = debugWithName("plugin:withPortableTextMarkModel");
3475
+ const debug$a = debugWithName("plugin:withPortableTextMarkModel");
3644
3476
  function createWithPortableTextMarkModel(editorActor, types2) {
3645
3477
  return function(editor) {
3646
3478
  const {
@@ -3654,7 +3486,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3654
3486
  for (const [child, childPath] of children) {
3655
3487
  const nextNode = node.children[childPath[1] + 1];
3656
3488
  if (editor.isTextSpan(child) && editor.isTextSpan(nextNode) && child.marks?.every((mark) => nextNode.marks?.includes(mark)) && nextNode.marks?.every((mark) => child.marks?.includes(mark))) {
3657
- debug$b("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
3489
+ debug$a("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
3658
3490
  type: "normalizing"
3659
3491
  }), slate.Transforms.mergeNodes(editor, {
3660
3492
  at: [childPath[0], childPath[1] + 1],
@@ -3667,7 +3499,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3667
3499
  }
3668
3500
  }
3669
3501
  if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {
3670
- debug$b("Adding .markDefs to block node"), editorActor.send({
3502
+ debug$a("Adding .markDefs to block node"), editorActor.send({
3671
3503
  type: "normalizing"
3672
3504
  }), slate.Transforms.setNodes(editor, {
3673
3505
  markDefs: []
@@ -3679,7 +3511,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3679
3511
  return;
3680
3512
  }
3681
3513
  if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {
3682
- debug$b("Adding .marks to span node"), editorActor.send({
3514
+ debug$a("Adding .marks to span node"), editorActor.send({
3683
3515
  type: "normalizing"
3684
3516
  }), slate.Transforms.setNodes(editor, {
3685
3517
  marks: []
@@ -3693,7 +3525,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3693
3525
  if (editor.isTextSpan(node)) {
3694
3526
  const blockPath = slate.Path.parent(path), [block] = slate.Editor.node(editor, blockPath), decorators2 = types2.decorators.map((decorator) => decorator.value), annotations = node.marks?.filter((mark) => !decorators2.includes(mark));
3695
3527
  if (editor.isTextBlock(block) && node.text === "" && annotations && annotations.length > 0) {
3696
- debug$b("Removing annotations from empty span node"), editorActor.send({
3528
+ debug$a("Removing annotations from empty span node"), editorActor.send({
3697
3529
  type: "normalizing"
3698
3530
  }), slate.Transforms.setNodes(editor, {
3699
3531
  marks: node.marks?.filter((mark) => decorators2.includes(mark))
@@ -3711,7 +3543,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3711
3543
  if (editor.isTextSpan(child)) {
3712
3544
  const marks = child.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !node.markDefs?.find((def) => def._key === mark));
3713
3545
  if (orphanedAnnotations.length > 0) {
3714
- debug$b("Removing orphaned annotations from span node"), editorActor.send({
3546
+ debug$a("Removing orphaned annotations from span node"), editorActor.send({
3715
3547
  type: "normalizing"
3716
3548
  }), slate.Transforms.setNodes(editor, {
3717
3549
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
@@ -3729,7 +3561,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3729
3561
  if (editor.isTextBlock(block)) {
3730
3562
  const decorators2 = types2.decorators.map((decorator) => decorator.value), marks = node.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !block.markDefs?.find((def) => def._key === mark));
3731
3563
  if (orphanedAnnotations.length > 0) {
3732
- debug$b("Removing orphaned annotations from span node"), editorActor.send({
3564
+ debug$a("Removing orphaned annotations from span node"), editorActor.send({
3733
3565
  type: "normalizing"
3734
3566
  }), slate.Transforms.setNodes(editor, {
3735
3567
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
@@ -3747,7 +3579,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3747
3579
  for (const markDef of markDefs)
3748
3580
  markDefKeys.has(markDef._key) || (markDefKeys.add(markDef._key), newMarkDefs.push(markDef));
3749
3581
  if (markDefs.length !== newMarkDefs.length) {
3750
- debug$b("Removing duplicate markDefs"), editorActor.send({
3582
+ debug$a("Removing duplicate markDefs"), editorActor.send({
3751
3583
  type: "normalizing"
3752
3584
  }), slate.Transforms.setNodes(editor, {
3753
3585
  markDefs: newMarkDefs
@@ -3762,7 +3594,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3762
3594
  if (editor.isTextBlock(node) && !editor.operations.some((op) => op.type === "merge_node" && "markDefs" in op.properties && op.path.length === 1)) {
3763
3595
  const newMarkDefs = (node.markDefs || []).filter((def) => node.children.find((child) => slate.Text.isText(child) && Array.isArray(child.marks) && child.marks.includes(def._key)));
3764
3596
  if (node.markDefs && !isEqual__default.default(newMarkDefs, node.markDefs)) {
3765
- debug$b("Removing markDef not in use"), editorActor.send({
3597
+ debug$a("Removing markDef not in use"), editorActor.send({
3766
3598
  type: "normalizing"
3767
3599
  }), slate.Transforms.setNodes(editor, {
3768
3600
  markDefs: newMarkDefs
@@ -3979,7 +3811,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
3979
3811
  const [targetBlock, targetPath] = slate.Editor.node(editor, [op.path[0] - 1]);
3980
3812
  if (editor.isTextBlock(targetBlock)) {
3981
3813
  const oldDefs = Array.isArray(targetBlock.markDefs) && targetBlock.markDefs || [], newMarkDefs = uniq__default.default([...oldDefs, ...op.properties.markDefs]);
3982
- debug$b("Copying markDefs over to merged block", op), slate.Transforms.setNodes(editor, {
3814
+ debug$a("Copying markDefs over to merged block", op), slate.Transforms.setNodes(editor, {
3983
3815
  markDefs: newMarkDefs
3984
3816
  }, {
3985
3817
  at: targetPath,
@@ -4040,7 +3872,12 @@ const addDecoratorActionImplementation = ({
4040
3872
  editor.marks = marks;
4041
3873
  }
4042
3874
  }
4043
- editor.onChange();
3875
+ if (editor.selection) {
3876
+ const selection = editor.selection;
3877
+ editor.selection = {
3878
+ ...selection
3879
+ };
3880
+ }
4044
3881
  }
4045
3882
  }, removeDecoratorActionImplementation = ({
4046
3883
  action
@@ -4048,7 +3885,7 @@ const addDecoratorActionImplementation = ({
4048
3885
  const editor = action.editor, mark = action.decorator, {
4049
3886
  selection
4050
3887
  } = editor;
4051
- if (selection)
3888
+ if (selection) {
4052
3889
  if (slate.Range.isExpanded(selection))
4053
3890
  slate.Transforms.setNodes(editor, {}, {
4054
3891
  match: slate.Text.isText,
@@ -4091,6 +3928,13 @@ const addDecoratorActionImplementation = ({
4091
3928
  };
4092
3929
  }
4093
3930
  }
3931
+ if (editor.selection) {
3932
+ const selection2 = editor.selection;
3933
+ editor.selection = {
3934
+ ...selection2
3935
+ };
3936
+ }
3937
+ }
4094
3938
  };
4095
3939
  function isDecoratorActive({
4096
3940
  editor,
@@ -4131,7 +3975,8 @@ const toggleDecoratorActionImplementation = ({
4131
3975
  decorator: action.decorator
4132
3976
  }
4133
3977
  });
4134
- }, debug$a = debugWithName("plugin:withPortableTextSelections"), debugVerbose$1 = debug$a.enabled && !1;
3978
+ };
3979
+ debugWithName("plugin:withPortableTextSelections");
4135
3980
  function createWithPortableTextSelections(editorActor, types2) {
4136
3981
  let prevSelection = null;
4137
3982
  return function(editor) {
@@ -4147,7 +3992,7 @@ function createWithPortableTextSelections(editorActor, types2) {
4147
3992
  ptRange = toPortableTextRange(value, editor.selection, types2), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
4148
3993
  }
4149
3994
  }
4150
- debugVerbose$1 && debug$a(`Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(editor.selection)})`), ptRange ? editorActor.send({
3995
+ ptRange ? editorActor.send({
4151
3996
  type: "selection",
4152
3997
  selection: ptRange
4153
3998
  }) : editorActor.send({
@@ -4160,10 +4005,9 @@ function createWithPortableTextSelections(editorActor, types2) {
4160
4005
  onChange
4161
4006
  } = editor;
4162
4007
  return editor.onChange = () => {
4163
- const hasChanges = editor.operations.length > 0;
4164
- onChange(), hasChanges && !editorActor.getSnapshot().matches({
4008
+ onChange(), editorActor.getSnapshot().matches({
4165
4009
  setup: "setting up"
4166
- }) && emitPortableTextSelection();
4010
+ }) || emitPortableTextSelection();
4167
4011
  }, editor;
4168
4012
  };
4169
4013
  }
@@ -5398,16 +5242,6 @@ const insertBlockObjectActionImplementation = ({
5398
5242
  const nextBlockPath = [action.editor.selection.focus.path.slice(0, 1)[0] + 1];
5399
5243
  slate.Transforms.select(action.editor, nextBlockPath);
5400
5244
  },
5401
- reselect: ({
5402
- action
5403
- }) => {
5404
- const selection = action.editor.selection;
5405
- selection && (slate.Transforms.select(action.editor, {
5406
- ...selection
5407
- }), action.editor.selection = {
5408
- ...selection
5409
- });
5410
- },
5411
5245
  "style.toggle": toggleStyleActionImplementation,
5412
5246
  "style.add": addStyleActionImplementation,
5413
5247
  "style.remove": removeStyleActionImplementation,
@@ -5419,6 +5253,27 @@ function performAction({
5419
5253
  action
5420
5254
  }) {
5421
5255
  switch (action.type) {
5256
+ case "annotation.toggle": {
5257
+ behaviorActionImplementations["annotation.toggle"]({
5258
+ context,
5259
+ action
5260
+ });
5261
+ break;
5262
+ }
5263
+ case "decorator.add": {
5264
+ behaviorActionImplementations["decorator.add"]({
5265
+ context,
5266
+ action
5267
+ });
5268
+ break;
5269
+ }
5270
+ case "decorator.remove": {
5271
+ behaviorActionImplementations["decorator.remove"]({
5272
+ context,
5273
+ action
5274
+ });
5275
+ break;
5276
+ }
5422
5277
  case "delete.block": {
5423
5278
  behaviorActionImplementations["delete.block"]({
5424
5279
  context,
@@ -5512,13 +5367,6 @@ function performAction({
5512
5367
  });
5513
5368
  break;
5514
5369
  }
5515
- case "reselect": {
5516
- behaviorActionImplementations.reselect({
5517
- context,
5518
- action
5519
- });
5520
- break;
5521
- }
5522
5370
  case "style.add": {
5523
5371
  behaviorActionImplementations["style.add"]({
5524
5372
  context,
@@ -5573,13 +5421,6 @@ function performDefaultAction({
5573
5421
  });
5574
5422
  break;
5575
5423
  }
5576
- case "annotation.toggle": {
5577
- behaviorActionImplementations["annotation.toggle"]({
5578
- context,
5579
- action
5580
- });
5581
- break;
5582
- }
5583
5424
  case "blur": {
5584
5425
  behaviorActionImplementations.blur({
5585
5426
  context,
@@ -5587,20 +5428,6 @@ function performDefaultAction({
5587
5428
  });
5588
5429
  break;
5589
5430
  }
5590
- case "decorator.add": {
5591
- behaviorActionImplementations["decorator.add"]({
5592
- context,
5593
- action
5594
- });
5595
- break;
5596
- }
5597
- case "decorator.remove": {
5598
- behaviorActionImplementations["decorator.remove"]({
5599
- context,
5600
- action
5601
- });
5602
- break;
5603
- }
5604
5431
  case "decorator.toggle": {
5605
5432
  behaviorActionImplementations["decorator.toggle"]({
5606
5433
  context,
@@ -5671,6 +5498,13 @@ function performDefaultAction({
5671
5498
  });
5672
5499
  break;
5673
5500
  }
5501
+ case "select": {
5502
+ behaviorActionImplementations.select({
5503
+ context,
5504
+ action
5505
+ });
5506
+ break;
5507
+ }
5674
5508
  default:
5675
5509
  behaviorActionImplementations["style.toggle"]({
5676
5510
  context,
@@ -5695,10 +5529,22 @@ const editorMachine = xstate.setup({
5695
5529
  input: {}
5696
5530
  },
5697
5531
  actions: {
5532
+ "add behavior to context": xstate.assign({
5533
+ behaviors: ({
5534
+ context,
5535
+ event
5536
+ }) => (xstate.assertEvent(event, "add behavior"), /* @__PURE__ */ new Set([...context.behaviors, event.behavior]))
5537
+ }),
5538
+ "remove behavior from context": xstate.assign({
5539
+ behaviors: ({
5540
+ context,
5541
+ event
5542
+ }) => (xstate.assertEvent(event, "remove behavior"), context.behaviors.delete(event.behavior), /* @__PURE__ */ new Set([...context.behaviors]))
5543
+ }),
5698
5544
  "assign behaviors": xstate.assign({
5699
5545
  behaviors: ({
5700
5546
  event
5701
- }) => (xstate.assertEvent(event, "update behaviors"), event.behaviors)
5547
+ }) => (xstate.assertEvent(event, "update behaviors"), new Set(event.behaviors))
5702
5548
  }),
5703
5549
  "assign schema": xstate.assign({
5704
5550
  schema: ({
@@ -5745,14 +5591,16 @@ const editorMachine = xstate.setup({
5745
5591
  const defaultAction = event.behaviorEvent.type === "copy" || event.behaviorEvent.type === "key.down" || event.behaviorEvent.type === "key.up" || event.behaviorEvent.type === "paste" ? void 0 : {
5746
5592
  ...event.behaviorEvent,
5747
5593
  editor: event.editor
5748
- }, eventBehaviors = context.behaviors.filter((behavior) => behavior.on === event.behaviorEvent.type);
5594
+ }, eventBehaviors = [...context.behaviors.values()].filter((behavior) => behavior.on === event.behaviorEvent.type);
5749
5595
  if (eventBehaviors.length === 0) {
5750
5596
  if (!defaultAction)
5751
5597
  return;
5752
- slate.Editor.withoutNormalizing(event.editor, () => {
5753
- performAction({
5754
- context,
5755
- action: defaultAction
5598
+ withApplyingBehaviorActions(event.editor, () => {
5599
+ slate.Editor.withoutNormalizing(event.editor, () => {
5600
+ performAction({
5601
+ context,
5602
+ action: defaultAction
5603
+ });
5756
5604
  });
5757
5605
  }), event.editor.onChange();
5758
5606
  return;
@@ -5780,21 +5628,28 @@ const editorMachine = xstate.setup({
5780
5628
  event: event.behaviorEvent
5781
5629
  }, shouldRun));
5782
5630
  for (const actionIntends of actionIntendSets)
5783
- behaviorOverwritten = behaviorOverwritten || actionIntends.length > 0 && actionIntends.some((actionIntend) => actionIntend.type !== "effect"), slate.Editor.withoutNormalizing(event.editor, () => {
5784
- for (const actionIntend of actionIntends) {
5785
- const action = {
5786
- ...actionIntend,
5787
- editor: event.editor
5788
- };
5789
- performAction({
5790
- context,
5791
- action
5792
- });
5793
- }
5794
- }), event.editor.onChange(), actionIntends.some((actionIntend) => actionIntend.type === "reselect") && enqueue.raise({
5795
- type: "selection",
5796
- selection: toPortableTextRange(event.editor.children, event.editor.selection, context.schema)
5797
- });
5631
+ behaviorOverwritten = behaviorOverwritten || actionIntends.length > 0 && actionIntends.some((actionIntend) => actionIntend.type !== "effect"), withApplyingBehaviorActions(event.editor, () => {
5632
+ slate.Editor.withoutNormalizing(event.editor, () => {
5633
+ for (const actionIntend of actionIntends) {
5634
+ if (actionIntend.type === "raise") {
5635
+ enqueue.raise({
5636
+ type: "behavior event",
5637
+ behaviorEvent: actionIntend.event,
5638
+ editor: event.editor
5639
+ });
5640
+ continue;
5641
+ }
5642
+ const action = {
5643
+ ...actionIntend,
5644
+ editor: event.editor
5645
+ };
5646
+ performAction({
5647
+ context,
5648
+ action
5649
+ });
5650
+ }
5651
+ });
5652
+ }), event.editor.onChange();
5798
5653
  if (behaviorOverwritten) {
5799
5654
  event.nativeEvent?.preventDefault();
5800
5655
  break;
@@ -5803,10 +5658,12 @@ const editorMachine = xstate.setup({
5803
5658
  if (!behaviorOverwritten) {
5804
5659
  if (!defaultAction)
5805
5660
  return;
5806
- slate.Editor.withoutNormalizing(event.editor, () => {
5807
- performAction({
5808
- context,
5809
- action: defaultAction
5661
+ withApplyingBehaviorActions(event.editor, () => {
5662
+ slate.Editor.withoutNormalizing(event.editor, () => {
5663
+ performAction({
5664
+ context,
5665
+ action: defaultAction
5666
+ });
5810
5667
  });
5811
5668
  }), event.editor.onChange();
5812
5669
  }
@@ -5817,7 +5674,7 @@ const editorMachine = xstate.setup({
5817
5674
  context: ({
5818
5675
  input
5819
5676
  }) => ({
5820
- behaviors: input.behaviors ?? behavior_core.coreBehaviors,
5677
+ behaviors: new Set(input.behaviors ?? behavior_core.coreBehaviors),
5821
5678
  keyGenerator: input.keyGenerator,
5822
5679
  pendingEvents: [],
5823
5680
  schema: input.schema,
@@ -5827,6 +5684,12 @@ const editorMachine = xstate.setup({
5827
5684
  value: input.value
5828
5685
  }),
5829
5686
  on: {
5687
+ "add behavior": {
5688
+ actions: "add behavior to context"
5689
+ },
5690
+ "remove behavior": {
5691
+ actions: "remove behavior from context"
5692
+ },
5830
5693
  unset: {
5831
5694
  actions: xstate.emit(({
5832
5695
  event
@@ -5947,17 +5810,7 @@ const editorMachine = xstate.setup({
5947
5810
  "behavior event": {
5948
5811
  actions: "handle behavior event"
5949
5812
  },
5950
- "annotation.add": {
5951
- actions: xstate.emit(({
5952
- event
5953
- }) => event)
5954
- },
5955
- "annotation.remove": {
5956
- actions: xstate.emit(({
5957
- event
5958
- }) => event)
5959
- },
5960
- "annotation.toggle": {
5813
+ "annotation.*": {
5961
5814
  actions: xstate.emit(({
5962
5815
  event
5963
5816
  }) => event)
@@ -5987,6 +5840,11 @@ const editorMachine = xstate.setup({
5987
5840
  event
5988
5841
  }) => event)
5989
5842
  },
5843
+ select: {
5844
+ actions: xstate.emit(({
5845
+ event
5846
+ }) => event)
5847
+ },
5990
5848
  "style.*": {
5991
5849
  actions: xstate.emit(({
5992
5850
  event
@@ -6157,6 +6015,15 @@ function createEditorFromActor(editorActor) {
6157
6015
  editorActorSnapshot: editorActor.getSnapshot(),
6158
6016
  slateEditorInstance: slateEditor.instance
6159
6017
  }),
6018
+ registerBehavior: (config) => (editorActor.send({
6019
+ type: "add behavior",
6020
+ behavior: config.behavior
6021
+ }), () => {
6022
+ editorActor.send({
6023
+ type: "remove behavior",
6024
+ behavior: config.behavior
6025
+ });
6026
+ }),
6160
6027
  send: (event) => {
6161
6028
  editorActor.send(event);
6162
6029
  },
@@ -6177,7 +6044,7 @@ const EditorActorContext = React.createContext({}), PortableTextEditorSelectionC
6177
6044
  if (selection === void 0)
6178
6045
  throw new Error("The `usePortableTextEditorSelection` hook must be used inside the <PortableTextEditor> component's context.");
6179
6046
  return selection;
6180
- }, debug$5 = debugWithName("component:PortableTextEditor:SelectionProvider"), debugVerbose = debug$5.enabled && !1;
6047
+ }, debug$5 = debugWithName("component:PortableTextEditor:SelectionProvider");
6181
6048
  function PortableTextEditorSelectionProvider(props) {
6182
6049
  const $ = reactCompilerRuntime.c(6), [selection, setSelection] = React.useState(null);
6183
6050
  let t0, t1;
@@ -6185,7 +6052,7 @@ function PortableTextEditorSelectionProvider(props) {
6185
6052
  debug$5("Subscribing to selection changes");
6186
6053
  const subscription = props.editorActor.on("selection", (event) => {
6187
6054
  React.startTransition(() => {
6188
- debugVerbose && debug$5("Setting selection"), setSelection(event.selection);
6055
+ setSelection(event.selection);
6189
6056
  });
6190
6057
  });
6191
6058
  return () => {
@@ -6381,23 +6248,19 @@ function RouteEventsToChanges(props) {
6381
6248
  });
6382
6249
  break bb5;
6383
6250
  }
6384
- case "annotation.add":
6385
- case "annotation.remove":
6386
- case "annotation.toggle":
6387
- case "blur":
6388
- case "decorator.add":
6389
- case "decorator.remove":
6390
- case "decorator.toggle":
6391
- case "focus":
6392
- case "insert.block object":
6393
- case "insert.inline object":
6394
- case "list item.toggle":
6395
- case "style.toggle":
6396
- case "patches":
6397
- case "editable":
6398
- case "read only":
6251
+ case "mutation": {
6252
+ handleChange(event);
6399
6253
  break bb5;
6400
- default:
6254
+ }
6255
+ case "ready": {
6256
+ handleChange(event);
6257
+ break bb5;
6258
+ }
6259
+ case "selection": {
6260
+ handleChange(event);
6261
+ break bb5;
6262
+ }
6263
+ case "unset":
6401
6264
  handleChange(event);
6402
6265
  }
6403
6266
  });
@@ -6530,17 +6393,9 @@ const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
6530
6393
  return React.useMemo(() => /* @__PURE__ */ jsxRuntime.jsx("span", { ...attributes, ref: spanRef, children: content }, leaf._key), [leaf, attributes, content]);
6531
6394
  };
6532
6395
  Leaf.displayName = "Leaf";
6533
- const debug$2 = debugWithName("plugin:withHotKeys"), DEFAULT_HOTKEYS = {
6534
- marks: {
6535
- "mod+b": "strong",
6536
- "mod+i": "em",
6537
- "mod+u": "underline",
6538
- "mod+'": "code"
6539
- },
6540
- custom: {}
6541
- };
6396
+ const debug$2 = debugWithName("plugin:withHotKeys");
6542
6397
  function createWithHotkeys(editorActor, portableTextEditor, hotkeysFromOptions) {
6543
- const reservedHotkeys = ["enter", "tab", "shift", "delete", "end"], activeHotkeys = hotkeysFromOptions || DEFAULT_HOTKEYS;
6398
+ const reservedHotkeys = ["enter", "tab", "shift", "delete", "end"], activeHotkeys = hotkeysFromOptions ?? {};
6544
6399
  return function(editor) {
6545
6400
  return editor.pteWithHotKeys = (event) => {
6546
6401
  Object.keys(activeHotkeys).forEach((cat) => {