@portabletext/editor 1.10.2 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var types = require("@sanity/types"), schema = require("@sanity/schema"), startCase = require("lodash.startcase"), jsxRuntime = require("react/jsx-runtime"), react$1 = require("@xstate/react"), isEqual = require("lodash/isEqual.js"), noop = require("lodash/noop.js"), react = require("react"), slate = require("slate"), slateReact = require("slate-react"), debug$m = require("debug"), reactCompilerRuntime = require("react-compiler-runtime"), styledComponents = require("styled-components"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), xstate = require("xstate"), throttle = require("lodash/throttle.js"), useEffectEvent = require("use-effect-event"), debounce = require("lodash/debounce.js"), 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"), getRandomValues = require("get-random-values-esm"), isHotkeyEsm = require("is-hotkey-esm"), blockTools = require("@sanity/block-tools");
3
+ var types = require("@sanity/types"), schema = require("@sanity/schema"), 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$m = require("debug"), reactCompilerRuntime = require("react-compiler-runtime"), styledComponents = require("styled-components"), uniq = require("lodash/uniq.js"), rxjs = require("rxjs"), useEffectEvent = require("use-effect-event"), throttle = require("lodash/throttle.js"), debounce = require("lodash/debounce.js"), patches = require("@portabletext/patches"), flatten = require("lodash/flatten.js"), isPlainObject = require("lodash/isPlainObject.js"), getRandomValues = require("get-random-values-esm"), xstate = require("xstate"), get = require("lodash/get.js"), isUndefined = require("lodash/isUndefined.js"), omitBy = require("lodash/omitBy.js"), isHotkeyEsm = require("is-hotkey-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), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$m), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), throttle__default = /* @__PURE__ */ _interopDefaultCompat(throttle), debounce__default = /* @__PURE__ */ _interopDefaultCompat(debounce), 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$m), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), throttle__default = /* @__PURE__ */ _interopDefaultCompat(throttle), debounce__default = /* @__PURE__ */ _interopDefaultCompat(debounce), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy);
8
8
  function defineBehavior(behavior) {
9
9
  return behavior;
10
10
  }
@@ -296,6 +296,65 @@ const breakingBlockObject = {
296
296
  blockObjects: coreBlockObjectBehaviors,
297
297
  lists: coreListBehaviors
298
298
  };
299
+ function createLinkBehaviors(config) {
300
+ const pasteLinkOnSelection = {
301
+ on: "paste",
302
+ guard: ({
303
+ context,
304
+ event
305
+ }) => {
306
+ const selectionCollapsed = selectionIsCollapsed(context), text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
307
+ url,
308
+ schema: context.schema
309
+ }) : void 0;
310
+ return annotation && !selectionCollapsed ? {
311
+ annotation
312
+ } : !1;
313
+ },
314
+ actions: [(_, {
315
+ annotation
316
+ }) => [{
317
+ type: "annotation.add",
318
+ annotation
319
+ }]]
320
+ }, pasteLinkAtCaret = {
321
+ on: "paste",
322
+ guard: ({
323
+ context,
324
+ event
325
+ }) => {
326
+ const focusSpan = getFocusSpan(context), selectionCollapsed = selectionIsCollapsed(context);
327
+ if (!focusSpan || !selectionCollapsed)
328
+ return !1;
329
+ const text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
330
+ url,
331
+ schema: context.schema
332
+ }) : void 0;
333
+ return url && annotation && selectionCollapsed ? {
334
+ focusSpan,
335
+ annotation,
336
+ url
337
+ } : !1;
338
+ },
339
+ actions: [(_, {
340
+ annotation,
341
+ url
342
+ }) => [{
343
+ type: "insert span",
344
+ text: url,
345
+ annotations: [annotation]
346
+ }]]
347
+ };
348
+ return [pasteLinkOnSelection, pasteLinkAtCaret];
349
+ }
350
+ function looksLikeUrl(text) {
351
+ let looksLikeUrl2 = !1;
352
+ try {
353
+ new URL(text), looksLikeUrl2 = !0;
354
+ } catch {
355
+ }
356
+ return looksLikeUrl2;
357
+ }
299
358
  function isPortableTextSpan(node) {
300
359
  return node._type === "span" && "text" in node && typeof node.text == "string" && (typeof node.marks > "u" || Array.isArray(node.marks) && node.marks.every((mark) => typeof mark == "string"));
301
360
  }
@@ -552,65 +611,6 @@ function createMarkdownBehaviors(config) {
552
611
  };
553
612
  return [automaticBlockquoteOnSpace, automaticBreak, automaticHeadingOnSpace, clearStyleOnBackspace, automaticListOnSpace];
554
613
  }
555
- function createLinkBehaviors(config) {
556
- const pasteLinkOnSelection = {
557
- on: "paste",
558
- guard: ({
559
- context,
560
- event
561
- }) => {
562
- const selectionCollapsed = selectionIsCollapsed(context), text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
563
- url,
564
- schema: context.schema
565
- }) : void 0;
566
- return annotation && !selectionCollapsed ? {
567
- annotation
568
- } : !1;
569
- },
570
- actions: [(_, {
571
- annotation
572
- }) => [{
573
- type: "annotation.add",
574
- annotation
575
- }]]
576
- }, pasteLinkAtCaret = {
577
- on: "paste",
578
- guard: ({
579
- context,
580
- event
581
- }) => {
582
- const focusSpan = getFocusSpan(context), selectionCollapsed = selectionIsCollapsed(context);
583
- if (!focusSpan || !selectionCollapsed)
584
- return !1;
585
- const text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
586
- url,
587
- schema: context.schema
588
- }) : void 0;
589
- return url && annotation && selectionCollapsed ? {
590
- focusSpan,
591
- annotation,
592
- url
593
- } : !1;
594
- },
595
- actions: [(_, {
596
- annotation,
597
- url
598
- }) => [{
599
- type: "insert span",
600
- text: url,
601
- annotations: [annotation]
602
- }]]
603
- };
604
- return [pasteLinkOnSelection, pasteLinkAtCaret];
605
- }
606
- function looksLikeUrl(text) {
607
- let looksLikeUrl2 = !1;
608
- try {
609
- new URL(text), looksLikeUrl2 = !0;
610
- } catch {
611
- }
612
- return looksLikeUrl2;
613
- }
614
614
  function getPortableTextMemberSchemaTypes(portableTextType) {
615
615
  if (!portableTextType)
616
616
  throw new Error("Parameter 'portabletextType' missing (required)");
@@ -1140,15 +1140,15 @@ const debug$l = debugWithName("components:DraggableBlock"), DraggableBlock = (t0
1140
1140
  element,
1141
1141
  readOnly,
1142
1142
  blockRef
1143
- } = t0, editor = slateReact.useSlateStatic(), dragGhostRef = react.useRef(), [isDragOver, setIsDragOver] = react.useState(!1);
1143
+ } = t0, editor = slateReact.useSlateStatic(), dragGhostRef = React.useRef(), [isDragOver, setIsDragOver] = React.useState(!1);
1144
1144
  let t1, t2;
1145
1145
  $[0] !== editor || $[1] !== element ? (t2 = slate.Editor.isVoid(editor, element), $[0] = editor, $[1] = element, $[2] = t2) : t2 = $[2], t1 = t2;
1146
1146
  const isVoid = t1;
1147
1147
  let t3, t4;
1148
1148
  $[3] !== editor || $[4] !== element ? (t4 = slate.Editor.isInline(editor, element), $[3] = editor, $[4] = element, $[5] = t4) : t4 = $[5], t3 = t4;
1149
- const isInline = t3, [blockElement, setBlockElement] = react.useState(null);
1149
+ const isInline = t3, [blockElement, setBlockElement] = React.useState(null);
1150
1150
  let t5, t6;
1151
- $[6] !== blockRef || $[7] !== editor || $[8] !== element ? (t5 = () => setBlockElement(blockRef ? blockRef.current : slateReact.ReactEditor.toDOMNode(editor, element)), t6 = [editor, element, blockRef], $[6] = blockRef, $[7] = editor, $[8] = element, $[9] = t5, $[10] = t6) : (t5 = $[9], t6 = $[10]), react.useEffect(t5, t6);
1151
+ $[6] !== blockRef || $[7] !== editor || $[8] !== element ? (t5 = () => setBlockElement(blockRef ? blockRef.current : slateReact.ReactEditor.toDOMNode(editor, element)), t6 = [editor, element, blockRef], $[6] = blockRef, $[7] = editor, $[8] = element, $[9] = t5, $[10] = t6) : (t5 = $[9], t6 = $[10]), React.useEffect(t5, t6);
1152
1152
  let t7;
1153
1153
  $[11] !== blockElement || $[12] !== editor || $[13] !== element ? (t7 = (event) => {
1154
1154
  const isMyDragOver = IS_DRAGGING_BLOCK_ELEMENT.get(editor);
@@ -1279,9 +1279,9 @@ const EMPTY_ANNOTATIONS = [], inlineBlockStyle = {
1279
1279
  renderStyle,
1280
1280
  spellCheck
1281
1281
  }) => {
1282
- const editor = slateReact.useSlateStatic(), selected = slateReact.useSelected(), blockRef = react.useRef(null), inlineBlockObjectRef = react.useRef(null), focused = selected && editor.selection && slate.Range.isCollapsed(editor.selection) || !1, value = react.useMemo(() => fromSlateValue([element], schemaTypes.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0], [editor, element, schemaTypes.block.name]);
1282
+ const editor = slateReact.useSlateStatic(), selected = slateReact.useSelected(), blockRef = React.useRef(null), inlineBlockObjectRef = React.useRef(null), focused = selected && editor.selection && slate.Range.isCollapsed(editor.selection) || !1, value = React.useMemo(() => fromSlateValue([element], schemaTypes.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0], [editor, element, schemaTypes.block.name]);
1283
1283
  let renderedBlock = children, className;
1284
- const blockPath = react.useMemo(() => [{
1284
+ const blockPath = React.useMemo(() => [{
1285
1285
  _key: element._key
1286
1286
  }], [element]);
1287
1287
  if (typeof element._type != "string")
@@ -1402,8 +1402,8 @@ const EMPTY_ANNOTATIONS = [], inlineBlockStyle = {
1402
1402
  ] }, element._key);
1403
1403
  };
1404
1404
  Element.displayName = "Element";
1405
- const PortableTextEditorContext = react.createContext(null), usePortableTextEditor = () => {
1406
- const editor = react.useContext(PortableTextEditorContext);
1405
+ const PortableTextEditorContext = React.createContext(null), usePortableTextEditor = () => {
1406
+ const editor = React.useContext(PortableTextEditorContext);
1407
1407
  if (!editor)
1408
1408
  throw new Error("The `usePortableTextEditor` hook must be used inside the <PortableTextEditor> component's context.");
1409
1409
  return editor;
@@ -2538,8 +2538,10 @@ function createWithUndoRedo(options) {
2538
2538
  apply: apply2
2539
2539
  } = editor;
2540
2540
  return editor.apply = (op) => {
2541
- if (editorActor.getSnapshot().context.readOnly)
2541
+ if (editorActor.getSnapshot().context.readOnly) {
2542
+ apply2(op);
2542
2543
  return;
2544
+ }
2543
2545
  if (isChangingRemotely(editor)) {
2544
2546
  apply2(op);
2545
2547
  return;
@@ -2752,19 +2754,20 @@ function useSyncValue(props) {
2752
2754
  const {
2753
2755
  editorActor,
2754
2756
  portableTextEditor,
2755
- readOnly
2756
- } = props, schemaTypes = editorActor.getSnapshot().context.schema, previousValue = react.useRef(), slateEditor = slateReact.useSlate(), updateValueFunctionRef = react.useRef(), updateFromCurrentValue = react.useCallback(() => {
2757
+ readOnly,
2758
+ slateEditor
2759
+ } = props, schemaTypes = editorActor.getSnapshot().context.schema, previousValue = React.useRef(), updateValueFunctionRef = React.useRef(), updateFromCurrentValue = React.useCallback(() => {
2757
2760
  const currentValue = CURRENT_VALUE.get(portableTextEditor);
2758
2761
  if (previousValue.current === currentValue) {
2759
2762
  debug$j("Value is the same object as previous, not need to sync");
2760
2763
  return;
2761
2764
  }
2762
2765
  updateValueFunctionRef.current && currentValue && (debug$j("Updating the value debounced"), updateValueFunctionRef.current(currentValue));
2763
- }, [portableTextEditor]), updateValueDebounced = react.useMemo(() => debounce__default.default(updateFromCurrentValue, 1e3, {
2766
+ }, [portableTextEditor]), updateValueDebounced = React.useMemo(() => debounce__default.default(updateFromCurrentValue, 1e3, {
2764
2767
  trailing: !0,
2765
2768
  leading: !1
2766
2769
  }), [updateFromCurrentValue]);
2767
- return react.useMemo(() => {
2770
+ return React.useMemo(() => {
2768
2771
  const updateFunction = (value) => {
2769
2772
  CURRENT_VALUE.set(portableTextEditor, value);
2770
2773
  const isProcessingLocalChanges = isChangingLocally(slateEditor), isProcessingRemoteChanges = isChangingRemotely(slateEditor);
@@ -2936,27 +2939,29 @@ function _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex) {
2936
2939
  }
2937
2940
  const debug$i = debugWithName("component:PortableTextEditor:Synchronizer"), debugVerbose$3 = debug$i.enabled && !1, FLUSH_PATCHES_THROTTLED_MS = process.env.NODE_ENV === "test" ? 500 : 1e3;
2938
2941
  function Synchronizer(props) {
2939
- const $ = reactCompilerRuntime.c(28), portableTextEditor = usePortableTextEditor(), readOnly = react$1.useSelector(props.editorActor, _temp$1), value = react$1.useSelector(props.editorActor, _temp2), {
2942
+ const $ = reactCompilerRuntime.c(26), readOnly = react.useSelector(props.editorActor, _temp), value = react.useSelector(props.editorActor, _temp2), {
2940
2943
  editorActor,
2941
2944
  getValue,
2942
- onChange
2945
+ portableTextEditor,
2946
+ slateEditor
2943
2947
  } = props;
2944
2948
  let t0;
2945
2949
  $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = [], $[0] = t0) : t0 = $[0];
2946
- const pendingPatches = react.useRef(t0);
2950
+ const pendingPatches = React.useRef(t0);
2947
2951
  let t1;
2948
- $[1] !== editorActor || $[2] !== portableTextEditor || $[3] !== readOnly ? (t1 = {
2952
+ $[1] !== editorActor || $[2] !== portableTextEditor || $[3] !== readOnly || $[4] !== slateEditor ? (t1 = {
2949
2953
  editorActor,
2950
2954
  portableTextEditor,
2951
- readOnly
2952
- }, $[1] = editorActor, $[2] = portableTextEditor, $[3] = readOnly, $[4] = t1) : t1 = $[4];
2953
- const syncValue = useSyncValue(t1), slateEditor = slateReact.useSlate();
2955
+ readOnly,
2956
+ slateEditor
2957
+ }, $[1] = editorActor, $[2] = portableTextEditor, $[3] = readOnly, $[4] = slateEditor, $[5] = t1) : t1 = $[5];
2958
+ const syncValue = useSyncValue(t1);
2954
2959
  let t2, t3;
2955
- $[5] !== slateEditor ? (t2 = () => {
2960
+ $[6] !== slateEditor ? (t2 = () => {
2956
2961
  IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !1);
2957
- }, t3 = [slateEditor], $[5] = slateEditor, $[6] = t2, $[7] = t3) : (t2 = $[6], t3 = $[7]), react.useEffect(t2, t3);
2962
+ }, t3 = [slateEditor], $[6] = slateEditor, $[7] = t2, $[8] = t3) : (t2 = $[7], t3 = $[8]), React.useEffect(t2, t3);
2958
2963
  let t4;
2959
- $[8] !== editorActor || $[9] !== getValue || $[10] !== slateEditor ? (t4 = () => {
2964
+ $[9] !== editorActor || $[10] !== getValue || $[11] !== slateEditor ? (t4 = () => {
2960
2965
  if (pendingPatches.current.length > 0) {
2961
2966
  debug$i("Flushing pending patches"), debugVerbose$3 && debug$i(`Patches:
2962
2967
  ${JSON.stringify(pendingPatches.current, null, 2)}`);
@@ -2968,17 +2973,14 @@ ${JSON.stringify(pendingPatches.current, null, 2)}`);
2968
2973
  }), pendingPatches.current = [];
2969
2974
  }
2970
2975
  IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !1);
2971
- }, $[8] = editorActor, $[9] = getValue, $[10] = slateEditor, $[11] = t4) : t4 = $[11];
2976
+ }, $[9] = editorActor, $[10] = getValue, $[11] = slateEditor, $[12] = t4) : t4 = $[12];
2972
2977
  const onFlushPendingPatches = t4;
2973
2978
  let t5, t6;
2974
- $[12] !== onFlushPendingPatches ? (t5 = () => () => {
2979
+ $[13] !== onFlushPendingPatches ? (t5 = () => () => {
2975
2980
  onFlushPendingPatches();
2976
- }, t6 = [onFlushPendingPatches], $[12] = onFlushPendingPatches, $[13] = t5, $[14] = t6) : (t5 = $[13], t6 = $[14]), react.useEffect(t5, t6);
2977
- let t7;
2978
- $[15] !== onChange ? (t7 = (change) => onChange(change), $[15] = onChange, $[16] = t7) : t7 = $[16];
2979
- const handleChange = useEffectEvent.useEffectEvent(t7);
2980
- let t8, t9;
2981
- $[17] !== editorActor || $[18] !== handleChange || $[19] !== onFlushPendingPatches || $[20] !== slateEditor ? (t8 = () => {
2981
+ }, t6 = [onFlushPendingPatches], $[13] = onFlushPendingPatches, $[14] = t5, $[15] = t6) : (t5 = $[14], t6 = $[15]), React.useEffect(t5, t6);
2982
+ let t7, t8;
2983
+ $[16] !== editorActor || $[17] !== onFlushPendingPatches || $[18] !== slateEditor ? (t7 = () => {
2982
2984
  const onFlushPendingPatchesThrottled = throttle__default.default(() => {
2983
2985
  if (slate.Editor.isNormalizing(slateEditor)) {
2984
2986
  onFlushPendingPatches();
@@ -2989,90 +2991,76 @@ ${JSON.stringify(pendingPatches.current, null, 2)}`);
2989
2991
  leading: !1,
2990
2992
  trailing: !0
2991
2993
  });
2992
- debug$i("Subscribing to editor changes");
2993
- const sub = editorActor.on("*", (event) => {
2994
- bb22: switch (event.type) {
2995
- case "patch": {
2996
- IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !0), pendingPatches.current.push(event.patch), onFlushPendingPatchesThrottled(), handleChange(event);
2997
- break bb22;
2998
- }
2999
- case "loading": {
3000
- handleChange({
3001
- type: "loading",
3002
- isLoading: !0
3003
- });
3004
- break bb22;
3005
- }
3006
- case "done loading": {
3007
- handleChange({
3008
- type: "loading",
3009
- isLoading: !1
3010
- });
3011
- break bb22;
3012
- }
3013
- case "focused": {
3014
- handleChange({
3015
- type: "focus",
3016
- event: event.event
3017
- });
3018
- break bb22;
3019
- }
3020
- case "value changed": {
3021
- handleChange({
3022
- type: "value",
3023
- value: event.value
3024
- });
3025
- break bb22;
3026
- }
3027
- case "invalid value": {
3028
- handleChange({
3029
- type: "invalidValue",
3030
- resolution: event.resolution,
3031
- value: event.value
3032
- });
3033
- break bb22;
3034
- }
3035
- case "error": {
3036
- handleChange({
3037
- ...event,
3038
- level: "warning"
3039
- });
3040
- break bb22;
3041
- }
3042
- case "annotation.add":
3043
- case "annotation.remove":
3044
- case "annotation.toggle":
3045
- case "focus":
3046
- case "patches":
3047
- break bb22;
3048
- default:
3049
- handleChange(event);
3050
- }
2994
+ debug$i("Subscribing to patch events");
2995
+ const sub = editorActor.on("patch", (event) => {
2996
+ IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !0), pendingPatches.current.push(event.patch), onFlushPendingPatchesThrottled();
3051
2997
  });
3052
2998
  return () => {
3053
- debug$i("Unsubscribing to changes"), sub.unsubscribe();
2999
+ debug$i("Unsubscribing to patch events"), sub.unsubscribe();
3054
3000
  };
3055
- }, t9 = [editorActor, handleChange, onFlushPendingPatches, slateEditor], $[17] = editorActor, $[18] = handleChange, $[19] = onFlushPendingPatches, $[20] = slateEditor, $[21] = t8, $[22] = t9) : (t8 = $[21], t9 = $[22]), react.useEffect(t8, t9);
3056
- const isInitialValueFromProps = react.useRef(!0);
3057
- let t10, t11;
3058
- return $[23] !== editorActor || $[24] !== syncValue || $[25] !== value ? (t10 = () => {
3001
+ }, t8 = [editorActor, onFlushPendingPatches, slateEditor], $[16] = editorActor, $[17] = onFlushPendingPatches, $[18] = slateEditor, $[19] = t7, $[20] = t8) : (t7 = $[19], t8 = $[20]), React.useEffect(t7, t8);
3002
+ const isInitialValueFromProps = React.useRef(!0);
3003
+ let t10, t9;
3004
+ return $[21] !== editorActor || $[22] !== syncValue || $[23] !== value ? (t9 = () => {
3059
3005
  debug$i("Value from props changed, syncing new value"), syncValue(value), isInitialValueFromProps.current && (editorActor.send({
3060
3006
  type: "ready"
3061
3007
  }), isInitialValueFromProps.current = !1);
3062
- }, t11 = [editorActor, syncValue, value], $[23] = editorActor, $[24] = syncValue, $[25] = value, $[26] = t10, $[27] = t11) : (t10 = $[26], t11 = $[27]), react.useEffect(t10, t11), null;
3008
+ }, t10 = [editorActor, syncValue, value], $[21] = editorActor, $[22] = syncValue, $[23] = value, $[24] = t10, $[25] = t9) : (t10 = $[24], t9 = $[25]), React.useEffect(t9, t10), null;
3063
3009
  }
3064
3010
  function _temp2(s_0) {
3065
3011
  return s_0.context.value;
3066
3012
  }
3067
- function _temp$1(s) {
3013
+ function _temp(s) {
3068
3014
  return s.context.readOnly;
3069
3015
  }
3070
3016
  Synchronizer.displayName = "Synchronizer";
3071
- const debug$h = debugWithName("operationToPatches");
3017
+ const EditorActorContext = React.createContext({}), PortableTextEditorSelectionContext = React.createContext(null), usePortableTextEditorSelection = () => {
3018
+ const selection = React.useContext(PortableTextEditorSelectionContext);
3019
+ if (selection === void 0)
3020
+ throw new Error("The `usePortableTextEditorSelection` hook must be used inside the <PortableTextEditor> component's context.");
3021
+ return selection;
3022
+ }, debug$h = debugWithName("component:PortableTextEditor:SelectionProvider"), debugVerbose$2 = debug$h.enabled && !1;
3023
+ function PortableTextEditorSelectionProvider(props) {
3024
+ const $ = reactCompilerRuntime.c(6), [selection, setSelection] = React.useState(null);
3025
+ let t0, t1;
3026
+ $[0] !== props.editorActor ? (t0 = () => {
3027
+ debug$h("Subscribing to selection changes");
3028
+ const subscription = props.editorActor.on("selection", (event) => {
3029
+ React.startTransition(() => {
3030
+ debugVerbose$2 && debug$h("Setting selection"), setSelection(event.selection);
3031
+ });
3032
+ });
3033
+ return () => {
3034
+ debug$h("Unsubscribing to selection changes"), subscription.unsubscribe();
3035
+ };
3036
+ }, t1 = [props.editorActor], $[0] = props.editorActor, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), React.useEffect(t0, t1);
3037
+ let t2;
3038
+ return $[3] !== props.children || $[4] !== selection ? (t2 = /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorSelectionContext.Provider, { value: selection, children: props.children }), $[3] = props.children, $[4] = selection, $[5] = t2) : t2 = $[5], t2;
3039
+ }
3040
+ const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
3041
+ let table;
3042
+ return () => {
3043
+ if (table)
3044
+ return table;
3045
+ table = [];
3046
+ for (let i = 0; i < 256; ++i)
3047
+ table[i] = (i + 256).toString(16).slice(1);
3048
+ return table;
3049
+ };
3050
+ })();
3051
+ function whatwgRNG(length = 16) {
3052
+ const rnds8 = new Uint8Array(length);
3053
+ return getRandomValues__default.default(rnds8), rnds8;
3054
+ }
3055
+ function randomKey(length) {
3056
+ const table = getByteHexTable();
3057
+ return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
3058
+ }
3059
+ const debug$g = debugWithName("operationToPatches");
3072
3060
  function createOperationToPatches(types2) {
3073
3061
  const textBlockName = types2.block.name;
3074
3062
  function insertTextPatch(editor, operation, beforeValue) {
3075
- debug$h.enabled && debug$h("Operation", JSON.stringify(operation, null, 2));
3063
+ debug$g.enabled && debug$g("Operation", JSON.stringify(operation, null, 2));
3076
3064
  const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
3077
3065
  if (!block)
3078
3066
  throw new Error("Could not find block");
@@ -3165,7 +3153,7 @@ function createOperationToPatches(types2) {
3165
3153
  _key: block.children[operation.path[1] - 1]._key
3166
3154
  }])];
3167
3155
  }
3168
- return debug$h("Something was inserted into a void block. Not producing editor patches."), [];
3156
+ return debug$g("Something was inserted into a void block. Not producing editor patches."), [];
3169
3157
  }
3170
3158
  function splitNodePatch(editor, operation, beforeValue) {
3171
3159
  const patches$1 = [], splitBlock = editor.children[operation.path[0]];
@@ -3223,9 +3211,9 @@ function createOperationToPatches(types2) {
3223
3211
  _key: block._key
3224
3212
  }, "children", {
3225
3213
  _key: spanToRemove._key
3226
- }])] : (debug$h("Span not found in editor trying to remove node"), []);
3214
+ }])] : (debug$g("Span not found in editor trying to remove node"), []);
3227
3215
  } else
3228
- return debug$h("Not creating patch inside object block"), [];
3216
+ return debug$g("Not creating patch inside object block"), [];
3229
3217
  }
3230
3218
  function mergeNodePatch(editor, operation, beforeValue) {
3231
3219
  const patches$1 = [], block = beforeValue[operation.path[0]], updatedBlock = editor.children[operation.path[0]];
@@ -3251,7 +3239,7 @@ function createOperationToPatches(types2) {
3251
3239
  _key: removedSpan._key
3252
3240
  }])) : console.warn(`Multiple spans have \`_key\` ${removedSpan._key}. It's ambiguous which one to remove.`, JSON.stringify(block, null, 2)));
3253
3241
  } else
3254
- debug$h("Void nodes can't be merged, not creating any patches");
3242
+ debug$g("Void nodes can't be merged, not creating any patches");
3255
3243
  return patches$1;
3256
3244
  }
3257
3245
  function moveNodePatch(editor, operation, beforeValue) {
@@ -3412,8 +3400,10 @@ function createWithMaxBlocks(editorActor) {
3412
3400
  apply: apply2
3413
3401
  } = editor;
3414
3402
  return editor.apply = (operation) => {
3415
- if (editorActor.getSnapshot().context.readOnly)
3403
+ if (editorActor.getSnapshot().context.readOnly) {
3404
+ apply2(operation);
3416
3405
  return;
3406
+ }
3417
3407
  if (isChangingRemotely(editor)) {
3418
3408
  apply2(operation);
3419
3409
  return;
@@ -3496,13 +3486,13 @@ function createWithObjectKeys(editorActor, schemaTypes) {
3496
3486
  }, editor;
3497
3487
  };
3498
3488
  }
3499
- const debug$g = debugWithName("applyPatches"), debugVerbose$2 = debug$g.enabled && !0;
3489
+ const debug$f = debugWithName("applyPatches"), debugVerbose$1 = debug$f.enabled && !0;
3500
3490
  function createApplyPatch(schemaTypes) {
3501
3491
  return (editor, patch) => {
3502
3492
  let changed = !1;
3503
- debugVerbose$2 && (debug$g(`
3493
+ debugVerbose$1 && (debug$f(`
3504
3494
 
3505
- NEW PATCH =============================================================`), debug$g(JSON.stringify(patch, null, 2)));
3495
+ NEW PATCH =============================================================`), debug$f(JSON.stringify(patch, null, 2)));
3506
3496
  try {
3507
3497
  switch (patch.type) {
3508
3498
  case "insert":
@@ -3518,7 +3508,7 @@ NEW PATCH =============================================================`), debug
3518
3508
  changed = diffMatchPatch(editor, patch);
3519
3509
  break;
3520
3510
  default:
3521
- debug$g("Unhandled patch", patch.type);
3511
+ debug$f("Unhandled patch", patch.type);
3522
3512
  }
3523
3513
  } catch (err) {
3524
3514
  console.error(err);
@@ -3533,9 +3523,9 @@ function diffMatchPatch(editor, patch) {
3533
3523
  childPath
3534
3524
  } = findBlockAndChildFromPath(editor, patch.path);
3535
3525
  if (!block)
3536
- return debug$g("Block not found"), !1;
3526
+ return debug$f("Block not found"), !1;
3537
3527
  if (!child || !childPath)
3538
- return debug$g("Child not found"), !1;
3528
+ return debug$f("Child not found"), !1;
3539
3529
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
3540
3530
  return !1;
3541
3531
  const patches2 = parse(patch.value), [newValue] = apply(patches2, child.text, {
@@ -3565,9 +3555,9 @@ function insertPatch(editor, patch, schemaTypes) {
3565
3555
  childPath: targetChildPath
3566
3556
  } = findBlockAndChildFromPath(editor, patch.path);
3567
3557
  if (!targetBlock || !targetBlockPath)
3568
- return debug$g("Block not found"), !1;
3558
+ return debug$f("Block not found"), !1;
3569
3559
  if (patch.path.length > 1 && patch.path[1] !== "children")
3570
- return debug$g("Ignoring patch targeting void value"), !1;
3560
+ return debug$f("Ignoring patch targeting void value"), !1;
3571
3561
  if (patch.path.length === 1) {
3572
3562
  const {
3573
3563
  items: items2,
@@ -3575,7 +3565,7 @@ function insertPatch(editor, patch, schemaTypes) {
3575
3565
  } = patch, blocksToInsert = toSlateValue(items2, {
3576
3566
  schemaTypes
3577
3567
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetBlockIndex = targetBlockPath[0], normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex;
3578
- return debug$g(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
3568
+ return debug$f(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
3579
3569
  at: [normalizedIdx2]
3580
3570
  }), debugState(editor, "after"), !0;
3581
3571
  }
@@ -3584,14 +3574,14 @@ function insertPatch(editor, patch, schemaTypes) {
3584
3574
  position
3585
3575
  } = patch;
3586
3576
  if (!targetChild || !targetChildPath)
3587
- return debug$g("Child not found"), !1;
3577
+ return debug$f("Child not found"), !1;
3588
3578
  const childrenToInsert = targetBlock && toSlateValue([{
3589
3579
  ...targetBlock,
3590
3580
  children: items
3591
3581
  }], {
3592
3582
  schemaTypes
3593
3583
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetChildIndex = targetChildPath[1], normalizedIdx = position === "after" ? targetChildIndex + 1 : targetChildIndex, childInsertPath = [targetChildPath[0], normalizedIdx];
3594
- return debug$g(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
3584
+ return debug$f(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
3595
3585
  at: childInsertPath
3596
3586
  }), debugState(editor, "after"), !0;
3597
3587
  }
@@ -3605,14 +3595,14 @@ function setPatch(editor, patch) {
3605
3595
  childPath
3606
3596
  } = findBlockAndChildFromPath(editor, patch.path);
3607
3597
  if (!block)
3608
- return debug$g("Block not found"), !1;
3598
+ return debug$f("Block not found"), !1;
3609
3599
  const isTextBlock = editor.isTextBlock(block);
3610
3600
  if (isTextBlock && patch.path.length > 1 && patch.path[1] !== "children")
3611
- return debug$g("Ignoring setting void value"), !1;
3601
+ return debug$f("Ignoring setting void value"), !1;
3612
3602
  if (debugState(editor, "before"), isTextBlock && child && childPath) {
3613
3603
  if (slate.Text.isText(value) && slate.Text.isText(child)) {
3614
3604
  const newText = child.text;
3615
- value.text !== newText && (debug$g("Setting text property"), editor.apply({
3605
+ value.text !== newText && (debug$f("Setting text property"), editor.apply({
3616
3606
  type: "remove_text",
3617
3607
  path: childPath,
3618
3608
  offset: 0,
@@ -3624,7 +3614,7 @@ function setPatch(editor, patch) {
3624
3614
  text: value.text
3625
3615
  }), editor.onChange());
3626
3616
  } else
3627
- debug$g("Setting non-text property"), editor.apply({
3617
+ debug$f("Setting non-text property"), editor.apply({
3628
3618
  type: "set_node",
3629
3619
  path: childPath,
3630
3620
  properties: {},
@@ -3632,7 +3622,7 @@ function setPatch(editor, patch) {
3632
3622
  });
3633
3623
  return !0;
3634
3624
  } else if (slate.Element.isElement(block) && patch.path.length === 1 && blockPath) {
3635
- debug$g("Setting block property");
3625
+ debug$f("Setting block property");
3636
3626
  const {
3637
3627
  children,
3638
3628
  ...nextRest
@@ -3649,7 +3639,7 @@ function setPatch(editor, patch) {
3649
3639
  ...prevRest
3650
3640
  },
3651
3641
  newProperties: nextRest
3652
- }), debug$g("Setting children"), block.children.forEach((c, cIndex) => {
3642
+ }), debug$f("Setting children"), block.children.forEach((c, cIndex) => {
3653
3643
  editor.apply({
3654
3644
  type: "remove_node",
3655
3645
  path: blockPath.concat(block.children.length - 1 - cIndex),
@@ -3675,7 +3665,7 @@ function setPatch(editor, patch) {
3675
3665
  }
3676
3666
  function unsetPatch(editor, patch) {
3677
3667
  if (patch.path.length === 0) {
3678
- debug$g("Removing everything"), debugState(editor, "before");
3668
+ debug$f("Removing everything"), debugState(editor, "before");
3679
3669
  const previousSelection = editor.selection;
3680
3670
  return slate.Transforms.deselect(editor), editor.children.forEach((_child, i) => {
3681
3671
  slate.Transforms.removeNodes(editor, {
@@ -3702,13 +3692,13 @@ function unsetPatch(editor, patch) {
3702
3692
  } = findBlockAndChildFromPath(editor, patch.path);
3703
3693
  if (patch.path.length === 1) {
3704
3694
  if (!block || !blockPath)
3705
- return debug$g("Block not found"), !1;
3695
+ return debug$f("Block not found"), !1;
3706
3696
  const blockIndex = blockPath[0];
3707
- return debug$g(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
3697
+ return debug$f(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
3708
3698
  at: [blockIndex]
3709
3699
  }), debugState(editor, "after"), !0;
3710
3700
  }
3711
- return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$g("Child not found"), !1) : (debug$g(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose$2 && debug$g(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
3701
+ 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$1 && debug$f(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
3712
3702
  at: childPath
3713
3703
  }), debugState(editor, "after"), !0) : !1;
3714
3704
  }
@@ -3716,7 +3706,7 @@ function isKeyedSegment(segment) {
3716
3706
  return typeof segment == "object" && "_key" in segment;
3717
3707
  }
3718
3708
  function debugState(editor, stateName) {
3719
- debugVerbose$2 && (debug$g(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$g(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3709
+ debugVerbose$1 && (debug$f(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$f(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3720
3710
  }
3721
3711
  function findBlockFromPath(editor, path) {
3722
3712
  let blockIndex = -1;
@@ -3758,7 +3748,7 @@ function findBlockAndChildFromPath(editor, path) {
3758
3748
  childPath: void 0
3759
3749
  };
3760
3750
  }
3761
- const debug$f = debugWithName("plugin:withPatches");
3751
+ const debug$e = debugWithName("plugin:withPatches");
3762
3752
  function createWithPatches({
3763
3753
  editorActor,
3764
3754
  patchFunctions,
@@ -3784,7 +3774,7 @@ function createWithPatches({
3784
3774
  withoutPatching(editor, () => {
3785
3775
  withoutSaving(editor, () => {
3786
3776
  patches2.forEach((patch) => {
3787
- debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3777
+ debug$e.enabled && debug$e(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3788
3778
  });
3789
3779
  });
3790
3780
  });
@@ -3797,10 +3787,10 @@ function createWithPatches({
3797
3787
  remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
3798
3788
  };
3799
3789
  return subscriptions.push(() => {
3800
- debug$f("Subscribing to remote patches");
3790
+ debug$e("Subscribing to remote patches");
3801
3791
  const sub = editorActor.on("patches", handlePatches);
3802
3792
  return () => {
3803
- debug$f("Unsubscribing to remote patches"), sub.unsubscribe();
3793
+ debug$e("Unsubscribing to remote patches"), sub.unsubscribe();
3804
3794
  };
3805
3795
  }), editor.apply = (operation) => {
3806
3796
  if (editorActor.getSnapshot().context.readOnly)
@@ -3853,37 +3843,39 @@ function createWithPatches({
3853
3843
  }, editor;
3854
3844
  };
3855
3845
  }
3856
- const debug$e = debugWithName("plugin:withPlaceholderBlock");
3846
+ const debug$d = debugWithName("plugin:withPlaceholderBlock");
3857
3847
  function createWithPlaceholderBlock(editorActor) {
3858
3848
  return function(editor) {
3859
3849
  const {
3860
3850
  apply: apply2
3861
3851
  } = editor;
3862
3852
  return editor.apply = (op) => {
3863
- if (!editorActor.getSnapshot().context.readOnly) {
3864
- if (isChangingRemotely(editor)) {
3865
- apply2(op);
3866
- return;
3867
- }
3868
- if (isUndoing(editor) || isRedoing(editor)) {
3869
- apply2(op);
3870
- return;
3871
- }
3872
- if (op.type === "remove_node") {
3873
- const node = op.node;
3874
- if (op.path[0] === 0 && slate.Editor.isVoid(editor, node)) {
3875
- const nextPath = slate.Path.next(op.path);
3876
- editor.children[nextPath[0]] || (debug$e("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
3877
- decorators: []
3878
- })));
3879
- }
3880
- }
3853
+ if (editorActor.getSnapshot().context.readOnly) {
3854
+ apply2(op);
3855
+ return;
3856
+ }
3857
+ if (isChangingRemotely(editor)) {
3881
3858
  apply2(op);
3859
+ return;
3860
+ }
3861
+ if (isUndoing(editor) || isRedoing(editor)) {
3862
+ apply2(op);
3863
+ return;
3864
+ }
3865
+ if (op.type === "remove_node") {
3866
+ const node = op.node;
3867
+ if (op.path[0] === 0 && slate.Editor.isVoid(editor, node)) {
3868
+ const nextPath = slate.Path.next(op.path);
3869
+ editor.children[nextPath[0]] || (debug$d("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
3870
+ decorators: []
3871
+ })));
3872
+ }
3882
3873
  }
3874
+ apply2(op);
3883
3875
  }, editor;
3884
3876
  };
3885
3877
  }
3886
- const debug$d = debugWithName("plugin:withPortableTextBlockStyle");
3878
+ const debug$c = debugWithName("plugin:withPortableTextBlockStyle");
3887
3879
  function createWithPortableTextBlockStyle(editorActor, types2) {
3888
3880
  const defaultStyle = types2.styles[0].value;
3889
3881
  return function(editor) {
@@ -3896,7 +3888,7 @@ function createWithPortableTextBlockStyle(editorActor, types2) {
3896
3888
  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)) {
3897
3889
  const [child] = slate.Editor.node(editor, [op.path[0] + 1, 0]);
3898
3890
  if (slate.Text.isText(child) && child.text === "") {
3899
- debug$d(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3891
+ debug$c(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3900
3892
  type: "normalizing"
3901
3893
  }), slate.Transforms.setNodes(editor, {
3902
3894
  style: defaultStyle
@@ -3918,12 +3910,12 @@ function createWithPortableTextBlockStyle(editorActor, types2) {
3918
3910
  at: editor.selection,
3919
3911
  match: (node) => editor.isTextBlock(node)
3920
3912
  })].forEach(([node, path]) => {
3921
- editor.isTextBlock(node) && node.style === blockStyle ? (debug$d(`Unsetting block style '${blockStyle}'`), slate.Transforms.setNodes(editor, {
3913
+ editor.isTextBlock(node) && node.style === blockStyle ? (debug$c(`Unsetting block style '${blockStyle}'`), slate.Transforms.setNodes(editor, {
3922
3914
  ...node,
3923
3915
  style: defaultStyle
3924
3916
  }, {
3925
3917
  at: path
3926
- })) : (blockStyle ? debug$d(`Setting style '${blockStyle}'`) : debug$d("Setting default style", defaultStyle), slate.Transforms.setNodes(editor, {
3918
+ })) : (blockStyle ? debug$c(`Setting style '${blockStyle}'`) : debug$c("Setting default style", defaultStyle), slate.Transforms.setNodes(editor, {
3927
3919
  ...node,
3928
3920
  style: blockStyle || defaultStyle
3929
3921
  }, {
@@ -3933,11 +3925,11 @@ function createWithPortableTextBlockStyle(editorActor, types2) {
3933
3925
  }, editor;
3934
3926
  };
3935
3927
  }
3936
- const debug$c = debugWithName("plugin:withPortableTextLists"), MAX_LIST_LEVEL = 10;
3928
+ const debug$b = debugWithName("plugin:withPortableTextLists"), MAX_LIST_LEVEL = 10;
3937
3929
  function createWithPortableTextLists(types2) {
3938
3930
  return function(editor) {
3939
3931
  return editor.pteToggleListItem = (listItemStyle) => {
3940
- editor.pteHasListStyle(listItemStyle) ? (debug$c(`Remove list item '${listItemStyle}'`), editor.pteUnsetListItem(listItemStyle)) : (debug$c(`Add list item '${listItemStyle}'`), editor.pteSetListItem(listItemStyle));
3932
+ editor.pteHasListStyle(listItemStyle) ? (debug$b(`Remove list item '${listItemStyle}'`), editor.pteUnsetListItem(listItemStyle)) : (debug$b(`Add list item '${listItemStyle}'`), editor.pteSetListItem(listItemStyle));
3941
3933
  }, editor.pteUnsetListItem = (listItemStyle) => {
3942
3934
  editor.selection && [...slate.Editor.nodes(editor, {
3943
3935
  at: editor.selection,
@@ -3953,7 +3945,7 @@ function createWithPortableTextLists(types2) {
3953
3945
  listItem: void 0,
3954
3946
  level: void 0
3955
3947
  };
3956
- debug$c(`Unsetting list '${listItemStyle}'`), slate.Transforms.setNodes(editor, newNode, {
3948
+ debug$b(`Unsetting list '${listItemStyle}'`), slate.Transforms.setNodes(editor, newNode, {
3957
3949
  at: path
3958
3950
  });
3959
3951
  }
@@ -3963,7 +3955,7 @@ function createWithPortableTextLists(types2) {
3963
3955
  at: editor.selection,
3964
3956
  match: (node) => editor.isTextBlock(node)
3965
3957
  })].forEach(([node, path]) => {
3966
- debug$c(`Setting list '${listItemStyle}'`), slate.Transforms.setNodes(editor, {
3958
+ debug$b(`Setting list '${listItemStyle}'`), slate.Transforms.setNodes(editor, {
3967
3959
  ...node,
3968
3960
  level: 1,
3969
3961
  listItem: listItemStyle || types2.lists[0] && types2.lists[0].value
@@ -3979,7 +3971,7 @@ function createWithPortableTextLists(types2) {
3979
3971
  match: (node) => slate.Element.isElement(node) && editor.isListBlock(node) && node.children.length === 1 && slate.Text.isText(node.children[0]) && node.children[0].text === ""
3980
3972
  })];
3981
3973
  return selectedBlocks.length === 0 ? !1 : (selectedBlocks.forEach(([node, path]) => {
3982
- slate.Element.isElement(node) && (debug$c("Unset list"), slate.Transforms.setNodes(editor, {
3974
+ slate.Element.isElement(node) && (debug$b("Unset list"), slate.Transforms.setNodes(editor, {
3983
3975
  ...node,
3984
3976
  level: void 0,
3985
3977
  listItem: void 0
@@ -3997,7 +3989,7 @@ function createWithPortableTextLists(types2) {
3997
3989
  return selectedBlocks.length === 0 ? !1 : (selectedBlocks.forEach(([node, path]) => {
3998
3990
  if (editor.isListBlock(node)) {
3999
3991
  let level = node.level || 1;
4000
- reverse ? (level--, debug$c("Decrementing list level", Math.min(MAX_LIST_LEVEL, Math.max(1, level)))) : (level++, debug$c("Incrementing list level", Math.min(MAX_LIST_LEVEL, Math.max(1, level)))), slate.Transforms.setNodes(editor, {
3992
+ reverse ? (level--, debug$b("Decrementing list level", Math.min(MAX_LIST_LEVEL, Math.max(1, level)))) : (level++, debug$b("Incrementing list level", Math.min(MAX_LIST_LEVEL, Math.max(1, level)))), slate.Transforms.setNodes(editor, {
4001
3993
  level: Math.min(MAX_LIST_LEVEL, Math.max(1, level))
4002
3994
  }, {
4003
3995
  at: path
@@ -4043,7 +4035,7 @@ function getNextSpan({
4043
4035
  }
4044
4036
  return nextSpan;
4045
4037
  }
4046
- const debug$b = debugWithName("plugin:withPortableTextMarkModel");
4038
+ const debug$a = debugWithName("plugin:withPortableTextMarkModel");
4047
4039
  function createWithPortableTextMarkModel(editorActor, types2) {
4048
4040
  return function(editor) {
4049
4041
  const {
@@ -4057,7 +4049,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4057
4049
  for (const [child, childPath] of children) {
4058
4050
  const nextNode = node.children[childPath[1] + 1];
4059
4051
  if (editor.isTextSpan(child) && editor.isTextSpan(nextNode) && child.marks?.every((mark) => nextNode.marks?.includes(mark)) && nextNode.marks?.every((mark) => child.marks?.includes(mark))) {
4060
- debug$b("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
4052
+ debug$a("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
4061
4053
  type: "normalizing"
4062
4054
  }), slate.Transforms.mergeNodes(editor, {
4063
4055
  at: [childPath[0], childPath[1] + 1],
@@ -4070,7 +4062,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4070
4062
  }
4071
4063
  }
4072
4064
  if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {
4073
- debug$b("Adding .markDefs to block node"), editorActor.send({
4065
+ debug$a("Adding .markDefs to block node"), editorActor.send({
4074
4066
  type: "normalizing"
4075
4067
  }), slate.Transforms.setNodes(editor, {
4076
4068
  markDefs: []
@@ -4082,7 +4074,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4082
4074
  return;
4083
4075
  }
4084
4076
  if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {
4085
- debug$b("Adding .marks to span node"), editorActor.send({
4077
+ debug$a("Adding .marks to span node"), editorActor.send({
4086
4078
  type: "normalizing"
4087
4079
  }), slate.Transforms.setNodes(editor, {
4088
4080
  marks: []
@@ -4096,7 +4088,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4096
4088
  if (editor.isTextSpan(node)) {
4097
4089
  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));
4098
4090
  if (editor.isTextBlock(block) && node.text === "" && annotations && annotations.length > 0) {
4099
- debug$b("Removing annotations from empty span node"), editorActor.send({
4091
+ debug$a("Removing annotations from empty span node"), editorActor.send({
4100
4092
  type: "normalizing"
4101
4093
  }), slate.Transforms.setNodes(editor, {
4102
4094
  marks: node.marks?.filter((mark) => decorators2.includes(mark))
@@ -4114,7 +4106,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4114
4106
  if (editor.isTextSpan(child)) {
4115
4107
  const marks = child.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !node.markDefs?.find((def) => def._key === mark));
4116
4108
  if (orphanedAnnotations.length > 0) {
4117
- debug$b("Removing orphaned annotations from span node"), editorActor.send({
4109
+ debug$a("Removing orphaned annotations from span node"), editorActor.send({
4118
4110
  type: "normalizing"
4119
4111
  }), slate.Transforms.setNodes(editor, {
4120
4112
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
@@ -4132,7 +4124,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4132
4124
  if (editor.isTextBlock(block)) {
4133
4125
  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));
4134
4126
  if (orphanedAnnotations.length > 0) {
4135
- debug$b("Removing orphaned annotations from span node"), editorActor.send({
4127
+ debug$a("Removing orphaned annotations from span node"), editorActor.send({
4136
4128
  type: "normalizing"
4137
4129
  }), slate.Transforms.setNodes(editor, {
4138
4130
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
@@ -4150,7 +4142,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4150
4142
  for (const markDef of markDefs)
4151
4143
  markDefKeys.has(markDef._key) || (markDefKeys.add(markDef._key), newMarkDefs.push(markDef));
4152
4144
  if (markDefs.length !== newMarkDefs.length) {
4153
- debug$b("Removing duplicate markDefs"), editorActor.send({
4145
+ debug$a("Removing duplicate markDefs"), editorActor.send({
4154
4146
  type: "normalizing"
4155
4147
  }), slate.Transforms.setNodes(editor, {
4156
4148
  markDefs: newMarkDefs
@@ -4165,7 +4157,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4165
4157
  if (editor.isTextBlock(node) && !editor.operations.some((op) => op.type === "merge_node" && "markDefs" in op.properties && op.path.length === 1)) {
4166
4158
  const newMarkDefs = (node.markDefs || []).filter((def) => node.children.find((child) => slate.Text.isText(child) && Array.isArray(child.marks) && child.marks.includes(def._key)));
4167
4159
  if (node.markDefs && !isEqual__default.default(newMarkDefs, node.markDefs)) {
4168
- debug$b("Removing markDef not in use"), editorActor.send({
4160
+ debug$a("Removing markDef not in use"), editorActor.send({
4169
4161
  type: "normalizing"
4170
4162
  }), slate.Transforms.setNodes(editor, {
4171
4163
  markDefs: newMarkDefs
@@ -4382,7 +4374,7 @@ function createWithPortableTextMarkModel(editorActor, types2) {
4382
4374
  const [targetBlock, targetPath] = slate.Editor.node(editor, [op.path[0] - 1]);
4383
4375
  if (editor.isTextBlock(targetBlock)) {
4384
4376
  const oldDefs = Array.isArray(targetBlock.markDefs) && targetBlock.markDefs || [], newMarkDefs = uniq__default.default([...oldDefs, ...op.properties.markDefs]);
4385
- debug$b("Copying markDefs over to merged block", op), slate.Transforms.setNodes(editor, {
4377
+ debug$a("Copying markDefs over to merged block", op), slate.Transforms.setNodes(editor, {
4386
4378
  markDefs: newMarkDefs
4387
4379
  }, {
4388
4380
  at: targetPath,
@@ -4534,7 +4526,7 @@ const toggleDecoratorActionImplementation = ({
4534
4526
  decorator: action.decorator
4535
4527
  }
4536
4528
  });
4537
- }, debug$a = debugWithName("plugin:withPortableTextSelections"), debugVerbose$1 = debug$a.enabled && !1;
4529
+ }, debug$9 = debugWithName("plugin:withPortableTextSelections"), debugVerbose = debug$9.enabled && !1;
4538
4530
  function createWithPortableTextSelections(editorActor, types2) {
4539
4531
  let prevSelection = null;
4540
4532
  return function(editor) {
@@ -4550,7 +4542,7 @@ function createWithPortableTextSelections(editorActor, types2) {
4550
4542
  ptRange = toPortableTextRange(value, editor.selection, types2), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
4551
4543
  }
4552
4544
  }
4553
- debugVerbose$1 && debug$a(`Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(editor.selection)})`), ptRange ? editorActor.send({
4545
+ debugVerbose && debug$9(`Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(editor.selection)})`), ptRange ? editorActor.send({
4554
4546
  type: "selection",
4555
4547
  selection: ptRange
4556
4548
  }) : editorActor.send({
@@ -4568,7 +4560,7 @@ function createWithPortableTextSelections(editorActor, types2) {
4568
4560
  }, editor;
4569
4561
  };
4570
4562
  }
4571
- const debug$9 = debugWithName("plugin:withSchemaTypes");
4563
+ const debug$8 = debugWithName("plugin:withSchemaTypes");
4572
4564
  function createWithSchemaTypes({
4573
4565
  editorActor,
4574
4566
  schemaTypes
@@ -4581,7 +4573,7 @@ function createWithSchemaTypes({
4581
4573
  return editor.normalizeNode = (entry) => {
4582
4574
  const [node, path] = entry;
4583
4575
  if (node._type === void 0 && path.length === 2) {
4584
- debug$9("Setting span type on text node without a type");
4576
+ debug$8("Setting span type on text node without a type");
4585
4577
  const span = node, key = span._key || editorActor.getSnapshot().context.keyGenerator();
4586
4578
  editorActor.send({
4587
4579
  type: "normalizing"
@@ -4597,7 +4589,7 @@ function createWithSchemaTypes({
4597
4589
  return;
4598
4590
  }
4599
4591
  if (node._key === void 0 && (path.length === 1 || path.length === 2)) {
4600
- debug$9("Setting missing key on child node without a key");
4592
+ debug$8("Setting missing key on child node without a key");
4601
4593
  const key = editorActor.getSnapshot().context.keyGenerator();
4602
4594
  editorActor.send({
4603
4595
  type: "normalizing"
@@ -4614,7 +4606,7 @@ function createWithSchemaTypes({
4614
4606
  }, editor;
4615
4607
  };
4616
4608
  }
4617
- const debug$8 = debugWithName("plugin:withUtils");
4609
+ const debug$7 = debugWithName("plugin:withUtils");
4618
4610
  function createWithUtils({
4619
4611
  editorActor,
4620
4612
  schemaTypes
@@ -4629,14 +4621,14 @@ function createWithUtils({
4629
4621
  depth: 2
4630
4622
  });
4631
4623
  if (!textNode || !slate.Text.isText(textNode) || textNode.text.length === 0) {
4632
- debug$8("pteExpandToWord: Can't expand to word here");
4624
+ debug$7("pteExpandToWord: Can't expand to word here");
4633
4625
  return;
4634
4626
  }
4635
4627
  const {
4636
4628
  focus
4637
4629
  } = selection, focusOffset = focus.offset, charsBefore = textNode.text.slice(0, focusOffset), charsAfter = textNode.text.slice(focusOffset, -1), isEmpty = (str) => str.match(/\s/g), whiteSpaceBeforeIndex = charsBefore.split("").reverse().findIndex((str) => isEmpty(str)), newStartOffset = whiteSpaceBeforeIndex > -1 ? charsBefore.length - whiteSpaceBeforeIndex : 0, whiteSpaceAfterIndex = charsAfter.split("").findIndex((obj) => isEmpty(obj)), newEndOffset = charsBefore.length + (whiteSpaceAfterIndex > -1 ? whiteSpaceAfterIndex : charsAfter.length + 1);
4638
4630
  if (!(newStartOffset === newEndOffset || Number.isNaN(newStartOffset) || Number.isNaN(newEndOffset))) {
4639
- debug$8("pteExpandToWord: Expanding to focused word"), slate.Transforms.setSelection(editor, {
4631
+ debug$7("pteExpandToWord: Expanding to focused word"), slate.Transforms.setSelection(editor, {
4640
4632
  anchor: {
4641
4633
  ...selection.anchor,
4642
4634
  offset: newStartOffset
@@ -4648,7 +4640,7 @@ function createWithUtils({
4648
4640
  });
4649
4641
  return;
4650
4642
  }
4651
- debug$8("pteExpandToWord: Can't expand to word here");
4643
+ debug$7("pteExpandToWord: Can't expand to word here");
4652
4644
  }
4653
4645
  }, editor.pteCreateTextBlock = (options) => toSlateValue([{
4654
4646
  _type: schemaTypes.block.name,
@@ -4674,16 +4666,10 @@ function createWithUtils({
4674
4666
  })[0], editor;
4675
4667
  };
4676
4668
  }
4677
- const originalFnMap = /* @__PURE__ */ new WeakMap(), withPlugins = (editor, options) => {
4669
+ const withPlugins = (editor, options) => {
4678
4670
  const e = editor, {
4679
4671
  editorActor
4680
- } = options, schemaTypes = editorActor.getSnapshot().context.schema;
4681
- e.destroy ? e.destroy() : originalFnMap.set(e, {
4682
- apply: e.apply,
4683
- onChange: e.onChange,
4684
- normalizeNode: e.normalizeNode
4685
- });
4686
- const operationToPatches = createOperationToPatches(schemaTypes), withObjectKeys = createWithObjectKeys(editorActor, schemaTypes), withSchemaTypes = createWithSchemaTypes({
4672
+ } = options, schemaTypes = editorActor.getSnapshot().context.schema, operationToPatches = createOperationToPatches(schemaTypes), withObjectKeys = createWithObjectKeys(editorActor, schemaTypes), withSchemaTypes = createWithSchemaTypes({
4687
4673
  editorActor,
4688
4674
  schemaTypes
4689
4675
  }), withPatches = createWithPatches({
@@ -4698,38 +4684,21 @@ const originalFnMap = /* @__PURE__ */ new WeakMap(), withPlugins = (editor, opti
4698
4684
  }), withPortableTextMarkModel = createWithPortableTextMarkModel(editorActor, schemaTypes), withPortableTextBlockStyle = createWithPortableTextBlockStyle(editorActor, schemaTypes), withPlaceholderBlock = createWithPlaceholderBlock(editorActor), withUtils = createWithUtils({
4699
4685
  editorActor,
4700
4686
  schemaTypes
4701
- }), withPortableTextSelections = createWithPortableTextSelections(editorActor, schemaTypes), withEventListeners = createWithEventListeners(editorActor, options.subscriptions);
4702
- return e.destroy = () => {
4703
- const originalFunctions = originalFnMap.get(e);
4704
- if (!originalFunctions)
4705
- throw new Error("Could not find pristine versions of editor functions");
4706
- e.apply = originalFunctions.apply, e.history = {
4707
- undos: [],
4708
- redos: []
4709
- }, e.normalizeNode = originalFunctions.normalizeNode, e.onChange = originalFunctions.onChange;
4710
- }, withEventListeners(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPortableTextLists(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e))))))))))));
4711
- }, debug$7 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
4687
+ }), withPortableTextSelections = createWithPortableTextSelections(editorActor, schemaTypes);
4688
+ return createWithEventListeners(editorActor, options.subscriptions)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPortableTextLists(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e))))))))))));
4689
+ }, debug$6 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
4712
4690
  function createSlateEditor(config) {
4713
4691
  const existingSlateEditor = slateEditors.get(config.editorActor);
4714
4692
  if (existingSlateEditor)
4715
- return debug$7("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
4716
- debug$7("Creating new Slate editor instance", config.editorActor.id);
4717
- let unsubscriptions = [], subscriptions = [];
4718
- const instance = withPlugins(slateReact.withReact(slate.createEditor()), {
4693
+ return debug$6("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
4694
+ debug$6("Creating new Slate editor instance", config.editorActor.id);
4695
+ const unsubscriptions = [], subscriptions = [], instance = withPlugins(slateReact.withReact(slate.createEditor()), {
4719
4696
  editorActor: config.editorActor,
4720
4697
  subscriptions
4721
4698
  });
4722
4699
  KEY_TO_VALUE_ELEMENT.set(instance, {}), KEY_TO_SLATE_ELEMENT.set(instance, {});
4723
4700
  for (const subscription of subscriptions)
4724
4701
  unsubscriptions.push(subscription());
4725
- config.editorActor.subscribe((snapshot) => {
4726
- if (snapshot.status !== "active") {
4727
- debug$7("Destroying Slate editor"), instance.destroy();
4728
- for (const unsubscribe of unsubscriptions)
4729
- unsubscribe();
4730
- subscriptions = [], unsubscriptions = [];
4731
- }
4732
- });
4733
4702
  const initialValue = [instance.pteCreateTextBlock({
4734
4703
  decorators: []
4735
4704
  })], slateEditor = {
@@ -4738,7 +4707,7 @@ function createSlateEditor(config) {
4738
4707
  };
4739
4708
  return slateEditors.set(config.editorActor, slateEditor), slateEditor;
4740
4709
  }
4741
- const EditorActorContext = react.createContext({}), debug$6 = debugWithName("API:editable");
4710
+ const debug$5 = debugWithName("API:editable");
4742
4711
  function createEditableAPI(editor, editorActor) {
4743
4712
  const types2 = editorActor.getSnapshot().context.schema;
4744
4713
  return {
@@ -4819,7 +4788,7 @@ function createEditableAPI(editor, editorActor) {
4819
4788
  }], {
4820
4789
  schemaTypes: editorActor.getSnapshot().context.schema
4821
4790
  })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types2.span.name, focusNode = slate.Node.get(editor, focusChildPath);
4822
- return isSpanNode && focusNode._type !== types2.span.name && (debug$6("Inserting span child next to inline object child, moving selection + 1"), editor.move({
4791
+ return isSpanNode && focusNode._type !== types2.span.name && (debug$5("Inserting span child next to inline object child, moving selection + 1"), editor.move({
4823
4792
  distance: 1,
4824
4793
  unit: "character"
4825
4794
  })), slate.Transforms.insertNodes(editor, child, {
@@ -4951,18 +4920,18 @@ function createEditableAPI(editor, editorActor) {
4951
4920
  throw new Error("Invalid range");
4952
4921
  if (range) {
4953
4922
  if (!options?.mode || options?.mode === "selected") {
4954
- debug$6("Deleting content in selection"), slate.Transforms.delete(editor, {
4923
+ debug$5("Deleting content in selection"), slate.Transforms.delete(editor, {
4955
4924
  at: range,
4956
4925
  hanging: !0,
4957
4926
  voids: !0
4958
4927
  }), editor.onChange();
4959
4928
  return;
4960
4929
  }
4961
- options?.mode === "blocks" && (debug$6("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
4930
+ options?.mode === "blocks" && (debug$5("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
4962
4931
  at: range,
4963
4932
  voids: !0,
4964
4933
  match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && slate.Element.isElement(node)
4965
- })), options?.mode === "children" && (debug$6("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
4934
+ })), options?.mode === "children" && (debug$5("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
4966
4935
  at: range,
4967
4936
  voids: !0,
4968
4937
  match: (node) => node._type === types2.span.name || // Text children
@@ -5125,7 +5094,7 @@ const addAnnotationActionImplementation = ({
5125
5094
  action
5126
5095
  }) => {
5127
5096
  const editor = action.editor;
5128
- if (debug$6("Removing annotation", action.annotation.name), !!editor.selection)
5097
+ if (debug$5("Removing annotation", action.annotation.name), !!editor.selection)
5129
5098
  if (slate.Range.isCollapsed(editor.selection)) {
5130
5099
  const [block, blockPath] = slate.Editor.node(editor, editor.selection, {
5131
5100
  depth: 1
@@ -5778,8 +5747,8 @@ const editorMachine = xstate.setup({
5778
5747
  keyGenerator: input.keyGenerator,
5779
5748
  pendingEvents: [],
5780
5749
  schema: input.schema,
5781
- readOnly: !1,
5782
- maxBlocks: void 0,
5750
+ readOnly: input.readOnly ?? !1,
5751
+ maxBlocks: input.maxBlocks,
5783
5752
  value: input.value
5784
5753
  }),
5785
5754
  on: {
@@ -5884,11 +5853,16 @@ const editorMachine = xstate.setup({
5884
5853
  })
5885
5854
  },
5886
5855
  "toggle readOnly": {
5887
- actions: xstate.assign({
5856
+ actions: [xstate.assign({
5888
5857
  readOnly: ({
5889
5858
  context
5890
5859
  }) => !context.readOnly
5891
- })
5860
+ }), xstate.emit(({
5861
+ context
5862
+ }) => ({
5863
+ type: "readOnly toggled",
5864
+ readOnly: context.readOnly
5865
+ }))]
5892
5866
  },
5893
5867
  "update maxBlocks": {
5894
5868
  actions: xstate.assign({
@@ -5979,50 +5953,65 @@ const editorMachine = xstate.setup({
5979
5953
  }
5980
5954
  }
5981
5955
  }
5982
- }), PortableTextEditorSelectionContext = react.createContext(null), usePortableTextEditorSelection = () => {
5983
- const selection = react.useContext(PortableTextEditorSelectionContext);
5984
- if (selection === void 0)
5985
- throw new Error("The `usePortableTextEditorSelection` hook must be used inside the <PortableTextEditor> component's context.");
5986
- return selection;
5987
- }, debug$5 = debugWithName("component:PortableTextEditor:SelectionProvider"), debugVerbose = debug$5.enabled && !1;
5988
- function PortableTextEditorSelectionProvider(props) {
5989
- const $ = reactCompilerRuntime.c(6), [selection, setSelection] = react.useState(null);
5990
- let t0, t1;
5991
- $[0] !== props.editorActor ? (t0 = () => {
5992
- debug$5("Subscribing to selection changes");
5993
- const subscription = props.editorActor.on("selection", (event) => {
5994
- react.startTransition(() => {
5995
- debugVerbose && debug$5("Setting selection"), setSelection(event.selection);
5996
- });
5997
- });
5998
- return () => {
5999
- debug$5("Unsubscribing to selection changes"), subscription.unsubscribe();
6000
- };
6001
- }, t1 = [props.editorActor], $[0] = props.editorActor, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), react.useEffect(t0, t1);
6002
- let t2;
6003
- return $[3] !== props.children || $[4] !== selection ? (t2 = /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorSelectionContext.Provider, { value: selection, children: props.children }), $[3] = props.children, $[4] = selection, $[5] = t2) : t2 = $[5], t2;
6004
- }
6005
- const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
6006
- let table;
6007
- return () => {
6008
- if (table)
6009
- return table;
6010
- table = [];
6011
- for (let i = 0; i < 256; ++i)
6012
- table[i] = (i + 256).toString(16).slice(1);
6013
- return table;
5956
+ });
5957
+ function createEditor(config) {
5958
+ const editorActor = xstate.createActor(editorMachine, {
5959
+ input: editorConfigToMachineInput(config)
5960
+ });
5961
+ editorActor.start();
5962
+ const slateEditor = createSlateEditor({
5963
+ editorActor
5964
+ }), editable = createEditableAPI(slateEditor.instance, editorActor);
5965
+ return {
5966
+ send: (event) => {
5967
+ editorActor.send(event);
5968
+ },
5969
+ on: (event, listener) => editorActor.on(
5970
+ event,
5971
+ // @ts-ignore
5972
+ listener
5973
+ ),
5974
+ editable,
5975
+ _internal: {
5976
+ editorActor,
5977
+ slateEditor
5978
+ }
6014
5979
  };
6015
- })();
6016
- function whatwgRNG(length = 16) {
6017
- const rnds8 = new Uint8Array(length);
6018
- return getRandomValues__default.default(rnds8), rnds8;
6019
5980
  }
6020
- function randomKey(length) {
6021
- const table = getByteHexTable();
6022
- return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
5981
+ function useEditor(config) {
5982
+ const editorActor = react.useActorRef(editorMachine, {
5983
+ input: editorConfigToMachineInput(config)
5984
+ }), slateEditor = createSlateEditor({
5985
+ editorActor
5986
+ }), editable = React.useMemo(() => createEditableAPI(slateEditor.instance, editorActor), [slateEditor.instance, editorActor]), send = React.useCallback((event) => {
5987
+ editorActor.send(event);
5988
+ }, [editorActor]), on = React.useCallback((event_0, listener) => editorActor.on(
5989
+ event_0,
5990
+ // @ts-ignore
5991
+ listener
5992
+ ), [editorActor]);
5993
+ return React.useMemo(() => ({
5994
+ send,
5995
+ on,
5996
+ editable,
5997
+ _internal: {
5998
+ editorActor,
5999
+ slateEditor
6000
+ }
6001
+ }), [send, on, editable, editorActor, slateEditor]);
6002
+ }
6003
+ function editorConfigToMachineInput(config) {
6004
+ return {
6005
+ behaviors: config.behaviors,
6006
+ keyGenerator: config.keyGenerator ?? defaultKeyGenerator,
6007
+ maxBlocks: config.maxBlocks,
6008
+ readOnly: config.readOnly,
6009
+ schema: config.schemaDefinition ? compileSchemaDefinition(config.schemaDefinition) : getPortableTextMemberSchemaTypes(config.schema.hasOwnProperty("jsonType") ? config.schema : compileType(config.schema)),
6010
+ value: config.initialValue
6011
+ };
6023
6012
  }
6024
6013
  const debug$4 = debugWithName("component:PortableTextEditor");
6025
- class PortableTextEditor extends react.Component {
6014
+ class PortableTextEditor extends React.Component {
6026
6015
  static displayName = "PortableTextEditor";
6027
6016
  /**
6028
6017
  * An observable of all the editor changes.
@@ -6032,66 +6021,49 @@ class PortableTextEditor extends react.Component {
6032
6021
  * A lookup table for all the relevant schema types for this portable text type.
6033
6022
  */
6034
6023
  /**
6024
+ * The editor instance
6025
+ */
6026
+ /*
6035
6027
  * The editor API (currently implemented with Slate).
6036
6028
  */
6037
6029
  constructor(props) {
6038
- if (super(props), props.editor) {
6039
- const editor = props.editor;
6040
- this.editorActor = editor._internal.editorActor, this.slateEditor = editor._internal.slateEditor, this.editorActor.start(), this.schemaTypes = this.editorActor.getSnapshot().context.schema;
6041
- } else {
6042
- if (!props.schemaType)
6043
- throw new Error('PortableTextEditor: missing "schemaType" property');
6044
- props.incomingPatches$ && console.warn("The prop 'incomingPatches$' is deprecated and renamed to 'patches$'"), this.schemaTypes = getPortableTextMemberSchemaTypes(props.schemaType.hasOwnProperty("jsonType") ? props.schemaType : compileType(props.schemaType)), this.editorActor = xstate.createActor(editorMachine, {
6045
- input: {
6046
- keyGenerator: props.keyGenerator || defaultKeyGenerator,
6047
- schema: this.schemaTypes,
6048
- value: props.value
6049
- }
6050
- }), this.editorActor.start(), this.slateEditor = createSlateEditor({
6051
- editorActor: this.editorActor
6052
- }), props.readOnly && this.editorActor.send({
6053
- type: "toggle readOnly"
6054
- }), props.maxBlocks && this.editorActor.send({
6055
- type: "update maxBlocks",
6056
- maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10)
6057
- });
6058
- }
6059
- this.editable = createEditableAPI(this.slateEditor.instance, this.editorActor);
6030
+ super(props), props.editor ? this.editor = props.editor : this.editor = createEditor({
6031
+ keyGenerator: props.keyGenerator ?? defaultKeyGenerator,
6032
+ schema: props.schemaType,
6033
+ initialValue: props.value,
6034
+ maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10),
6035
+ readOnly: props.readOnly
6036
+ }), this.schemaTypes = this.editor._internal.editorActor.getSnapshot().context.schema, this.editable = this.editor.editable;
6060
6037
  }
6061
6038
  componentDidUpdate(prevProps) {
6062
- !this.props.editor && !prevProps.editor && this.props.schemaType !== prevProps.schemaType && (this.schemaTypes = getPortableTextMemberSchemaTypes(this.props.schemaType.hasOwnProperty("jsonType") ? this.props.schemaType : compileType(this.props.schemaType)), this.editorActor.send({
6039
+ !this.props.editor && !prevProps.editor && this.props.schemaType !== prevProps.schemaType && (this.schemaTypes = getPortableTextMemberSchemaTypes(this.props.schemaType.hasOwnProperty("jsonType") ? this.props.schemaType : compileType(this.props.schemaType)), this.editor._internal.editorActor.send({
6063
6040
  type: "update schema",
6064
6041
  schema: this.schemaTypes
6065
- })), !this.props.editor && !prevProps.editor && (this.props.readOnly !== prevProps.readOnly && this.editorActor.send({
6042
+ })), !this.props.editor && !prevProps.editor && (this.props.readOnly !== prevProps.readOnly && this.editor._internal.editorActor.send({
6066
6043
  type: "toggle readOnly"
6067
- }), this.props.maxBlocks !== prevProps.maxBlocks && this.editorActor.send({
6044
+ }), this.props.maxBlocks !== prevProps.maxBlocks && this.editor._internal.editorActor.send({
6068
6045
  type: "update maxBlocks",
6069
6046
  maxBlocks: this.props.maxBlocks === void 0 ? void 0 : Number.parseInt(this.props.maxBlocks.toString(), 10)
6070
- }), this.props.value !== prevProps.value && this.editorActor.send({
6047
+ }), this.props.value !== prevProps.value && this.editor._internal.editorActor.send({
6071
6048
  type: "update value",
6072
6049
  value: this.props.value
6073
6050
  }), this.props.editorRef !== prevProps.editorRef && this.props.editorRef && (this.props.editorRef.current = this));
6074
6051
  }
6075
6052
  setEditable = (editable) => {
6076
- this.editable = {
6077
- ...this.editable,
6053
+ this.editor.editable = {
6054
+ ...this.editor.editable,
6078
6055
  ...editable
6079
6056
  };
6080
6057
  };
6081
- getValue = () => {
6082
- if (this.editable)
6083
- return this.editable.getValue();
6084
- };
6085
6058
  render() {
6086
6059
  const legacyPatches = this.props.editor ? void 0 : this.props.incomingPatches$ ?? this.props.patches$;
6087
6060
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
6088
- legacyPatches ? /* @__PURE__ */ jsxRuntime.jsx(RoutePatchesObservableToEditorActor, { editorActor: this.editorActor, patches$: legacyPatches }) : null,
6089
- /* @__PURE__ */ jsxRuntime.jsx(EditorActorContext.Provider, { value: this.editorActor, children: /* @__PURE__ */ jsxRuntime.jsx(slateReact.Slate, { editor: this.slateEditor.instance, initialValue: this.slateEditor.initialValue, children: /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorContext.Provider, { value: this, children: /* @__PURE__ */ jsxRuntime.jsxs(PortableTextEditorSelectionProvider, { editorActor: this.editorActor, children: [
6090
- /* @__PURE__ */ jsxRuntime.jsx(Synchronizer, { editorActor: this.editorActor, getValue: this.getValue, onChange: (change) => {
6091
- this.props.editor || this.props.onChange(change), this.change$.next(change);
6092
- } }),
6093
- this.props.children
6094
- ] }) }) }) })
6061
+ legacyPatches ? /* @__PURE__ */ jsxRuntime.jsx(RoutePatchesObservableToEditorActor, { editorActor: this.editor._internal.editorActor, patches$: legacyPatches }) : null,
6062
+ /* @__PURE__ */ jsxRuntime.jsx(RouteEventsToChanges, { editorActor: this.editor._internal.editorActor, onChange: (change) => {
6063
+ this.props.editor || this.props.onChange(change), this.change$.next(change);
6064
+ } }),
6065
+ /* @__PURE__ */ jsxRuntime.jsx(Synchronizer, { editorActor: this.editor._internal.editorActor, getValue: this.editor.editable.getValue, portableTextEditor: this, slateEditor: this.editor._internal.slateEditor.instance }),
6066
+ /* @__PURE__ */ jsxRuntime.jsx(EditorActorContext.Provider, { value: this.editor._internal.editorActor, children: /* @__PURE__ */ jsxRuntime.jsx(slateReact.Slate, { editor: this.editor._internal.slateEditor.instance, initialValue: this.editor._internal.slateEditor.initialValue, children: /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorContext.Provider, { value: this, children: /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorSelectionProvider, { editorActor: this.editor._internal.editorActor, children: this.props.children }) }) }) })
6095
6067
  ] });
6096
6068
  }
6097
6069
  // Static API methods
@@ -6157,7 +6129,80 @@ function RoutePatchesObservableToEditorActor(props) {
6157
6129
  return () => {
6158
6130
  subscription.unsubscribe();
6159
6131
  };
6160
- }, t1 = [props.editorActor, props.patches$], $[0] = props.editorActor, $[1] = props.patches$, $[2] = t0, $[3] = t1) : (t0 = $[2], t1 = $[3]), react.useEffect(t0, t1), null;
6132
+ }, t1 = [props.editorActor, props.patches$], $[0] = props.editorActor, $[1] = props.patches$, $[2] = t0, $[3] = t1) : (t0 = $[2], t1 = $[3]), React.useEffect(t0, t1), null;
6133
+ }
6134
+ function RouteEventsToChanges(props) {
6135
+ const $ = reactCompilerRuntime.c(6);
6136
+ let t0;
6137
+ $[0] !== props ? (t0 = (change) => props.onChange(change), $[0] = props, $[1] = t0) : t0 = $[1];
6138
+ const handleChange = useEffectEvent.useEffectEvent(t0);
6139
+ let t1, t2;
6140
+ return $[2] !== handleChange || $[3] !== props.editorActor ? (t1 = () => {
6141
+ debug$4("Subscribing to editor changes");
6142
+ const sub = props.editorActor.on("*", (event) => {
6143
+ bb5: switch (event.type) {
6144
+ case "patch": {
6145
+ handleChange(event);
6146
+ break bb5;
6147
+ }
6148
+ case "loading": {
6149
+ handleChange({
6150
+ type: "loading",
6151
+ isLoading: !0
6152
+ });
6153
+ break bb5;
6154
+ }
6155
+ case "done loading": {
6156
+ handleChange({
6157
+ type: "loading",
6158
+ isLoading: !1
6159
+ });
6160
+ break bb5;
6161
+ }
6162
+ case "focused": {
6163
+ handleChange({
6164
+ type: "focus",
6165
+ event: event.event
6166
+ });
6167
+ break bb5;
6168
+ }
6169
+ case "value changed": {
6170
+ handleChange({
6171
+ type: "value",
6172
+ value: event.value
6173
+ });
6174
+ break bb5;
6175
+ }
6176
+ case "invalid value": {
6177
+ handleChange({
6178
+ type: "invalidValue",
6179
+ resolution: event.resolution,
6180
+ value: event.value
6181
+ });
6182
+ break bb5;
6183
+ }
6184
+ case "error": {
6185
+ handleChange({
6186
+ ...event,
6187
+ level: "warning"
6188
+ });
6189
+ break bb5;
6190
+ }
6191
+ case "annotation.add":
6192
+ case "annotation.remove":
6193
+ case "annotation.toggle":
6194
+ case "focus":
6195
+ case "patches":
6196
+ case "readOnly toggled":
6197
+ break bb5;
6198
+ default:
6199
+ handleChange(event);
6200
+ }
6201
+ });
6202
+ return () => {
6203
+ debug$4("Unsubscribing to changes"), sub.unsubscribe();
6204
+ };
6205
+ }, t2 = [props.editorActor, handleChange], $[2] = handleChange, $[3] = props.editorActor, $[4] = t1, $[5] = t2) : (t1 = $[4], t2 = $[5]), React.useEffect(t1, t2), null;
6161
6206
  }
6162
6207
  const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (props) => {
6163
6208
  const {
@@ -6169,22 +6214,22 @@ const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
6169
6214
  renderChild,
6170
6215
  renderDecorator,
6171
6216
  renderAnnotation
6172
- } = props, spanRef = react.useRef(null), portableTextEditor = usePortableTextEditor(), blockSelected = slateReact.useSelected(), [focused, setFocused] = react.useState(!1), [selected, setSelected] = react.useState(!1), block = children.props.parent, path = react.useMemo(() => block ? [{
6217
+ } = props, spanRef = React.useRef(null), portableTextEditor = usePortableTextEditor(), blockSelected = slateReact.useSelected(), [focused, setFocused] = React.useState(!1), [selected, setSelected] = React.useState(!1), block = children.props.parent, path = React.useMemo(() => block ? [{
6173
6218
  _key: block?._key
6174
6219
  }, "children", {
6175
6220
  _key: leaf._key
6176
- }] : [], [block, leaf._key]), decoratorValues = react.useMemo(() => schemaTypes.decorators.map((dec) => dec.value), [schemaTypes.decorators]), marks = react.useMemo(() => uniq__default.default((leaf.marks || EMPTY_MARKS).filter((mark) => decoratorValues.includes(mark))), [decoratorValues, leaf.marks]), annotationMarks = Array.isArray(leaf.marks) ? leaf.marks : EMPTY_MARKS, annotations = react.useMemo(() => annotationMarks.map((mark_0) => !decoratorValues.includes(mark_0) && block?.markDefs?.find((def) => def._key === mark_0)).filter(Boolean), [annotationMarks, block, decoratorValues]), shouldTrackSelectionAndFocus = annotations.length > 0 && blockSelected;
6177
- react.useEffect(() => {
6221
+ }] : [], [block, leaf._key]), decoratorValues = React.useMemo(() => schemaTypes.decorators.map((dec) => dec.value), [schemaTypes.decorators]), marks = React.useMemo(() => uniq__default.default((leaf.marks || EMPTY_MARKS).filter((mark) => decoratorValues.includes(mark))), [decoratorValues, leaf.marks]), annotationMarks = Array.isArray(leaf.marks) ? leaf.marks : EMPTY_MARKS, annotations = React.useMemo(() => annotationMarks.map((mark_0) => !decoratorValues.includes(mark_0) && block?.markDefs?.find((def) => def._key === mark_0)).filter(Boolean), [annotationMarks, block, decoratorValues]), shouldTrackSelectionAndFocus = annotations.length > 0 && blockSelected;
6222
+ React.useEffect(() => {
6178
6223
  if (!shouldTrackSelectionAndFocus) {
6179
6224
  setFocused(!1);
6180
6225
  return;
6181
6226
  }
6182
6227
  const sel = PortableTextEditor.getSelection(portableTextEditor);
6183
- sel && isEqual__default.default(sel.focus.path, path) && PortableTextEditor.isCollapsedSelection(portableTextEditor) && react.startTransition(() => {
6228
+ sel && isEqual__default.default(sel.focus.path, path) && PortableTextEditor.isCollapsedSelection(portableTextEditor) && React.startTransition(() => {
6184
6229
  setFocused(!0);
6185
6230
  });
6186
6231
  }, [shouldTrackSelectionAndFocus, path, portableTextEditor]);
6187
- const setSelectedFromRange = react.useCallback(() => {
6232
+ const setSelectedFromRange = React.useCallback(() => {
6188
6233
  if (!shouldTrackSelectionAndFocus)
6189
6234
  return;
6190
6235
  debug$3("Setting selection and focus from range");
@@ -6199,7 +6244,7 @@ const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
6199
6244
  } else
6200
6245
  setSelected(!1);
6201
6246
  }, [shouldTrackSelectionAndFocus]);
6202
- react.useEffect(() => {
6247
+ React.useEffect(() => {
6203
6248
  if (!shouldTrackSelectionAndFocus)
6204
6249
  return;
6205
6250
  const onBlur = editorActor.on("blur", () => {
@@ -6213,8 +6258,8 @@ const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
6213
6258
  return () => {
6214
6259
  onBlur.unsubscribe(), onFocus.unsubscribe(), onSelection.unsubscribe();
6215
6260
  };
6216
- }, [editorActor, path, portableTextEditor, setSelectedFromRange, shouldTrackSelectionAndFocus]), react.useEffect(() => setSelectedFromRange(), [setSelectedFromRange]);
6217
- const content = react.useMemo(() => {
6261
+ }, [editorActor, path, portableTextEditor, setSelectedFromRange, shouldTrackSelectionAndFocus]), React.useEffect(() => setSelectedFromRange(), [setSelectedFromRange]);
6262
+ const content = React.useMemo(() => {
6218
6263
  let returnedChildren = children;
6219
6264
  if (slate.Text.isText(leaf) && leaf._type === schemaTypes.span.name && (marks.forEach((mark_1) => {
6220
6265
  const schemaType = schemaTypes.decorators.find((dec_0) => dec_0.value === mark_1);
@@ -6280,7 +6325,7 @@ const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
6280
6325
  }
6281
6326
  return returnedChildren;
6282
6327
  }, [annotations, block, children, focused, leaf, marks, path, renderAnnotation, renderChild, renderDecorator, schemaTypes.annotations, schemaTypes.decorators, schemaTypes.span, selected]);
6283
- return react.useMemo(() => /* @__PURE__ */ jsxRuntime.jsx("span", { ...attributes, ref: spanRef, children: content }, leaf._key), [leaf, attributes, content]);
6328
+ return React.useMemo(() => /* @__PURE__ */ jsxRuntime.jsx("span", { ...attributes, ref: spanRef, children: content }, leaf._key), [leaf, attributes, content]);
6284
6329
  };
6285
6330
  Leaf.displayName = "Leaf";
6286
6331
  const debug$2 = debugWithName("plugin:withHotKeys"), DEFAULT_HOTKEYS = {
@@ -6593,7 +6638,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6593
6638
  pointerEvents: "none",
6594
6639
  left: 0,
6595
6640
  right: 0
6596
- }, PortableTextEditable = react.forwardRef(function(props, forwardedRef) {
6641
+ }, PortableTextEditable = React.forwardRef(function(props, forwardedRef) {
6597
6642
  const {
6598
6643
  hotkeys,
6599
6644
  onBlur,
@@ -6614,19 +6659,17 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6614
6659
  scrollSelectionIntoView,
6615
6660
  spellCheck,
6616
6661
  ...restProps
6617
- } = props, portableTextEditor = usePortableTextEditor(), ref = react.useRef(null), [editableElement, setEditableElement] = react.useState(null), [hasInvalidValue, setHasInvalidValue] = react.useState(!1), [rangeDecorationState, setRangeDecorationsState] = react.useState([]);
6618
- react.useImperativeHandle(forwardedRef, () => ref.current);
6619
- const rangeDecorationsRef = react.useRef(rangeDecorations), editorActor = react.useContext(EditorActorContext), readOnly = react$1.useSelector(editorActor, (s) => s.context.readOnly), {
6620
- schemaTypes
6621
- } = portableTextEditor, slateEditor = slateReact.useSlate(), blockTypeName = schemaTypes.block.name;
6622
- react.useMemo(() => {
6662
+ } = props, portableTextEditor = usePortableTextEditor(), ref = React.useRef(null), [editableElement, setEditableElement] = React.useState(null), [hasInvalidValue, setHasInvalidValue] = React.useState(!1), [rangeDecorationState, setRangeDecorationsState] = React.useState([]);
6663
+ React.useImperativeHandle(forwardedRef, () => ref.current);
6664
+ const rangeDecorationsRef = React.useRef(rangeDecorations), editorActor = React.useContext(EditorActorContext), readOnly = react.useSelector(editorActor, (s) => s.context.readOnly), schemaTypes = react.useSelector(editorActor, (s_0) => s_0.context.schema), slateEditor = slateReact.useSlate(), blockTypeName = schemaTypes.block.name;
6665
+ React.useMemo(() => {
6623
6666
  const withInsertData = createWithInsertData(editorActor, schemaTypes);
6624
6667
  if (readOnly)
6625
6668
  return debug("Editable is in read only mode"), withInsertData(slateEditor);
6626
6669
  const withHotKeys = createWithHotkeys(editorActor, portableTextEditor, hotkeys);
6627
6670
  return debug("Editable is in edit mode"), withInsertData(withHotKeys(slateEditor));
6628
6671
  }, [editorActor, hotkeys, portableTextEditor, readOnly, schemaTypes, slateEditor]);
6629
- const renderElement = react.useCallback((eProps) => /* @__PURE__ */ jsxRuntime.jsx(Element, { ...eProps, readOnly, renderBlock, renderChild, renderListItem, renderStyle, schemaTypes, spellCheck }), [schemaTypes, spellCheck, readOnly, renderBlock, renderChild, renderListItem, renderStyle]), renderLeaf = react.useCallback((lProps) => {
6672
+ const renderElement = React.useCallback((eProps) => /* @__PURE__ */ jsxRuntime.jsx(Element, { ...eProps, readOnly, renderBlock, renderChild, renderListItem, renderStyle, schemaTypes, spellCheck }), [schemaTypes, spellCheck, readOnly, renderBlock, renderChild, renderListItem, renderStyle]), renderLeaf = React.useCallback((lProps) => {
6630
6673
  if (lProps.leaf._type === "span") {
6631
6674
  let rendered = /* @__PURE__ */ jsxRuntime.jsx(Leaf, { ...lProps, editorActor, schemaTypes, renderAnnotation, renderChild, renderDecorator, readOnly });
6632
6675
  if (renderPlaceholder && lProps.leaf.placeholder && lProps.text.text === "")
@@ -6640,7 +6683,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6640
6683
  })), rendered;
6641
6684
  }
6642
6685
  return lProps.children;
6643
- }, [editorActor, readOnly, renderAnnotation, renderChild, renderDecorator, renderPlaceholder, schemaTypes]), restoreSelectionFromProps = react.useCallback(() => {
6686
+ }, [editorActor, readOnly, renderAnnotation, renderChild, renderDecorator, renderPlaceholder, schemaTypes]), restoreSelectionFromProps = React.useCallback(() => {
6644
6687
  if (propsSelection) {
6645
6688
  debug(`Selection from props ${JSON.stringify(propsSelection)}`);
6646
6689
  const normalizedSelection = normalizeSelection(propsSelection, fromSlateValue(slateEditor.children, blockTypeName));
@@ -6653,7 +6696,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6653
6696
  }), slateEditor.onChange());
6654
6697
  }
6655
6698
  }
6656
- }, [blockTypeName, editorActor, propsSelection, slateEditor]), syncRangeDecorations = react.useCallback((operation) => {
6699
+ }, [blockTypeName, editorActor, propsSelection, slateEditor]), syncRangeDecorations = React.useCallback((operation) => {
6657
6700
  if (rangeDecorations && rangeDecorations.length > 0) {
6658
6701
  const newSlateRanges = [];
6659
6702
  if (rangeDecorations.forEach((rangeDecorationItem) => {
@@ -6686,7 +6729,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6686
6729
  }
6687
6730
  setRangeDecorationsState((rangeDecorationState_0) => rangeDecorationState_0.length > 0 ? [] : rangeDecorationState_0);
6688
6731
  }, [portableTextEditor, rangeDecorations, schemaTypes, slateEditor]);
6689
- react.useEffect(() => {
6732
+ React.useEffect(() => {
6690
6733
  const onReady = editorActor.on("ready", () => {
6691
6734
  restoreSelectionFromProps();
6692
6735
  }), onInvalidValue = editorActor.on("invalid value", () => {
@@ -6697,21 +6740,21 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6697
6740
  return () => {
6698
6741
  onReady.unsubscribe(), onInvalidValue.unsubscribe(), onValueChanged.unsubscribe();
6699
6742
  };
6700
- }, [editorActor, restoreSelectionFromProps]), react.useEffect(() => {
6743
+ }, [editorActor, restoreSelectionFromProps]), React.useEffect(() => {
6701
6744
  propsSelection && !hasInvalidValue && restoreSelectionFromProps();
6702
6745
  }, [hasInvalidValue, propsSelection, restoreSelectionFromProps]);
6703
- const [syncedRangeDecorations, setSyncedRangeDecorations] = react.useState(!1);
6704
- react.useEffect(() => {
6746
+ const [syncedRangeDecorations, setSyncedRangeDecorations] = React.useState(!1);
6747
+ React.useEffect(() => {
6705
6748
  syncedRangeDecorations || (setSyncedRangeDecorations(!0), syncRangeDecorations());
6706
- }, [syncRangeDecorations, syncedRangeDecorations]), react.useEffect(() => {
6749
+ }, [syncRangeDecorations, syncedRangeDecorations]), React.useEffect(() => {
6707
6750
  isEqual__default.default(rangeDecorations, rangeDecorationsRef.current) || syncRangeDecorations(), rangeDecorationsRef.current = rangeDecorations;
6708
- }, [rangeDecorations, syncRangeDecorations]), react.useEffect(() => {
6751
+ }, [rangeDecorations, syncRangeDecorations]), React.useEffect(() => {
6709
6752
  const teardown = withSyncRangeDecorations(slateEditor, syncRangeDecorations);
6710
6753
  return () => teardown();
6711
6754
  }, [slateEditor, syncRangeDecorations]);
6712
- const handleCopy = react.useCallback((event) => {
6755
+ const handleCopy = React.useCallback((event) => {
6713
6756
  onCopy && onCopy(event) !== void 0 && event.preventDefault();
6714
- }, [onCopy]), handlePaste = react.useCallback((event_0) => {
6757
+ }, [onCopy]), handlePaste = React.useCallback((event_0) => {
6715
6758
  const value_0 = PortableTextEditor.getValue(portableTextEditor), path = toPortableTextRange(value_0, slateEditor.selection, schemaTypes)?.focus.path || [], onPasteResult = onPaste?.({
6716
6759
  event: event_0,
6717
6760
  value: value_0,
@@ -6736,7 +6779,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6736
6779
  },
6737
6780
  editor: slateEditor
6738
6781
  })), debug("No result from custom paste handler, pasting normally");
6739
- }, [editorActor, onPaste, portableTextEditor, schemaTypes, slateEditor]), handleOnFocus = react.useCallback((event_1) => {
6782
+ }, [editorActor, onPaste, portableTextEditor, schemaTypes, slateEditor]), handleOnFocus = React.useCallback((event_1) => {
6740
6783
  if (onFocus && onFocus(event_1), !event_1.isDefaultPrevented()) {
6741
6784
  const selection = PortableTextEditor.getSelection(portableTextEditor);
6742
6785
  selection === null && (slate.Transforms.select(slateEditor, slate.Editor.start(slateEditor, [])), slateEditor.onChange()), editorActor.send({
@@ -6749,20 +6792,20 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6749
6792
  selection
6750
6793
  });
6751
6794
  }
6752
- }, [editorActor, onFocus, portableTextEditor, slateEditor]), handleClick = react.useCallback((event_2) => {
6795
+ }, [editorActor, onFocus, portableTextEditor, slateEditor]), handleClick = React.useCallback((event_2) => {
6753
6796
  onClick && onClick(event_2);
6754
6797
  const focusBlockPath = slateEditor.selection ? slateEditor.selection.focus.path.slice(0, 1) : void 0, focusBlock = focusBlockPath ? slate.Node.descendant(slateEditor, focusBlockPath) : void 0, [_, lastNodePath] = slate.Node.last(slateEditor, []), lastBlockPath = lastNodePath.slice(0, 1), lastNodeFocused = focusBlockPath ? slate.Path.equals(lastBlockPath, focusBlockPath) : !1, lastBlockIsVoid = focusBlock ? !slateEditor.isTextBlock(focusBlock) : !1;
6755
6798
  slateEditor.selection && slate.Range.isCollapsed(slateEditor.selection) && lastNodeFocused && lastBlockIsVoid && (slate.Transforms.insertNodes(slateEditor, slateEditor.pteCreateTextBlock({
6756
6799
  decorators: []
6757
6800
  })), slateEditor.onChange());
6758
- }, [onClick, slateEditor]), handleOnBlur = react.useCallback((event_3) => {
6801
+ }, [onClick, slateEditor]), handleOnBlur = React.useCallback((event_3) => {
6759
6802
  onBlur && onBlur(event_3), event_3.isPropagationStopped() || editorActor.send({
6760
6803
  type: "blur",
6761
6804
  event: event_3
6762
6805
  });
6763
- }, [editorActor, onBlur]), handleOnBeforeInput = react.useCallback((event_4) => {
6806
+ }, [editorActor, onBlur]), handleOnBeforeInput = React.useCallback((event_4) => {
6764
6807
  onBeforeInput && onBeforeInput(event_4);
6765
- }, [onBeforeInput]), validateSelection = react.useCallback(() => {
6808
+ }, [onBeforeInput]), validateSelection = React.useCallback(() => {
6766
6809
  if (!slateEditor.selection)
6767
6810
  return;
6768
6811
  const root = slateReact.ReactEditor.findDocumentOrShadowRoot(slateEditor), {
@@ -6781,7 +6824,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6781
6824
  debug("Could not resolve selection, selecting top document"), slate.Transforms.deselect(slateEditor), slateEditor.children.length > 0 && slate.Transforms.select(slateEditor, [0, 0]), slateEditor.onChange();
6782
6825
  }
6783
6826
  }, [ref, slateEditor]);
6784
- react.useEffect(() => {
6827
+ React.useEffect(() => {
6785
6828
  if (editableElement) {
6786
6829
  const mutationObserver = new MutationObserver(validateSelection);
6787
6830
  return mutationObserver.observe(editableElement, {
@@ -6795,14 +6838,14 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6795
6838
  };
6796
6839
  }
6797
6840
  }, [validateSelection, editableElement]);
6798
- const handleKeyDown = react.useCallback((event_5) => {
6841
+ const handleKeyDown = React.useCallback((event_5) => {
6799
6842
  props.onKeyDown && props.onKeyDown(event_5), event_5.isDefaultPrevented() || slateEditor.pteWithHotKeys(event_5);
6800
- }, [props, slateEditor]), scrollSelectionIntoViewToSlate = react.useMemo(() => {
6843
+ }, [props, slateEditor]), scrollSelectionIntoViewToSlate = React.useMemo(() => {
6801
6844
  if (scrollSelectionIntoView !== void 0)
6802
6845
  return scrollSelectionIntoView === null ? noop__default.default : (_editor, domRange) => {
6803
6846
  scrollSelectionIntoView(portableTextEditor, domRange);
6804
6847
  };
6805
- }, [portableTextEditor, scrollSelectionIntoView]), decorate = react.useCallback(([, path_0]) => {
6848
+ }, [portableTextEditor, scrollSelectionIntoView]), decorate = React.useCallback(([, path_0]) => {
6806
6849
  if (isEqualToEmptyEditor(slateEditor.children, schemaTypes))
6807
6850
  return [{
6808
6851
  anchor: {
@@ -6829,7 +6872,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6829
6872
  }) || slate.Range.includes(item, path_0));
6830
6873
  return result_1.length > 0 ? result_1 : [];
6831
6874
  }, [slateEditor, schemaTypes, rangeDecorationState]);
6832
- return react.useEffect(() => {
6875
+ return React.useEffect(() => {
6833
6876
  ref.current = slateReact.ReactEditor.toDOMNode(slateEditor, slateEditor), setEditableElement(ref.current);
6834
6877
  }, [slateEditor, ref]), portableTextEditor ? hasInvalidValue ? null : /* @__PURE__ */ jsxRuntime.jsx(
6835
6878
  slateReact.Editable,
@@ -6854,45 +6897,55 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6854
6897
  ) : null;
6855
6898
  });
6856
6899
  PortableTextEditable.displayName = "ForwardRef(PortableTextEditable)";
6857
- function useEditor(config) {
6858
- const $ = reactCompilerRuntime.c(21), t0 = config.keyGenerator ?? defaultKeyGenerator;
6859
- let t1;
6860
- $[0] !== config.schema || $[1] !== config.schemaDefinition ? (t1 = config.schemaDefinition ? compileSchemaDefinition(config.schemaDefinition) : getPortableTextMemberSchemaTypes(config.schema.hasOwnProperty("jsonType") ? config.schema : compileType(config.schema)), $[0] = config.schema, $[1] = config.schemaDefinition, $[2] = t1) : t1 = $[2];
6900
+ const EditorContext = React__default.default.createContext(void 0);
6901
+ function EditorProvider(props) {
6902
+ const $ = reactCompilerRuntime.c(30), editor = useEditor(props.config), editorActor = editor._internal.editorActor, slateEditor = editor._internal.slateEditor, editable = editor.editable;
6903
+ let t0, t1;
6904
+ $[0] !== editor ? (t1 = new PortableTextEditor({
6905
+ editor
6906
+ }), $[0] = editor, $[1] = t1) : t1 = $[1], t0 = t1;
6907
+ const portableTextEditor = t0;
6861
6908
  let t2;
6862
- $[3] !== config.behaviors || $[4] !== config.initialValue || $[5] !== t0 || $[6] !== t1 ? (t2 = {
6863
- input: {
6864
- behaviors: config.behaviors,
6865
- keyGenerator: t0,
6866
- schema: t1,
6867
- value: config.initialValue
6868
- }
6869
- }, $[3] = config.behaviors, $[4] = config.initialValue, $[5] = t0, $[6] = t1, $[7] = t2) : t2 = $[7];
6870
- const editorActor = react$1.useActorRef(editorMachine, t2);
6909
+ $[2] !== portableTextEditor.change$ ? (t2 = (change) => {
6910
+ portableTextEditor.change$.next(change);
6911
+ }, $[2] = portableTextEditor.change$, $[3] = t2) : t2 = $[3];
6871
6912
  let t3;
6872
- $[8] !== editorActor ? (t3 = createSlateEditor({
6873
- editorActor
6874
- }), $[8] = editorActor, $[9] = t3) : t3 = $[9];
6875
- const slateEditor = t3, readOnly = react$1.useSelector(editorActor, _temp);
6876
- let t4, t5;
6877
- $[10] !== editorActor ? (t4 = (event) => {
6878
- editorActor.send(event);
6879
- }, t5 = (event_0, listener) => editorActor.on(event_0, listener), $[10] = editorActor, $[11] = t4, $[12] = t5) : (t4 = $[11], t5 = $[12]);
6913
+ $[4] !== editorActor || $[5] !== t2 ? (t3 = /* @__PURE__ */ jsxRuntime.jsx(RouteEventsToChanges, { editorActor, onChange: t2 }), $[4] = editorActor, $[5] = t2, $[6] = t3) : t3 = $[6];
6914
+ let t4;
6915
+ $[7] !== editable.getValue || $[8] !== editorActor || $[9] !== portableTextEditor || $[10] !== slateEditor.instance ? (t4 = /* @__PURE__ */ jsxRuntime.jsx(Synchronizer, { editorActor, getValue: editable.getValue, portableTextEditor, slateEditor: slateEditor.instance }), $[7] = editable.getValue, $[8] = editorActor, $[9] = portableTextEditor, $[10] = slateEditor.instance, $[11] = t4) : t4 = $[11];
6916
+ let t5;
6917
+ $[12] !== editorActor || $[13] !== props.children ? (t5 = /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorSelectionProvider, { editorActor, children: props.children }), $[12] = editorActor, $[13] = props.children, $[14] = t5) : t5 = $[14];
6880
6918
  let t6;
6881
- $[13] !== editorActor || $[14] !== slateEditor ? (t6 = {
6882
- editorActor,
6883
- slateEditor
6884
- }, $[13] = editorActor, $[14] = slateEditor, $[15] = t6) : t6 = $[15];
6919
+ $[15] !== portableTextEditor || $[16] !== t5 ? (t6 = /* @__PURE__ */ jsxRuntime.jsx(PortableTextEditorContext.Provider, { value: portableTextEditor, children: t5 }), $[15] = portableTextEditor, $[16] = t5, $[17] = t6) : t6 = $[17];
6885
6920
  let t7;
6886
- return $[16] !== readOnly || $[17] !== t4 || $[18] !== t5 || $[19] !== t6 ? (t7 = {
6887
- send: t4,
6888
- on: t5,
6889
- readOnly,
6890
- _internal: t6
6891
- }, $[16] = readOnly, $[17] = t4, $[18] = t5, $[19] = t6, $[20] = t7) : t7 = $[20], t7;
6921
+ $[18] !== slateEditor.initialValue || $[19] !== slateEditor.instance || $[20] !== t6 ? (t7 = /* @__PURE__ */ jsxRuntime.jsx(slateReact.Slate, { editor: slateEditor.instance, initialValue: slateEditor.initialValue, children: t6 }), $[18] = slateEditor.initialValue, $[19] = slateEditor.instance, $[20] = t6, $[21] = t7) : t7 = $[21];
6922
+ let t8;
6923
+ $[22] !== editorActor || $[23] !== t7 ? (t8 = /* @__PURE__ */ jsxRuntime.jsx(EditorActorContext.Provider, { value: editorActor, children: t7 }), $[22] = editorActor, $[23] = t7, $[24] = t8) : t8 = $[24];
6924
+ let t9;
6925
+ return $[25] !== editor || $[26] !== t3 || $[27] !== t4 || $[28] !== t8 ? (t9 = /* @__PURE__ */ jsxRuntime.jsxs(EditorContext.Provider, { value: editor, children: [
6926
+ t3,
6927
+ t4,
6928
+ t8
6929
+ ] }), $[25] = editor, $[26] = t3, $[27] = t4, $[28] = t8, $[29] = t9) : t9 = $[29], t9;
6930
+ }
6931
+ function useEditorContext() {
6932
+ const editor = React__default.default.useContext(EditorContext);
6933
+ if (!editor)
6934
+ throw new Error("No Editor set. Use EditorProvider to set one.");
6935
+ return editor;
6892
6936
  }
6893
- function _temp(s) {
6894
- return s.context.readOnly;
6937
+ function EditorEventListener(props) {
6938
+ const $ = reactCompilerRuntime.c(4), editor = useEditorContext(), on = useEffectEvent.useEffectEvent(props.on);
6939
+ let t0, t1;
6940
+ return $[0] !== editor || $[1] !== on ? (t0 = () => {
6941
+ const subscription = editor.on("*", on);
6942
+ return () => {
6943
+ subscription.unsubscribe();
6944
+ };
6945
+ }, t1 = [editor, on], $[0] = editor, $[1] = on, $[2] = t0, $[3] = t1) : (t0 = $[2], t1 = $[3]), React.useEffect(t0, t1), null;
6895
6946
  }
6947
+ exports.EditorEventListener = EditorEventListener;
6948
+ exports.EditorProvider = EditorProvider;
6896
6949
  exports.PortableTextEditable = PortableTextEditable;
6897
6950
  exports.PortableTextEditor = PortableTextEditor;
6898
6951
  exports.coreBehavior = coreBehavior;
@@ -6904,6 +6957,7 @@ exports.defineSchema = defineSchema;
6904
6957
  exports.editorMachine = editorMachine;
6905
6958
  exports.keyGenerator = defaultKeyGenerator;
6906
6959
  exports.useEditor = useEditor;
6960
+ exports.useEditorContext = useEditorContext;
6907
6961
  exports.usePortableTextEditor = usePortableTextEditor;
6908
6962
  exports.usePortableTextEditorSelection = usePortableTextEditorSelection;
6909
6963
  //# sourceMappingURL=index.js.map