@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.esm.js CHANGED
@@ -5,25 +5,25 @@ import { jsx, Fragment, jsxs } from "react/jsx-runtime";
5
5
  import { useSelector, useActorRef } from "@xstate/react";
6
6
  import isEqual from "lodash/isEqual.js";
7
7
  import noop from "lodash/noop.js";
8
- import { useRef, useState, useEffect, useMemo, createContext, useContext, useCallback, startTransition, Component, forwardRef, useImperativeHandle } from "react";
9
- import { Editor, Element as Element$1, Range, Point, Text, Path, Transforms, Operation, Node, createEditor, deleteBackward, deleteForward, insertText } from "slate";
10
- import { useSlateStatic, ReactEditor, useSelected, useSlate, withReact, Slate, Editable } from "slate-react";
8
+ import React, { useRef, useState, useEffect, useMemo, createContext, useContext, useCallback, startTransition, Component, forwardRef, useImperativeHandle } from "react";
9
+ import { Editor, Element as Element$1, Range, Point, Text, Path, Transforms, Operation, Node, createEditor as createEditor$1, deleteBackward, deleteForward, insertText } from "slate";
10
+ import { useSlateStatic, ReactEditor, useSelected, withReact, Slate, useSlate, Editable } from "slate-react";
11
11
  import debug$m from "debug";
12
12
  import { c } from "react-compiler-runtime";
13
13
  import { styled } from "styled-components";
14
14
  import uniq from "lodash/uniq.js";
15
15
  import { Subject } from "rxjs";
16
- import { setup, assign, assertEvent, emit, enqueueActions, createActor } from "xstate";
17
- import throttle from "lodash/throttle.js";
18
16
  import { useEffectEvent } from "use-effect-event";
17
+ import throttle from "lodash/throttle.js";
19
18
  import debounce from "lodash/debounce.js";
20
19
  import { unset, set, setIfMissing, insert, diffMatchPatch as diffMatchPatch$1, applyAll } from "@portabletext/patches";
21
20
  import flatten from "lodash/flatten.js";
22
21
  import isPlainObject from "lodash/isPlainObject.js";
22
+ import getRandomValues from "get-random-values-esm";
23
+ import { setup, assign, assertEvent, emit, enqueueActions, createActor } from "xstate";
23
24
  import get from "lodash/get.js";
24
25
  import isUndefined from "lodash/isUndefined.js";
25
26
  import omitBy from "lodash/omitBy.js";
26
- import getRandomValues from "get-random-values-esm";
27
27
  import { isHotkey } from "is-hotkey-esm";
28
28
  import { htmlToBlocks, normalizeBlock } from "@sanity/block-tools";
29
29
  function defineBehavior(behavior) {
@@ -317,6 +317,65 @@ const breakingBlockObject = {
317
317
  blockObjects: coreBlockObjectBehaviors,
318
318
  lists: coreListBehaviors
319
319
  };
320
+ function createLinkBehaviors(config) {
321
+ const pasteLinkOnSelection = {
322
+ on: "paste",
323
+ guard: ({
324
+ context,
325
+ event
326
+ }) => {
327
+ const selectionCollapsed = selectionIsCollapsed(context), text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
328
+ url,
329
+ schema: context.schema
330
+ }) : void 0;
331
+ return annotation && !selectionCollapsed ? {
332
+ annotation
333
+ } : !1;
334
+ },
335
+ actions: [(_, {
336
+ annotation
337
+ }) => [{
338
+ type: "annotation.add",
339
+ annotation
340
+ }]]
341
+ }, pasteLinkAtCaret = {
342
+ on: "paste",
343
+ guard: ({
344
+ context,
345
+ event
346
+ }) => {
347
+ const focusSpan = getFocusSpan(context), selectionCollapsed = selectionIsCollapsed(context);
348
+ if (!focusSpan || !selectionCollapsed)
349
+ return !1;
350
+ const text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
351
+ url,
352
+ schema: context.schema
353
+ }) : void 0;
354
+ return url && annotation && selectionCollapsed ? {
355
+ focusSpan,
356
+ annotation,
357
+ url
358
+ } : !1;
359
+ },
360
+ actions: [(_, {
361
+ annotation,
362
+ url
363
+ }) => [{
364
+ type: "insert span",
365
+ text: url,
366
+ annotations: [annotation]
367
+ }]]
368
+ };
369
+ return [pasteLinkOnSelection, pasteLinkAtCaret];
370
+ }
371
+ function looksLikeUrl(text) {
372
+ let looksLikeUrl2 = !1;
373
+ try {
374
+ new URL(text), looksLikeUrl2 = !0;
375
+ } catch {
376
+ }
377
+ return looksLikeUrl2;
378
+ }
320
379
  function isPortableTextSpan(node) {
321
380
  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"));
322
381
  }
@@ -573,65 +632,6 @@ function createMarkdownBehaviors(config) {
573
632
  };
574
633
  return [automaticBlockquoteOnSpace, automaticBreak, automaticHeadingOnSpace, clearStyleOnBackspace, automaticListOnSpace];
575
634
  }
576
- function createLinkBehaviors(config) {
577
- const pasteLinkOnSelection = {
578
- on: "paste",
579
- guard: ({
580
- context,
581
- event
582
- }) => {
583
- const selectionCollapsed = selectionIsCollapsed(context), text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
584
- url,
585
- schema: context.schema
586
- }) : void 0;
587
- return annotation && !selectionCollapsed ? {
588
- annotation
589
- } : !1;
590
- },
591
- actions: [(_, {
592
- annotation
593
- }) => [{
594
- type: "annotation.add",
595
- annotation
596
- }]]
597
- }, pasteLinkAtCaret = {
598
- on: "paste",
599
- guard: ({
600
- context,
601
- event
602
- }) => {
603
- const focusSpan = getFocusSpan(context), selectionCollapsed = selectionIsCollapsed(context);
604
- if (!focusSpan || !selectionCollapsed)
605
- return !1;
606
- const text = event.clipboardData.getData("text/plain"), url = looksLikeUrl(text) ? text : void 0, annotation = url !== void 0 ? config.linkAnnotation?.({
607
- url,
608
- schema: context.schema
609
- }) : void 0;
610
- return url && annotation && selectionCollapsed ? {
611
- focusSpan,
612
- annotation,
613
- url
614
- } : !1;
615
- },
616
- actions: [(_, {
617
- annotation,
618
- url
619
- }) => [{
620
- type: "insert span",
621
- text: url,
622
- annotations: [annotation]
623
- }]]
624
- };
625
- return [pasteLinkOnSelection, pasteLinkAtCaret];
626
- }
627
- function looksLikeUrl(text) {
628
- let looksLikeUrl2 = !1;
629
- try {
630
- new URL(text), looksLikeUrl2 = !0;
631
- } catch {
632
- }
633
- return looksLikeUrl2;
634
- }
635
635
  function getPortableTextMemberSchemaTypes(portableTextType) {
636
636
  if (!portableTextType)
637
637
  throw new Error("Parameter 'portabletextType' missing (required)");
@@ -2559,8 +2559,10 @@ function createWithUndoRedo(options) {
2559
2559
  apply: apply2
2560
2560
  } = editor;
2561
2561
  return editor.apply = (op) => {
2562
- if (editorActor.getSnapshot().context.readOnly)
2562
+ if (editorActor.getSnapshot().context.readOnly) {
2563
+ apply2(op);
2563
2564
  return;
2565
+ }
2564
2566
  if (isChangingRemotely(editor)) {
2565
2567
  apply2(op);
2566
2568
  return;
@@ -2773,8 +2775,9 @@ function useSyncValue(props) {
2773
2775
  const {
2774
2776
  editorActor,
2775
2777
  portableTextEditor,
2776
- readOnly
2777
- } = props, schemaTypes = editorActor.getSnapshot().context.schema, previousValue = useRef(), slateEditor = useSlate(), updateValueFunctionRef = useRef(), updateFromCurrentValue = useCallback(() => {
2778
+ readOnly,
2779
+ slateEditor
2780
+ } = props, schemaTypes = editorActor.getSnapshot().context.schema, previousValue = useRef(), updateValueFunctionRef = useRef(), updateFromCurrentValue = useCallback(() => {
2778
2781
  const currentValue = CURRENT_VALUE.get(portableTextEditor);
2779
2782
  if (previousValue.current === currentValue) {
2780
2783
  debug$j("Value is the same object as previous, not need to sync");
@@ -2957,27 +2960,29 @@ function _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex) {
2957
2960
  }
2958
2961
  const debug$i = debugWithName("component:PortableTextEditor:Synchronizer"), debugVerbose$3 = debug$i.enabled && !1, FLUSH_PATCHES_THROTTLED_MS = process.env.NODE_ENV === "test" ? 500 : 1e3;
2959
2962
  function Synchronizer(props) {
2960
- const $ = c(28), portableTextEditor = usePortableTextEditor(), readOnly = useSelector(props.editorActor, _temp$1), value = useSelector(props.editorActor, _temp2), {
2963
+ const $ = c(26), readOnly = useSelector(props.editorActor, _temp), value = useSelector(props.editorActor, _temp2), {
2961
2964
  editorActor,
2962
2965
  getValue,
2963
- onChange
2966
+ portableTextEditor,
2967
+ slateEditor
2964
2968
  } = props;
2965
2969
  let t0;
2966
2970
  $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = [], $[0] = t0) : t0 = $[0];
2967
2971
  const pendingPatches = useRef(t0);
2968
2972
  let t1;
2969
- $[1] !== editorActor || $[2] !== portableTextEditor || $[3] !== readOnly ? (t1 = {
2973
+ $[1] !== editorActor || $[2] !== portableTextEditor || $[3] !== readOnly || $[4] !== slateEditor ? (t1 = {
2970
2974
  editorActor,
2971
2975
  portableTextEditor,
2972
- readOnly
2973
- }, $[1] = editorActor, $[2] = portableTextEditor, $[3] = readOnly, $[4] = t1) : t1 = $[4];
2974
- const syncValue = useSyncValue(t1), slateEditor = useSlate();
2976
+ readOnly,
2977
+ slateEditor
2978
+ }, $[1] = editorActor, $[2] = portableTextEditor, $[3] = readOnly, $[4] = slateEditor, $[5] = t1) : t1 = $[5];
2979
+ const syncValue = useSyncValue(t1);
2975
2980
  let t2, t3;
2976
- $[5] !== slateEditor ? (t2 = () => {
2981
+ $[6] !== slateEditor ? (t2 = () => {
2977
2982
  IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !1);
2978
- }, t3 = [slateEditor], $[5] = slateEditor, $[6] = t2, $[7] = t3) : (t2 = $[6], t3 = $[7]), useEffect(t2, t3);
2983
+ }, t3 = [slateEditor], $[6] = slateEditor, $[7] = t2, $[8] = t3) : (t2 = $[7], t3 = $[8]), useEffect(t2, t3);
2979
2984
  let t4;
2980
- $[8] !== editorActor || $[9] !== getValue || $[10] !== slateEditor ? (t4 = () => {
2985
+ $[9] !== editorActor || $[10] !== getValue || $[11] !== slateEditor ? (t4 = () => {
2981
2986
  if (pendingPatches.current.length > 0) {
2982
2987
  debug$i("Flushing pending patches"), debugVerbose$3 && debug$i(`Patches:
2983
2988
  ${JSON.stringify(pendingPatches.current, null, 2)}`);
@@ -2989,17 +2994,14 @@ ${JSON.stringify(pendingPatches.current, null, 2)}`);
2989
2994
  }), pendingPatches.current = [];
2990
2995
  }
2991
2996
  IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !1);
2992
- }, $[8] = editorActor, $[9] = getValue, $[10] = slateEditor, $[11] = t4) : t4 = $[11];
2997
+ }, $[9] = editorActor, $[10] = getValue, $[11] = slateEditor, $[12] = t4) : t4 = $[12];
2993
2998
  const onFlushPendingPatches = t4;
2994
2999
  let t5, t6;
2995
- $[12] !== onFlushPendingPatches ? (t5 = () => () => {
3000
+ $[13] !== onFlushPendingPatches ? (t5 = () => () => {
2996
3001
  onFlushPendingPatches();
2997
- }, t6 = [onFlushPendingPatches], $[12] = onFlushPendingPatches, $[13] = t5, $[14] = t6) : (t5 = $[13], t6 = $[14]), useEffect(t5, t6);
2998
- let t7;
2999
- $[15] !== onChange ? (t7 = (change) => onChange(change), $[15] = onChange, $[16] = t7) : t7 = $[16];
3000
- const handleChange = useEffectEvent(t7);
3001
- let t8, t9;
3002
- $[17] !== editorActor || $[18] !== handleChange || $[19] !== onFlushPendingPatches || $[20] !== slateEditor ? (t8 = () => {
3002
+ }, t6 = [onFlushPendingPatches], $[13] = onFlushPendingPatches, $[14] = t5, $[15] = t6) : (t5 = $[14], t6 = $[15]), useEffect(t5, t6);
3003
+ let t7, t8;
3004
+ $[16] !== editorActor || $[17] !== onFlushPendingPatches || $[18] !== slateEditor ? (t7 = () => {
3003
3005
  const onFlushPendingPatchesThrottled = throttle(() => {
3004
3006
  if (Editor.isNormalizing(slateEditor)) {
3005
3007
  onFlushPendingPatches();
@@ -3010,90 +3012,76 @@ ${JSON.stringify(pendingPatches.current, null, 2)}`);
3010
3012
  leading: !1,
3011
3013
  trailing: !0
3012
3014
  });
3013
- debug$i("Subscribing to editor changes");
3014
- const sub = editorActor.on("*", (event) => {
3015
- bb22: switch (event.type) {
3016
- case "patch": {
3017
- IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !0), pendingPatches.current.push(event.patch), onFlushPendingPatchesThrottled(), handleChange(event);
3018
- break bb22;
3019
- }
3020
- case "loading": {
3021
- handleChange({
3022
- type: "loading",
3023
- isLoading: !0
3024
- });
3025
- break bb22;
3026
- }
3027
- case "done loading": {
3028
- handleChange({
3029
- type: "loading",
3030
- isLoading: !1
3031
- });
3032
- break bb22;
3033
- }
3034
- case "focused": {
3035
- handleChange({
3036
- type: "focus",
3037
- event: event.event
3038
- });
3039
- break bb22;
3040
- }
3041
- case "value changed": {
3042
- handleChange({
3043
- type: "value",
3044
- value: event.value
3045
- });
3046
- break bb22;
3047
- }
3048
- case "invalid value": {
3049
- handleChange({
3050
- type: "invalidValue",
3051
- resolution: event.resolution,
3052
- value: event.value
3053
- });
3054
- break bb22;
3055
- }
3056
- case "error": {
3057
- handleChange({
3058
- ...event,
3059
- level: "warning"
3060
- });
3061
- break bb22;
3062
- }
3063
- case "annotation.add":
3064
- case "annotation.remove":
3065
- case "annotation.toggle":
3066
- case "focus":
3067
- case "patches":
3068
- break bb22;
3069
- default:
3070
- handleChange(event);
3071
- }
3015
+ debug$i("Subscribing to patch events");
3016
+ const sub = editorActor.on("patch", (event) => {
3017
+ IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, !0), pendingPatches.current.push(event.patch), onFlushPendingPatchesThrottled();
3072
3018
  });
3073
3019
  return () => {
3074
- debug$i("Unsubscribing to changes"), sub.unsubscribe();
3020
+ debug$i("Unsubscribing to patch events"), sub.unsubscribe();
3075
3021
  };
3076
- }, t9 = [editorActor, handleChange, onFlushPendingPatches, slateEditor], $[17] = editorActor, $[18] = handleChange, $[19] = onFlushPendingPatches, $[20] = slateEditor, $[21] = t8, $[22] = t9) : (t8 = $[21], t9 = $[22]), useEffect(t8, t9);
3022
+ }, t8 = [editorActor, onFlushPendingPatches, slateEditor], $[16] = editorActor, $[17] = onFlushPendingPatches, $[18] = slateEditor, $[19] = t7, $[20] = t8) : (t7 = $[19], t8 = $[20]), useEffect(t7, t8);
3077
3023
  const isInitialValueFromProps = useRef(!0);
3078
- let t10, t11;
3079
- return $[23] !== editorActor || $[24] !== syncValue || $[25] !== value ? (t10 = () => {
3024
+ let t10, t9;
3025
+ return $[21] !== editorActor || $[22] !== syncValue || $[23] !== value ? (t9 = () => {
3080
3026
  debug$i("Value from props changed, syncing new value"), syncValue(value), isInitialValueFromProps.current && (editorActor.send({
3081
3027
  type: "ready"
3082
3028
  }), isInitialValueFromProps.current = !1);
3083
- }, t11 = [editorActor, syncValue, value], $[23] = editorActor, $[24] = syncValue, $[25] = value, $[26] = t10, $[27] = t11) : (t10 = $[26], t11 = $[27]), useEffect(t10, t11), null;
3029
+ }, t10 = [editorActor, syncValue, value], $[21] = editorActor, $[22] = syncValue, $[23] = value, $[24] = t10, $[25] = t9) : (t10 = $[24], t9 = $[25]), useEffect(t9, t10), null;
3084
3030
  }
3085
3031
  function _temp2(s_0) {
3086
3032
  return s_0.context.value;
3087
3033
  }
3088
- function _temp$1(s) {
3034
+ function _temp(s) {
3089
3035
  return s.context.readOnly;
3090
3036
  }
3091
3037
  Synchronizer.displayName = "Synchronizer";
3092
- const debug$h = debugWithName("operationToPatches");
3038
+ const EditorActorContext = createContext({}), PortableTextEditorSelectionContext = createContext(null), usePortableTextEditorSelection = () => {
3039
+ const selection = useContext(PortableTextEditorSelectionContext);
3040
+ if (selection === void 0)
3041
+ throw new Error("The `usePortableTextEditorSelection` hook must be used inside the <PortableTextEditor> component's context.");
3042
+ return selection;
3043
+ }, debug$h = debugWithName("component:PortableTextEditor:SelectionProvider"), debugVerbose$2 = debug$h.enabled && !1;
3044
+ function PortableTextEditorSelectionProvider(props) {
3045
+ const $ = c(6), [selection, setSelection] = useState(null);
3046
+ let t0, t1;
3047
+ $[0] !== props.editorActor ? (t0 = () => {
3048
+ debug$h("Subscribing to selection changes");
3049
+ const subscription = props.editorActor.on("selection", (event) => {
3050
+ startTransition(() => {
3051
+ debugVerbose$2 && debug$h("Setting selection"), setSelection(event.selection);
3052
+ });
3053
+ });
3054
+ return () => {
3055
+ debug$h("Unsubscribing to selection changes"), subscription.unsubscribe();
3056
+ };
3057
+ }, t1 = [props.editorActor], $[0] = props.editorActor, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), useEffect(t0, t1);
3058
+ let t2;
3059
+ return $[3] !== props.children || $[4] !== selection ? (t2 = /* @__PURE__ */ jsx(PortableTextEditorSelectionContext.Provider, { value: selection, children: props.children }), $[3] = props.children, $[4] = selection, $[5] = t2) : t2 = $[5], t2;
3060
+ }
3061
+ const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
3062
+ let table;
3063
+ return () => {
3064
+ if (table)
3065
+ return table;
3066
+ table = [];
3067
+ for (let i = 0; i < 256; ++i)
3068
+ table[i] = (i + 256).toString(16).slice(1);
3069
+ return table;
3070
+ };
3071
+ })();
3072
+ function whatwgRNG(length = 16) {
3073
+ const rnds8 = new Uint8Array(length);
3074
+ return getRandomValues(rnds8), rnds8;
3075
+ }
3076
+ function randomKey(length) {
3077
+ const table = getByteHexTable();
3078
+ return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
3079
+ }
3080
+ const debug$g = debugWithName("operationToPatches");
3093
3081
  function createOperationToPatches(types) {
3094
3082
  const textBlockName = types.block.name;
3095
3083
  function insertTextPatch(editor, operation, beforeValue) {
3096
- debug$h.enabled && debug$h("Operation", JSON.stringify(operation, null, 2));
3084
+ debug$g.enabled && debug$g("Operation", JSON.stringify(operation, null, 2));
3097
3085
  const block = editor.isTextBlock(editor.children[operation.path[0]]) && editor.children[operation.path[0]];
3098
3086
  if (!block)
3099
3087
  throw new Error("Could not find block");
@@ -3186,7 +3174,7 @@ function createOperationToPatches(types) {
3186
3174
  _key: block.children[operation.path[1] - 1]._key
3187
3175
  }])];
3188
3176
  }
3189
- return debug$h("Something was inserted into a void block. Not producing editor patches."), [];
3177
+ return debug$g("Something was inserted into a void block. Not producing editor patches."), [];
3190
3178
  }
3191
3179
  function splitNodePatch(editor, operation, beforeValue) {
3192
3180
  const patches = [], splitBlock = editor.children[operation.path[0]];
@@ -3244,9 +3232,9 @@ function createOperationToPatches(types) {
3244
3232
  _key: block._key
3245
3233
  }, "children", {
3246
3234
  _key: spanToRemove._key
3247
- }])] : (debug$h("Span not found in editor trying to remove node"), []);
3235
+ }])] : (debug$g("Span not found in editor trying to remove node"), []);
3248
3236
  } else
3249
- return debug$h("Not creating patch inside object block"), [];
3237
+ return debug$g("Not creating patch inside object block"), [];
3250
3238
  }
3251
3239
  function mergeNodePatch(editor, operation, beforeValue) {
3252
3240
  const patches = [], block = beforeValue[operation.path[0]], updatedBlock = editor.children[operation.path[0]];
@@ -3272,7 +3260,7 @@ function createOperationToPatches(types) {
3272
3260
  _key: removedSpan._key
3273
3261
  }])) : console.warn(`Multiple spans have \`_key\` ${removedSpan._key}. It's ambiguous which one to remove.`, JSON.stringify(block, null, 2)));
3274
3262
  } else
3275
- debug$h("Void nodes can't be merged, not creating any patches");
3263
+ debug$g("Void nodes can't be merged, not creating any patches");
3276
3264
  return patches;
3277
3265
  }
3278
3266
  function moveNodePatch(editor, operation, beforeValue) {
@@ -3433,8 +3421,10 @@ function createWithMaxBlocks(editorActor) {
3433
3421
  apply: apply2
3434
3422
  } = editor;
3435
3423
  return editor.apply = (operation) => {
3436
- if (editorActor.getSnapshot().context.readOnly)
3424
+ if (editorActor.getSnapshot().context.readOnly) {
3425
+ apply2(operation);
3437
3426
  return;
3427
+ }
3438
3428
  if (isChangingRemotely(editor)) {
3439
3429
  apply2(operation);
3440
3430
  return;
@@ -3517,13 +3507,13 @@ function createWithObjectKeys(editorActor, schemaTypes) {
3517
3507
  }, editor;
3518
3508
  };
3519
3509
  }
3520
- const debug$g = debugWithName("applyPatches"), debugVerbose$2 = debug$g.enabled && !0;
3510
+ const debug$f = debugWithName("applyPatches"), debugVerbose$1 = debug$f.enabled && !0;
3521
3511
  function createApplyPatch(schemaTypes) {
3522
3512
  return (editor, patch) => {
3523
3513
  let changed = !1;
3524
- debugVerbose$2 && (debug$g(`
3514
+ debugVerbose$1 && (debug$f(`
3525
3515
 
3526
- NEW PATCH =============================================================`), debug$g(JSON.stringify(patch, null, 2)));
3516
+ NEW PATCH =============================================================`), debug$f(JSON.stringify(patch, null, 2)));
3527
3517
  try {
3528
3518
  switch (patch.type) {
3529
3519
  case "insert":
@@ -3539,7 +3529,7 @@ NEW PATCH =============================================================`), debug
3539
3529
  changed = diffMatchPatch(editor, patch);
3540
3530
  break;
3541
3531
  default:
3542
- debug$g("Unhandled patch", patch.type);
3532
+ debug$f("Unhandled patch", patch.type);
3543
3533
  }
3544
3534
  } catch (err) {
3545
3535
  console.error(err);
@@ -3554,9 +3544,9 @@ function diffMatchPatch(editor, patch) {
3554
3544
  childPath
3555
3545
  } = findBlockAndChildFromPath(editor, patch.path);
3556
3546
  if (!block)
3557
- return debug$g("Block not found"), !1;
3547
+ return debug$f("Block not found"), !1;
3558
3548
  if (!child || !childPath)
3559
- return debug$g("Child not found"), !1;
3549
+ return debug$f("Child not found"), !1;
3560
3550
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !Text.isText(child))
3561
3551
  return !1;
3562
3552
  const patches = parse(patch.value), [newValue] = apply(patches, child.text, {
@@ -3586,9 +3576,9 @@ function insertPatch(editor, patch, schemaTypes) {
3586
3576
  childPath: targetChildPath
3587
3577
  } = findBlockAndChildFromPath(editor, patch.path);
3588
3578
  if (!targetBlock || !targetBlockPath)
3589
- return debug$g("Block not found"), !1;
3579
+ return debug$f("Block not found"), !1;
3590
3580
  if (patch.path.length > 1 && patch.path[1] !== "children")
3591
- return debug$g("Ignoring patch targeting void value"), !1;
3581
+ return debug$f("Ignoring patch targeting void value"), !1;
3592
3582
  if (patch.path.length === 1) {
3593
3583
  const {
3594
3584
  items: items2,
@@ -3596,7 +3586,7 @@ function insertPatch(editor, patch, schemaTypes) {
3596
3586
  } = patch, blocksToInsert = toSlateValue(items2, {
3597
3587
  schemaTypes
3598
3588
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetBlockIndex = targetBlockPath[0], normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex;
3599
- return debug$g(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), Transforms.insertNodes(editor, blocksToInsert, {
3589
+ return debug$f(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), Transforms.insertNodes(editor, blocksToInsert, {
3600
3590
  at: [normalizedIdx2]
3601
3591
  }), debugState(editor, "after"), !0;
3602
3592
  }
@@ -3605,14 +3595,14 @@ function insertPatch(editor, patch, schemaTypes) {
3605
3595
  position
3606
3596
  } = patch;
3607
3597
  if (!targetChild || !targetChildPath)
3608
- return debug$g("Child not found"), !1;
3598
+ return debug$f("Child not found"), !1;
3609
3599
  const childrenToInsert = targetBlock && toSlateValue([{
3610
3600
  ...targetBlock,
3611
3601
  children: items
3612
3602
  }], {
3613
3603
  schemaTypes
3614
3604
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetChildIndex = targetChildPath[1], normalizedIdx = position === "after" ? targetChildIndex + 1 : targetChildIndex, childInsertPath = [targetChildPath[0], normalizedIdx];
3615
- return debug$g(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && Element$1.isElement(childrenToInsert[0]) && Transforms.insertNodes(editor, childrenToInsert[0].children, {
3605
+ return debug$f(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && Element$1.isElement(childrenToInsert[0]) && Transforms.insertNodes(editor, childrenToInsert[0].children, {
3616
3606
  at: childInsertPath
3617
3607
  }), debugState(editor, "after"), !0;
3618
3608
  }
@@ -3626,14 +3616,14 @@ function setPatch(editor, patch) {
3626
3616
  childPath
3627
3617
  } = findBlockAndChildFromPath(editor, patch.path);
3628
3618
  if (!block)
3629
- return debug$g("Block not found"), !1;
3619
+ return debug$f("Block not found"), !1;
3630
3620
  const isTextBlock = editor.isTextBlock(block);
3631
3621
  if (isTextBlock && patch.path.length > 1 && patch.path[1] !== "children")
3632
- return debug$g("Ignoring setting void value"), !1;
3622
+ return debug$f("Ignoring setting void value"), !1;
3633
3623
  if (debugState(editor, "before"), isTextBlock && child && childPath) {
3634
3624
  if (Text.isText(value) && Text.isText(child)) {
3635
3625
  const newText = child.text;
3636
- value.text !== newText && (debug$g("Setting text property"), editor.apply({
3626
+ value.text !== newText && (debug$f("Setting text property"), editor.apply({
3637
3627
  type: "remove_text",
3638
3628
  path: childPath,
3639
3629
  offset: 0,
@@ -3645,7 +3635,7 @@ function setPatch(editor, patch) {
3645
3635
  text: value.text
3646
3636
  }), editor.onChange());
3647
3637
  } else
3648
- debug$g("Setting non-text property"), editor.apply({
3638
+ debug$f("Setting non-text property"), editor.apply({
3649
3639
  type: "set_node",
3650
3640
  path: childPath,
3651
3641
  properties: {},
@@ -3653,7 +3643,7 @@ function setPatch(editor, patch) {
3653
3643
  });
3654
3644
  return !0;
3655
3645
  } else if (Element$1.isElement(block) && patch.path.length === 1 && blockPath) {
3656
- debug$g("Setting block property");
3646
+ debug$f("Setting block property");
3657
3647
  const {
3658
3648
  children,
3659
3649
  ...nextRest
@@ -3670,7 +3660,7 @@ function setPatch(editor, patch) {
3670
3660
  ...prevRest
3671
3661
  },
3672
3662
  newProperties: nextRest
3673
- }), debug$g("Setting children"), block.children.forEach((c2, cIndex) => {
3663
+ }), debug$f("Setting children"), block.children.forEach((c2, cIndex) => {
3674
3664
  editor.apply({
3675
3665
  type: "remove_node",
3676
3666
  path: blockPath.concat(block.children.length - 1 - cIndex),
@@ -3696,7 +3686,7 @@ function setPatch(editor, patch) {
3696
3686
  }
3697
3687
  function unsetPatch(editor, patch) {
3698
3688
  if (patch.path.length === 0) {
3699
- debug$g("Removing everything"), debugState(editor, "before");
3689
+ debug$f("Removing everything"), debugState(editor, "before");
3700
3690
  const previousSelection = editor.selection;
3701
3691
  return Transforms.deselect(editor), editor.children.forEach((_child, i) => {
3702
3692
  Transforms.removeNodes(editor, {
@@ -3723,13 +3713,13 @@ function unsetPatch(editor, patch) {
3723
3713
  } = findBlockAndChildFromPath(editor, patch.path);
3724
3714
  if (patch.path.length === 1) {
3725
3715
  if (!block || !blockPath)
3726
- return debug$g("Block not found"), !1;
3716
+ return debug$f("Block not found"), !1;
3727
3717
  const blockIndex = blockPath[0];
3728
- return debug$g(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), Transforms.removeNodes(editor, {
3718
+ return debug$f(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), Transforms.removeNodes(editor, {
3729
3719
  at: [blockIndex]
3730
3720
  }), debugState(editor, "after"), !0;
3731
3721
  }
3732
- 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)}`), Transforms.removeNodes(editor, {
3722
+ 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)}`), Transforms.removeNodes(editor, {
3733
3723
  at: childPath
3734
3724
  }), debugState(editor, "after"), !0) : !1;
3735
3725
  }
@@ -3737,7 +3727,7 @@ function isKeyedSegment(segment) {
3737
3727
  return typeof segment == "object" && "_key" in segment;
3738
3728
  }
3739
3729
  function debugState(editor, stateName) {
3740
- debugVerbose$2 && (debug$g(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$g(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3730
+ debugVerbose$1 && (debug$f(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$f(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
3741
3731
  }
3742
3732
  function findBlockFromPath(editor, path) {
3743
3733
  let blockIndex = -1;
@@ -3779,7 +3769,7 @@ function findBlockAndChildFromPath(editor, path) {
3779
3769
  childPath: void 0
3780
3770
  };
3781
3771
  }
3782
- const debug$f = debugWithName("plugin:withPatches");
3772
+ const debug$e = debugWithName("plugin:withPatches");
3783
3773
  function createWithPatches({
3784
3774
  editorActor,
3785
3775
  patchFunctions,
@@ -3805,7 +3795,7 @@ function createWithPatches({
3805
3795
  withoutPatching(editor, () => {
3806
3796
  withoutSaving(editor, () => {
3807
3797
  patches.forEach((patch) => {
3808
- debug$f.enabled && debug$f(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3798
+ debug$e.enabled && debug$e(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
3809
3799
  });
3810
3800
  });
3811
3801
  });
@@ -3818,10 +3808,10 @@ function createWithPatches({
3818
3808
  remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
3819
3809
  };
3820
3810
  return subscriptions.push(() => {
3821
- debug$f("Subscribing to remote patches");
3811
+ debug$e("Subscribing to remote patches");
3822
3812
  const sub = editorActor.on("patches", handlePatches);
3823
3813
  return () => {
3824
- debug$f("Unsubscribing to remote patches"), sub.unsubscribe();
3814
+ debug$e("Unsubscribing to remote patches"), sub.unsubscribe();
3825
3815
  };
3826
3816
  }), editor.apply = (operation) => {
3827
3817
  if (editorActor.getSnapshot().context.readOnly)
@@ -3874,37 +3864,39 @@ function createWithPatches({
3874
3864
  }, editor;
3875
3865
  };
3876
3866
  }
3877
- const debug$e = debugWithName("plugin:withPlaceholderBlock");
3867
+ const debug$d = debugWithName("plugin:withPlaceholderBlock");
3878
3868
  function createWithPlaceholderBlock(editorActor) {
3879
3869
  return function(editor) {
3880
3870
  const {
3881
3871
  apply: apply2
3882
3872
  } = editor;
3883
3873
  return editor.apply = (op) => {
3884
- if (!editorActor.getSnapshot().context.readOnly) {
3885
- if (isChangingRemotely(editor)) {
3886
- apply2(op);
3887
- return;
3888
- }
3889
- if (isUndoing(editor) || isRedoing(editor)) {
3890
- apply2(op);
3891
- return;
3892
- }
3893
- if (op.type === "remove_node") {
3894
- const node = op.node;
3895
- if (op.path[0] === 0 && Editor.isVoid(editor, node)) {
3896
- const nextPath = Path.next(op.path);
3897
- editor.children[nextPath[0]] || (debug$e("Adding placeholder block"), Editor.insertNode(editor, editor.pteCreateTextBlock({
3898
- decorators: []
3899
- })));
3900
- }
3901
- }
3874
+ if (editorActor.getSnapshot().context.readOnly) {
3875
+ apply2(op);
3876
+ return;
3877
+ }
3878
+ if (isChangingRemotely(editor)) {
3879
+ apply2(op);
3880
+ return;
3881
+ }
3882
+ if (isUndoing(editor) || isRedoing(editor)) {
3902
3883
  apply2(op);
3884
+ return;
3903
3885
  }
3886
+ if (op.type === "remove_node") {
3887
+ const node = op.node;
3888
+ if (op.path[0] === 0 && Editor.isVoid(editor, node)) {
3889
+ const nextPath = Path.next(op.path);
3890
+ editor.children[nextPath[0]] || (debug$d("Adding placeholder block"), Editor.insertNode(editor, editor.pteCreateTextBlock({
3891
+ decorators: []
3892
+ })));
3893
+ }
3894
+ }
3895
+ apply2(op);
3904
3896
  }, editor;
3905
3897
  };
3906
3898
  }
3907
- const debug$d = debugWithName("plugin:withPortableTextBlockStyle");
3899
+ const debug$c = debugWithName("plugin:withPortableTextBlockStyle");
3908
3900
  function createWithPortableTextBlockStyle(editorActor, types) {
3909
3901
  const defaultStyle = types.styles[0].value;
3910
3902
  return function(editor) {
@@ -3917,7 +3909,7 @@ function createWithPortableTextBlockStyle(editorActor, types) {
3917
3909
  if (op.type === "split_node" && op.path.length === 1 && editor.isTextBlock(op.properties) && op.properties.style !== defaultStyle && op.path[0] === path[0] && !Path.equals(path, op.path)) {
3918
3910
  const [child] = Editor.node(editor, [op.path[0] + 1, 0]);
3919
3911
  if (Text.isText(child) && child.text === "") {
3920
- debug$d(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3912
+ debug$c(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
3921
3913
  type: "normalizing"
3922
3914
  }), Transforms.setNodes(editor, {
3923
3915
  style: defaultStyle
@@ -3939,12 +3931,12 @@ function createWithPortableTextBlockStyle(editorActor, types) {
3939
3931
  at: editor.selection,
3940
3932
  match: (node) => editor.isTextBlock(node)
3941
3933
  })].forEach(([node, path]) => {
3942
- editor.isTextBlock(node) && node.style === blockStyle ? (debug$d(`Unsetting block style '${blockStyle}'`), Transforms.setNodes(editor, {
3934
+ editor.isTextBlock(node) && node.style === blockStyle ? (debug$c(`Unsetting block style '${blockStyle}'`), Transforms.setNodes(editor, {
3943
3935
  ...node,
3944
3936
  style: defaultStyle
3945
3937
  }, {
3946
3938
  at: path
3947
- })) : (blockStyle ? debug$d(`Setting style '${blockStyle}'`) : debug$d("Setting default style", defaultStyle), Transforms.setNodes(editor, {
3939
+ })) : (blockStyle ? debug$c(`Setting style '${blockStyle}'`) : debug$c("Setting default style", defaultStyle), Transforms.setNodes(editor, {
3948
3940
  ...node,
3949
3941
  style: blockStyle || defaultStyle
3950
3942
  }, {
@@ -3954,11 +3946,11 @@ function createWithPortableTextBlockStyle(editorActor, types) {
3954
3946
  }, editor;
3955
3947
  };
3956
3948
  }
3957
- const debug$c = debugWithName("plugin:withPortableTextLists"), MAX_LIST_LEVEL = 10;
3949
+ const debug$b = debugWithName("plugin:withPortableTextLists"), MAX_LIST_LEVEL = 10;
3958
3950
  function createWithPortableTextLists(types) {
3959
3951
  return function(editor) {
3960
3952
  return editor.pteToggleListItem = (listItemStyle) => {
3961
- editor.pteHasListStyle(listItemStyle) ? (debug$c(`Remove list item '${listItemStyle}'`), editor.pteUnsetListItem(listItemStyle)) : (debug$c(`Add list item '${listItemStyle}'`), editor.pteSetListItem(listItemStyle));
3953
+ editor.pteHasListStyle(listItemStyle) ? (debug$b(`Remove list item '${listItemStyle}'`), editor.pteUnsetListItem(listItemStyle)) : (debug$b(`Add list item '${listItemStyle}'`), editor.pteSetListItem(listItemStyle));
3962
3954
  }, editor.pteUnsetListItem = (listItemStyle) => {
3963
3955
  editor.selection && [...Editor.nodes(editor, {
3964
3956
  at: editor.selection,
@@ -3974,7 +3966,7 @@ function createWithPortableTextLists(types) {
3974
3966
  listItem: void 0,
3975
3967
  level: void 0
3976
3968
  };
3977
- debug$c(`Unsetting list '${listItemStyle}'`), Transforms.setNodes(editor, newNode, {
3969
+ debug$b(`Unsetting list '${listItemStyle}'`), Transforms.setNodes(editor, newNode, {
3978
3970
  at: path
3979
3971
  });
3980
3972
  }
@@ -3984,7 +3976,7 @@ function createWithPortableTextLists(types) {
3984
3976
  at: editor.selection,
3985
3977
  match: (node) => editor.isTextBlock(node)
3986
3978
  })].forEach(([node, path]) => {
3987
- debug$c(`Setting list '${listItemStyle}'`), Transforms.setNodes(editor, {
3979
+ debug$b(`Setting list '${listItemStyle}'`), Transforms.setNodes(editor, {
3988
3980
  ...node,
3989
3981
  level: 1,
3990
3982
  listItem: listItemStyle || types.lists[0] && types.lists[0].value
@@ -4000,7 +3992,7 @@ function createWithPortableTextLists(types) {
4000
3992
  match: (node) => Element$1.isElement(node) && editor.isListBlock(node) && node.children.length === 1 && Text.isText(node.children[0]) && node.children[0].text === ""
4001
3993
  })];
4002
3994
  return selectedBlocks.length === 0 ? !1 : (selectedBlocks.forEach(([node, path]) => {
4003
- Element$1.isElement(node) && (debug$c("Unset list"), Transforms.setNodes(editor, {
3995
+ Element$1.isElement(node) && (debug$b("Unset list"), Transforms.setNodes(editor, {
4004
3996
  ...node,
4005
3997
  level: void 0,
4006
3998
  listItem: void 0
@@ -4018,7 +4010,7 @@ function createWithPortableTextLists(types) {
4018
4010
  return selectedBlocks.length === 0 ? !1 : (selectedBlocks.forEach(([node, path]) => {
4019
4011
  if (editor.isListBlock(node)) {
4020
4012
  let level = node.level || 1;
4021
- 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)))), Transforms.setNodes(editor, {
4013
+ 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)))), Transforms.setNodes(editor, {
4022
4014
  level: Math.min(MAX_LIST_LEVEL, Math.max(1, level))
4023
4015
  }, {
4024
4016
  at: path
@@ -4064,7 +4056,7 @@ function getNextSpan({
4064
4056
  }
4065
4057
  return nextSpan;
4066
4058
  }
4067
- const debug$b = debugWithName("plugin:withPortableTextMarkModel");
4059
+ const debug$a = debugWithName("plugin:withPortableTextMarkModel");
4068
4060
  function createWithPortableTextMarkModel(editorActor, types) {
4069
4061
  return function(editor) {
4070
4062
  const {
@@ -4078,7 +4070,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4078
4070
  for (const [child, childPath] of children) {
4079
4071
  const nextNode = node.children[childPath[1] + 1];
4080
4072
  if (editor.isTextSpan(child) && editor.isTextSpan(nextNode) && child.marks?.every((mark) => nextNode.marks?.includes(mark)) && nextNode.marks?.every((mark) => child.marks?.includes(mark))) {
4081
- debug$b("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
4073
+ debug$a("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), editorActor.send({
4082
4074
  type: "normalizing"
4083
4075
  }), Transforms.mergeNodes(editor, {
4084
4076
  at: [childPath[0], childPath[1] + 1],
@@ -4091,7 +4083,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4091
4083
  }
4092
4084
  }
4093
4085
  if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {
4094
- debug$b("Adding .markDefs to block node"), editorActor.send({
4086
+ debug$a("Adding .markDefs to block node"), editorActor.send({
4095
4087
  type: "normalizing"
4096
4088
  }), Transforms.setNodes(editor, {
4097
4089
  markDefs: []
@@ -4103,7 +4095,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4103
4095
  return;
4104
4096
  }
4105
4097
  if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {
4106
- debug$b("Adding .marks to span node"), editorActor.send({
4098
+ debug$a("Adding .marks to span node"), editorActor.send({
4107
4099
  type: "normalizing"
4108
4100
  }), Transforms.setNodes(editor, {
4109
4101
  marks: []
@@ -4117,7 +4109,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4117
4109
  if (editor.isTextSpan(node)) {
4118
4110
  const blockPath = Path.parent(path), [block] = Editor.node(editor, blockPath), decorators2 = types.decorators.map((decorator) => decorator.value), annotations = node.marks?.filter((mark) => !decorators2.includes(mark));
4119
4111
  if (editor.isTextBlock(block) && node.text === "" && annotations && annotations.length > 0) {
4120
- debug$b("Removing annotations from empty span node"), editorActor.send({
4112
+ debug$a("Removing annotations from empty span node"), editorActor.send({
4121
4113
  type: "normalizing"
4122
4114
  }), Transforms.setNodes(editor, {
4123
4115
  marks: node.marks?.filter((mark) => decorators2.includes(mark))
@@ -4135,7 +4127,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4135
4127
  if (editor.isTextSpan(child)) {
4136
4128
  const marks = child.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !node.markDefs?.find((def) => def._key === mark));
4137
4129
  if (orphanedAnnotations.length > 0) {
4138
- debug$b("Removing orphaned annotations from span node"), editorActor.send({
4130
+ debug$a("Removing orphaned annotations from span node"), editorActor.send({
4139
4131
  type: "normalizing"
4140
4132
  }), Transforms.setNodes(editor, {
4141
4133
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
@@ -4153,7 +4145,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4153
4145
  if (editor.isTextBlock(block)) {
4154
4146
  const decorators2 = types.decorators.map((decorator) => decorator.value), marks = node.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !block.markDefs?.find((def) => def._key === mark));
4155
4147
  if (orphanedAnnotations.length > 0) {
4156
- debug$b("Removing orphaned annotations from span node"), editorActor.send({
4148
+ debug$a("Removing orphaned annotations from span node"), editorActor.send({
4157
4149
  type: "normalizing"
4158
4150
  }), Transforms.setNodes(editor, {
4159
4151
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
@@ -4171,7 +4163,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4171
4163
  for (const markDef of markDefs)
4172
4164
  markDefKeys.has(markDef._key) || (markDefKeys.add(markDef._key), newMarkDefs.push(markDef));
4173
4165
  if (markDefs.length !== newMarkDefs.length) {
4174
- debug$b("Removing duplicate markDefs"), editorActor.send({
4166
+ debug$a("Removing duplicate markDefs"), editorActor.send({
4175
4167
  type: "normalizing"
4176
4168
  }), Transforms.setNodes(editor, {
4177
4169
  markDefs: newMarkDefs
@@ -4186,7 +4178,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4186
4178
  if (editor.isTextBlock(node) && !editor.operations.some((op) => op.type === "merge_node" && "markDefs" in op.properties && op.path.length === 1)) {
4187
4179
  const newMarkDefs = (node.markDefs || []).filter((def) => node.children.find((child) => Text.isText(child) && Array.isArray(child.marks) && child.marks.includes(def._key)));
4188
4180
  if (node.markDefs && !isEqual(newMarkDefs, node.markDefs)) {
4189
- debug$b("Removing markDef not in use"), editorActor.send({
4181
+ debug$a("Removing markDef not in use"), editorActor.send({
4190
4182
  type: "normalizing"
4191
4183
  }), Transforms.setNodes(editor, {
4192
4184
  markDefs: newMarkDefs
@@ -4403,7 +4395,7 @@ function createWithPortableTextMarkModel(editorActor, types) {
4403
4395
  const [targetBlock, targetPath] = Editor.node(editor, [op.path[0] - 1]);
4404
4396
  if (editor.isTextBlock(targetBlock)) {
4405
4397
  const oldDefs = Array.isArray(targetBlock.markDefs) && targetBlock.markDefs || [], newMarkDefs = uniq([...oldDefs, ...op.properties.markDefs]);
4406
- debug$b("Copying markDefs over to merged block", op), Transforms.setNodes(editor, {
4398
+ debug$a("Copying markDefs over to merged block", op), Transforms.setNodes(editor, {
4407
4399
  markDefs: newMarkDefs
4408
4400
  }, {
4409
4401
  at: targetPath,
@@ -4555,7 +4547,7 @@ const toggleDecoratorActionImplementation = ({
4555
4547
  decorator: action.decorator
4556
4548
  }
4557
4549
  });
4558
- }, debug$a = debugWithName("plugin:withPortableTextSelections"), debugVerbose$1 = debug$a.enabled && !1;
4550
+ }, debug$9 = debugWithName("plugin:withPortableTextSelections"), debugVerbose = debug$9.enabled && !1;
4559
4551
  function createWithPortableTextSelections(editorActor, types) {
4560
4552
  let prevSelection = null;
4561
4553
  return function(editor) {
@@ -4571,7 +4563,7 @@ function createWithPortableTextSelections(editorActor, types) {
4571
4563
  ptRange = toPortableTextRange(value, editor.selection, types), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
4572
4564
  }
4573
4565
  }
4574
- debugVerbose$1 && debug$a(`Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(editor.selection)})`), ptRange ? editorActor.send({
4566
+ debugVerbose && debug$9(`Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(editor.selection)})`), ptRange ? editorActor.send({
4575
4567
  type: "selection",
4576
4568
  selection: ptRange
4577
4569
  }) : editorActor.send({
@@ -4589,7 +4581,7 @@ function createWithPortableTextSelections(editorActor, types) {
4589
4581
  }, editor;
4590
4582
  };
4591
4583
  }
4592
- const debug$9 = debugWithName("plugin:withSchemaTypes");
4584
+ const debug$8 = debugWithName("plugin:withSchemaTypes");
4593
4585
  function createWithSchemaTypes({
4594
4586
  editorActor,
4595
4587
  schemaTypes
@@ -4602,7 +4594,7 @@ function createWithSchemaTypes({
4602
4594
  return editor.normalizeNode = (entry) => {
4603
4595
  const [node, path] = entry;
4604
4596
  if (node._type === void 0 && path.length === 2) {
4605
- debug$9("Setting span type on text node without a type");
4597
+ debug$8("Setting span type on text node without a type");
4606
4598
  const span = node, key = span._key || editorActor.getSnapshot().context.keyGenerator();
4607
4599
  editorActor.send({
4608
4600
  type: "normalizing"
@@ -4618,7 +4610,7 @@ function createWithSchemaTypes({
4618
4610
  return;
4619
4611
  }
4620
4612
  if (node._key === void 0 && (path.length === 1 || path.length === 2)) {
4621
- debug$9("Setting missing key on child node without a key");
4613
+ debug$8("Setting missing key on child node without a key");
4622
4614
  const key = editorActor.getSnapshot().context.keyGenerator();
4623
4615
  editorActor.send({
4624
4616
  type: "normalizing"
@@ -4635,7 +4627,7 @@ function createWithSchemaTypes({
4635
4627
  }, editor;
4636
4628
  };
4637
4629
  }
4638
- const debug$8 = debugWithName("plugin:withUtils");
4630
+ const debug$7 = debugWithName("plugin:withUtils");
4639
4631
  function createWithUtils({
4640
4632
  editorActor,
4641
4633
  schemaTypes
@@ -4650,14 +4642,14 @@ function createWithUtils({
4650
4642
  depth: 2
4651
4643
  });
4652
4644
  if (!textNode || !Text.isText(textNode) || textNode.text.length === 0) {
4653
- debug$8("pteExpandToWord: Can't expand to word here");
4645
+ debug$7("pteExpandToWord: Can't expand to word here");
4654
4646
  return;
4655
4647
  }
4656
4648
  const {
4657
4649
  focus
4658
4650
  } = 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);
4659
4651
  if (!(newStartOffset === newEndOffset || Number.isNaN(newStartOffset) || Number.isNaN(newEndOffset))) {
4660
- debug$8("pteExpandToWord: Expanding to focused word"), Transforms.setSelection(editor, {
4652
+ debug$7("pteExpandToWord: Expanding to focused word"), Transforms.setSelection(editor, {
4661
4653
  anchor: {
4662
4654
  ...selection.anchor,
4663
4655
  offset: newStartOffset
@@ -4669,7 +4661,7 @@ function createWithUtils({
4669
4661
  });
4670
4662
  return;
4671
4663
  }
4672
- debug$8("pteExpandToWord: Can't expand to word here");
4664
+ debug$7("pteExpandToWord: Can't expand to word here");
4673
4665
  }
4674
4666
  }, editor.pteCreateTextBlock = (options) => toSlateValue([{
4675
4667
  _type: schemaTypes.block.name,
@@ -4695,16 +4687,10 @@ function createWithUtils({
4695
4687
  })[0], editor;
4696
4688
  };
4697
4689
  }
4698
- const originalFnMap = /* @__PURE__ */ new WeakMap(), withPlugins = (editor, options) => {
4690
+ const withPlugins = (editor, options) => {
4699
4691
  const e = editor, {
4700
4692
  editorActor
4701
- } = options, schemaTypes = editorActor.getSnapshot().context.schema;
4702
- e.destroy ? e.destroy() : originalFnMap.set(e, {
4703
- apply: e.apply,
4704
- onChange: e.onChange,
4705
- normalizeNode: e.normalizeNode
4706
- });
4707
- const operationToPatches = createOperationToPatches(schemaTypes), withObjectKeys = createWithObjectKeys(editorActor, schemaTypes), withSchemaTypes = createWithSchemaTypes({
4693
+ } = options, schemaTypes = editorActor.getSnapshot().context.schema, operationToPatches = createOperationToPatches(schemaTypes), withObjectKeys = createWithObjectKeys(editorActor, schemaTypes), withSchemaTypes = createWithSchemaTypes({
4708
4694
  editorActor,
4709
4695
  schemaTypes
4710
4696
  }), withPatches = createWithPatches({
@@ -4719,38 +4705,21 @@ const originalFnMap = /* @__PURE__ */ new WeakMap(), withPlugins = (editor, opti
4719
4705
  }), withPortableTextMarkModel = createWithPortableTextMarkModel(editorActor, schemaTypes), withPortableTextBlockStyle = createWithPortableTextBlockStyle(editorActor, schemaTypes), withPlaceholderBlock = createWithPlaceholderBlock(editorActor), withUtils = createWithUtils({
4720
4706
  editorActor,
4721
4707
  schemaTypes
4722
- }), withPortableTextSelections = createWithPortableTextSelections(editorActor, schemaTypes), withEventListeners = createWithEventListeners(editorActor, options.subscriptions);
4723
- return e.destroy = () => {
4724
- const originalFunctions = originalFnMap.get(e);
4725
- if (!originalFunctions)
4726
- throw new Error("Could not find pristine versions of editor functions");
4727
- e.apply = originalFunctions.apply, e.history = {
4728
- undos: [],
4729
- redos: []
4730
- }, e.normalizeNode = originalFunctions.normalizeNode, e.onChange = originalFunctions.onChange;
4731
- }, withEventListeners(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPortableTextLists(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e))))))))))));
4732
- }, debug$7 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
4708
+ }), withPortableTextSelections = createWithPortableTextSelections(editorActor, schemaTypes);
4709
+ return createWithEventListeners(editorActor, options.subscriptions)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPortableTextLists(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e))))))))))));
4710
+ }, debug$6 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
4733
4711
  function createSlateEditor(config) {
4734
4712
  const existingSlateEditor = slateEditors.get(config.editorActor);
4735
4713
  if (existingSlateEditor)
4736
- return debug$7("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
4737
- debug$7("Creating new Slate editor instance", config.editorActor.id);
4738
- let unsubscriptions = [], subscriptions = [];
4739
- const instance = withPlugins(withReact(createEditor()), {
4714
+ return debug$6("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
4715
+ debug$6("Creating new Slate editor instance", config.editorActor.id);
4716
+ const unsubscriptions = [], subscriptions = [], instance = withPlugins(withReact(createEditor$1()), {
4740
4717
  editorActor: config.editorActor,
4741
4718
  subscriptions
4742
4719
  });
4743
4720
  KEY_TO_VALUE_ELEMENT.set(instance, {}), KEY_TO_SLATE_ELEMENT.set(instance, {});
4744
4721
  for (const subscription of subscriptions)
4745
4722
  unsubscriptions.push(subscription());
4746
- config.editorActor.subscribe((snapshot) => {
4747
- if (snapshot.status !== "active") {
4748
- debug$7("Destroying Slate editor"), instance.destroy();
4749
- for (const unsubscribe of unsubscriptions)
4750
- unsubscribe();
4751
- subscriptions = [], unsubscriptions = [];
4752
- }
4753
- });
4754
4723
  const initialValue = [instance.pteCreateTextBlock({
4755
4724
  decorators: []
4756
4725
  })], slateEditor = {
@@ -4759,7 +4728,7 @@ function createSlateEditor(config) {
4759
4728
  };
4760
4729
  return slateEditors.set(config.editorActor, slateEditor), slateEditor;
4761
4730
  }
4762
- const EditorActorContext = createContext({}), debug$6 = debugWithName("API:editable");
4731
+ const debug$5 = debugWithName("API:editable");
4763
4732
  function createEditableAPI(editor, editorActor) {
4764
4733
  const types = editorActor.getSnapshot().context.schema;
4765
4734
  return {
@@ -4840,7 +4809,7 @@ function createEditableAPI(editor, editorActor) {
4840
4809
  }], {
4841
4810
  schemaTypes: editorActor.getSnapshot().context.schema
4842
4811
  })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types.span.name, focusNode = Node.get(editor, focusChildPath);
4843
- return isSpanNode && focusNode._type !== types.span.name && (debug$6("Inserting span child next to inline object child, moving selection + 1"), editor.move({
4812
+ return isSpanNode && focusNode._type !== types.span.name && (debug$5("Inserting span child next to inline object child, moving selection + 1"), editor.move({
4844
4813
  distance: 1,
4845
4814
  unit: "character"
4846
4815
  })), Transforms.insertNodes(editor, child, {
@@ -4972,18 +4941,18 @@ function createEditableAPI(editor, editorActor) {
4972
4941
  throw new Error("Invalid range");
4973
4942
  if (range) {
4974
4943
  if (!options?.mode || options?.mode === "selected") {
4975
- debug$6("Deleting content in selection"), Transforms.delete(editor, {
4944
+ debug$5("Deleting content in selection"), Transforms.delete(editor, {
4976
4945
  at: range,
4977
4946
  hanging: !0,
4978
4947
  voids: !0
4979
4948
  }), editor.onChange();
4980
4949
  return;
4981
4950
  }
4982
- options?.mode === "blocks" && (debug$6("Deleting blocks touched by selection"), Transforms.removeNodes(editor, {
4951
+ options?.mode === "blocks" && (debug$5("Deleting blocks touched by selection"), Transforms.removeNodes(editor, {
4983
4952
  at: range,
4984
4953
  voids: !0,
4985
4954
  match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && Element$1.isElement(node)
4986
- })), options?.mode === "children" && (debug$6("Deleting children touched by selection"), Transforms.removeNodes(editor, {
4955
+ })), options?.mode === "children" && (debug$5("Deleting children touched by selection"), Transforms.removeNodes(editor, {
4987
4956
  at: range,
4988
4957
  voids: !0,
4989
4958
  match: (node) => node._type === types.span.name || // Text children
@@ -5146,7 +5115,7 @@ const addAnnotationActionImplementation = ({
5146
5115
  action
5147
5116
  }) => {
5148
5117
  const editor = action.editor;
5149
- if (debug$6("Removing annotation", action.annotation.name), !!editor.selection)
5118
+ if (debug$5("Removing annotation", action.annotation.name), !!editor.selection)
5150
5119
  if (Range.isCollapsed(editor.selection)) {
5151
5120
  const [block, blockPath] = Editor.node(editor, editor.selection, {
5152
5121
  depth: 1
@@ -5799,8 +5768,8 @@ const editorMachine = setup({
5799
5768
  keyGenerator: input.keyGenerator,
5800
5769
  pendingEvents: [],
5801
5770
  schema: input.schema,
5802
- readOnly: !1,
5803
- maxBlocks: void 0,
5771
+ readOnly: input.readOnly ?? !1,
5772
+ maxBlocks: input.maxBlocks,
5804
5773
  value: input.value
5805
5774
  }),
5806
5775
  on: {
@@ -5905,11 +5874,16 @@ const editorMachine = setup({
5905
5874
  })
5906
5875
  },
5907
5876
  "toggle readOnly": {
5908
- actions: assign({
5877
+ actions: [assign({
5909
5878
  readOnly: ({
5910
5879
  context
5911
5880
  }) => !context.readOnly
5912
- })
5881
+ }), emit(({
5882
+ context
5883
+ }) => ({
5884
+ type: "readOnly toggled",
5885
+ readOnly: context.readOnly
5886
+ }))]
5913
5887
  },
5914
5888
  "update maxBlocks": {
5915
5889
  actions: assign({
@@ -6000,47 +5974,62 @@ const editorMachine = setup({
6000
5974
  }
6001
5975
  }
6002
5976
  }
6003
- }), PortableTextEditorSelectionContext = createContext(null), usePortableTextEditorSelection = () => {
6004
- const selection = useContext(PortableTextEditorSelectionContext);
6005
- if (selection === void 0)
6006
- throw new Error("The `usePortableTextEditorSelection` hook must be used inside the <PortableTextEditor> component's context.");
6007
- return selection;
6008
- }, debug$5 = debugWithName("component:PortableTextEditor:SelectionProvider"), debugVerbose = debug$5.enabled && !1;
6009
- function PortableTextEditorSelectionProvider(props) {
6010
- const $ = c(6), [selection, setSelection] = useState(null);
6011
- let t0, t1;
6012
- $[0] !== props.editorActor ? (t0 = () => {
6013
- debug$5("Subscribing to selection changes");
6014
- const subscription = props.editorActor.on("selection", (event) => {
6015
- startTransition(() => {
6016
- debugVerbose && debug$5("Setting selection"), setSelection(event.selection);
6017
- });
6018
- });
6019
- return () => {
6020
- debug$5("Unsubscribing to selection changes"), subscription.unsubscribe();
6021
- };
6022
- }, t1 = [props.editorActor], $[0] = props.editorActor, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), useEffect(t0, t1);
6023
- let t2;
6024
- return $[3] !== props.children || $[4] !== selection ? (t2 = /* @__PURE__ */ jsx(PortableTextEditorSelectionContext.Provider, { value: selection, children: props.children }), $[3] = props.children, $[4] = selection, $[5] = t2) : t2 = $[5], t2;
6025
- }
6026
- const defaultKeyGenerator = () => randomKey(12), getByteHexTable = /* @__PURE__ */ (() => {
6027
- let table;
6028
- return () => {
6029
- if (table)
6030
- return table;
6031
- table = [];
6032
- for (let i = 0; i < 256; ++i)
6033
- table[i] = (i + 256).toString(16).slice(1);
6034
- return table;
5977
+ });
5978
+ function createEditor(config) {
5979
+ const editorActor = createActor(editorMachine, {
5980
+ input: editorConfigToMachineInput(config)
5981
+ });
5982
+ editorActor.start();
5983
+ const slateEditor = createSlateEditor({
5984
+ editorActor
5985
+ }), editable = createEditableAPI(slateEditor.instance, editorActor);
5986
+ return {
5987
+ send: (event) => {
5988
+ editorActor.send(event);
5989
+ },
5990
+ on: (event, listener) => editorActor.on(
5991
+ event,
5992
+ // @ts-ignore
5993
+ listener
5994
+ ),
5995
+ editable,
5996
+ _internal: {
5997
+ editorActor,
5998
+ slateEditor
5999
+ }
6035
6000
  };
6036
- })();
6037
- function whatwgRNG(length = 16) {
6038
- const rnds8 = new Uint8Array(length);
6039
- return getRandomValues(rnds8), rnds8;
6040
6001
  }
6041
- function randomKey(length) {
6042
- const table = getByteHexTable();
6043
- return whatwgRNG(length).reduce((str, n) => str + table[n], "").slice(0, length);
6002
+ function useEditor(config) {
6003
+ const editorActor = useActorRef(editorMachine, {
6004
+ input: editorConfigToMachineInput(config)
6005
+ }), slateEditor = createSlateEditor({
6006
+ editorActor
6007
+ }), editable = useMemo(() => createEditableAPI(slateEditor.instance, editorActor), [slateEditor.instance, editorActor]), send = useCallback((event) => {
6008
+ editorActor.send(event);
6009
+ }, [editorActor]), on = useCallback((event_0, listener) => editorActor.on(
6010
+ event_0,
6011
+ // @ts-ignore
6012
+ listener
6013
+ ), [editorActor]);
6014
+ return useMemo(() => ({
6015
+ send,
6016
+ on,
6017
+ editable,
6018
+ _internal: {
6019
+ editorActor,
6020
+ slateEditor
6021
+ }
6022
+ }), [send, on, editable, editorActor, slateEditor]);
6023
+ }
6024
+ function editorConfigToMachineInput(config) {
6025
+ return {
6026
+ behaviors: config.behaviors,
6027
+ keyGenerator: config.keyGenerator ?? defaultKeyGenerator,
6028
+ maxBlocks: config.maxBlocks,
6029
+ readOnly: config.readOnly,
6030
+ schema: config.schemaDefinition ? compileSchemaDefinition(config.schemaDefinition) : getPortableTextMemberSchemaTypes(config.schema.hasOwnProperty("jsonType") ? config.schema : compileType(config.schema)),
6031
+ value: config.initialValue
6032
+ };
6044
6033
  }
6045
6034
  const debug$4 = debugWithName("component:PortableTextEditor");
6046
6035
  class PortableTextEditor extends Component {
@@ -6053,66 +6042,49 @@ class PortableTextEditor extends Component {
6053
6042
  * A lookup table for all the relevant schema types for this portable text type.
6054
6043
  */
6055
6044
  /**
6045
+ * The editor instance
6046
+ */
6047
+ /*
6056
6048
  * The editor API (currently implemented with Slate).
6057
6049
  */
6058
6050
  constructor(props) {
6059
- if (super(props), props.editor) {
6060
- const editor = props.editor;
6061
- this.editorActor = editor._internal.editorActor, this.slateEditor = editor._internal.slateEditor, this.editorActor.start(), this.schemaTypes = this.editorActor.getSnapshot().context.schema;
6062
- } else {
6063
- if (!props.schemaType)
6064
- throw new Error('PortableTextEditor: missing "schemaType" property');
6065
- 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 = createActor(editorMachine, {
6066
- input: {
6067
- keyGenerator: props.keyGenerator || defaultKeyGenerator,
6068
- schema: this.schemaTypes,
6069
- value: props.value
6070
- }
6071
- }), this.editorActor.start(), this.slateEditor = createSlateEditor({
6072
- editorActor: this.editorActor
6073
- }), props.readOnly && this.editorActor.send({
6074
- type: "toggle readOnly"
6075
- }), props.maxBlocks && this.editorActor.send({
6076
- type: "update maxBlocks",
6077
- maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10)
6078
- });
6079
- }
6080
- this.editable = createEditableAPI(this.slateEditor.instance, this.editorActor);
6051
+ super(props), props.editor ? this.editor = props.editor : this.editor = createEditor({
6052
+ keyGenerator: props.keyGenerator ?? defaultKeyGenerator,
6053
+ schema: props.schemaType,
6054
+ initialValue: props.value,
6055
+ maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10),
6056
+ readOnly: props.readOnly
6057
+ }), this.schemaTypes = this.editor._internal.editorActor.getSnapshot().context.schema, this.editable = this.editor.editable;
6081
6058
  }
6082
6059
  componentDidUpdate(prevProps) {
6083
- !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({
6060
+ !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({
6084
6061
  type: "update schema",
6085
6062
  schema: this.schemaTypes
6086
- })), !this.props.editor && !prevProps.editor && (this.props.readOnly !== prevProps.readOnly && this.editorActor.send({
6063
+ })), !this.props.editor && !prevProps.editor && (this.props.readOnly !== prevProps.readOnly && this.editor._internal.editorActor.send({
6087
6064
  type: "toggle readOnly"
6088
- }), this.props.maxBlocks !== prevProps.maxBlocks && this.editorActor.send({
6065
+ }), this.props.maxBlocks !== prevProps.maxBlocks && this.editor._internal.editorActor.send({
6089
6066
  type: "update maxBlocks",
6090
6067
  maxBlocks: this.props.maxBlocks === void 0 ? void 0 : Number.parseInt(this.props.maxBlocks.toString(), 10)
6091
- }), this.props.value !== prevProps.value && this.editorActor.send({
6068
+ }), this.props.value !== prevProps.value && this.editor._internal.editorActor.send({
6092
6069
  type: "update value",
6093
6070
  value: this.props.value
6094
6071
  }), this.props.editorRef !== prevProps.editorRef && this.props.editorRef && (this.props.editorRef.current = this));
6095
6072
  }
6096
6073
  setEditable = (editable) => {
6097
- this.editable = {
6098
- ...this.editable,
6074
+ this.editor.editable = {
6075
+ ...this.editor.editable,
6099
6076
  ...editable
6100
6077
  };
6101
6078
  };
6102
- getValue = () => {
6103
- if (this.editable)
6104
- return this.editable.getValue();
6105
- };
6106
6079
  render() {
6107
6080
  const legacyPatches = this.props.editor ? void 0 : this.props.incomingPatches$ ?? this.props.patches$;
6108
6081
  return /* @__PURE__ */ jsxs(Fragment, { children: [
6109
- legacyPatches ? /* @__PURE__ */ jsx(RoutePatchesObservableToEditorActor, { editorActor: this.editorActor, patches$: legacyPatches }) : null,
6110
- /* @__PURE__ */ jsx(EditorActorContext.Provider, { value: this.editorActor, children: /* @__PURE__ */ jsx(Slate, { editor: this.slateEditor.instance, initialValue: this.slateEditor.initialValue, children: /* @__PURE__ */ jsx(PortableTextEditorContext.Provider, { value: this, children: /* @__PURE__ */ jsxs(PortableTextEditorSelectionProvider, { editorActor: this.editorActor, children: [
6111
- /* @__PURE__ */ jsx(Synchronizer, { editorActor: this.editorActor, getValue: this.getValue, onChange: (change) => {
6112
- this.props.editor || this.props.onChange(change), this.change$.next(change);
6113
- } }),
6114
- this.props.children
6115
- ] }) }) }) })
6082
+ legacyPatches ? /* @__PURE__ */ jsx(RoutePatchesObservableToEditorActor, { editorActor: this.editor._internal.editorActor, patches$: legacyPatches }) : null,
6083
+ /* @__PURE__ */ jsx(RouteEventsToChanges, { editorActor: this.editor._internal.editorActor, onChange: (change) => {
6084
+ this.props.editor || this.props.onChange(change), this.change$.next(change);
6085
+ } }),
6086
+ /* @__PURE__ */ jsx(Synchronizer, { editorActor: this.editor._internal.editorActor, getValue: this.editor.editable.getValue, portableTextEditor: this, slateEditor: this.editor._internal.slateEditor.instance }),
6087
+ /* @__PURE__ */ jsx(EditorActorContext.Provider, { value: this.editor._internal.editorActor, children: /* @__PURE__ */ jsx(Slate, { editor: this.editor._internal.slateEditor.instance, initialValue: this.editor._internal.slateEditor.initialValue, children: /* @__PURE__ */ jsx(PortableTextEditorContext.Provider, { value: this, children: /* @__PURE__ */ jsx(PortableTextEditorSelectionProvider, { editorActor: this.editor._internal.editorActor, children: this.props.children }) }) }) })
6116
6088
  ] });
6117
6089
  }
6118
6090
  // Static API methods
@@ -6180,6 +6152,79 @@ function RoutePatchesObservableToEditorActor(props) {
6180
6152
  };
6181
6153
  }, t1 = [props.editorActor, props.patches$], $[0] = props.editorActor, $[1] = props.patches$, $[2] = t0, $[3] = t1) : (t0 = $[2], t1 = $[3]), useEffect(t0, t1), null;
6182
6154
  }
6155
+ function RouteEventsToChanges(props) {
6156
+ const $ = c(6);
6157
+ let t0;
6158
+ $[0] !== props ? (t0 = (change) => props.onChange(change), $[0] = props, $[1] = t0) : t0 = $[1];
6159
+ const handleChange = useEffectEvent(t0);
6160
+ let t1, t2;
6161
+ return $[2] !== handleChange || $[3] !== props.editorActor ? (t1 = () => {
6162
+ debug$4("Subscribing to editor changes");
6163
+ const sub = props.editorActor.on("*", (event) => {
6164
+ bb5: switch (event.type) {
6165
+ case "patch": {
6166
+ handleChange(event);
6167
+ break bb5;
6168
+ }
6169
+ case "loading": {
6170
+ handleChange({
6171
+ type: "loading",
6172
+ isLoading: !0
6173
+ });
6174
+ break bb5;
6175
+ }
6176
+ case "done loading": {
6177
+ handleChange({
6178
+ type: "loading",
6179
+ isLoading: !1
6180
+ });
6181
+ break bb5;
6182
+ }
6183
+ case "focused": {
6184
+ handleChange({
6185
+ type: "focus",
6186
+ event: event.event
6187
+ });
6188
+ break bb5;
6189
+ }
6190
+ case "value changed": {
6191
+ handleChange({
6192
+ type: "value",
6193
+ value: event.value
6194
+ });
6195
+ break bb5;
6196
+ }
6197
+ case "invalid value": {
6198
+ handleChange({
6199
+ type: "invalidValue",
6200
+ resolution: event.resolution,
6201
+ value: event.value
6202
+ });
6203
+ break bb5;
6204
+ }
6205
+ case "error": {
6206
+ handleChange({
6207
+ ...event,
6208
+ level: "warning"
6209
+ });
6210
+ break bb5;
6211
+ }
6212
+ case "annotation.add":
6213
+ case "annotation.remove":
6214
+ case "annotation.toggle":
6215
+ case "focus":
6216
+ case "patches":
6217
+ case "readOnly toggled":
6218
+ break bb5;
6219
+ default:
6220
+ handleChange(event);
6221
+ }
6222
+ });
6223
+ return () => {
6224
+ debug$4("Unsubscribing to changes"), sub.unsubscribe();
6225
+ };
6226
+ }, t2 = [props.editorActor, handleChange], $[2] = handleChange, $[3] = props.editorActor, $[4] = t1, $[5] = t2) : (t1 = $[4], t2 = $[5]), useEffect(t1, t2), null;
6227
+ }
6183
6228
  const debug$3 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (props) => {
6184
6229
  const {
6185
6230
  editorActor,
@@ -6637,9 +6682,7 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6637
6682
  ...restProps
6638
6683
  } = props, portableTextEditor = usePortableTextEditor(), ref = useRef(null), [editableElement, setEditableElement] = useState(null), [hasInvalidValue, setHasInvalidValue] = useState(!1), [rangeDecorationState, setRangeDecorationsState] = useState([]);
6639
6684
  useImperativeHandle(forwardedRef, () => ref.current);
6640
- const rangeDecorationsRef = useRef(rangeDecorations), editorActor = useContext(EditorActorContext), readOnly = useSelector(editorActor, (s) => s.context.readOnly), {
6641
- schemaTypes
6642
- } = portableTextEditor, slateEditor = useSlate(), blockTypeName = schemaTypes.block.name;
6685
+ const rangeDecorationsRef = useRef(rangeDecorations), editorActor = useContext(EditorActorContext), readOnly = useSelector(editorActor, (s) => s.context.readOnly), schemaTypes = useSelector(editorActor, (s_0) => s_0.context.schema), slateEditor = useSlate(), blockTypeName = schemaTypes.block.name;
6643
6686
  useMemo(() => {
6644
6687
  const withInsertData = createWithInsertData(editorActor, schemaTypes);
6645
6688
  if (readOnly)
@@ -6875,46 +6918,56 @@ const debug = debugWithName("component:Editable"), PLACEHOLDER_STYLE = {
6875
6918
  ) : null;
6876
6919
  });
6877
6920
  PortableTextEditable.displayName = "ForwardRef(PortableTextEditable)";
6878
- function useEditor(config) {
6879
- const $ = c(21), t0 = config.keyGenerator ?? defaultKeyGenerator;
6880
- let t1;
6881
- $[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];
6921
+ const EditorContext = React.createContext(void 0);
6922
+ function EditorProvider(props) {
6923
+ const $ = c(30), editor = useEditor(props.config), editorActor = editor._internal.editorActor, slateEditor = editor._internal.slateEditor, editable = editor.editable;
6924
+ let t0, t1;
6925
+ $[0] !== editor ? (t1 = new PortableTextEditor({
6926
+ editor
6927
+ }), $[0] = editor, $[1] = t1) : t1 = $[1], t0 = t1;
6928
+ const portableTextEditor = t0;
6882
6929
  let t2;
6883
- $[3] !== config.behaviors || $[4] !== config.initialValue || $[5] !== t0 || $[6] !== t1 ? (t2 = {
6884
- input: {
6885
- behaviors: config.behaviors,
6886
- keyGenerator: t0,
6887
- schema: t1,
6888
- value: config.initialValue
6889
- }
6890
- }, $[3] = config.behaviors, $[4] = config.initialValue, $[5] = t0, $[6] = t1, $[7] = t2) : t2 = $[7];
6891
- const editorActor = useActorRef(editorMachine, t2);
6930
+ $[2] !== portableTextEditor.change$ ? (t2 = (change) => {
6931
+ portableTextEditor.change$.next(change);
6932
+ }, $[2] = portableTextEditor.change$, $[3] = t2) : t2 = $[3];
6892
6933
  let t3;
6893
- $[8] !== editorActor ? (t3 = createSlateEditor({
6894
- editorActor
6895
- }), $[8] = editorActor, $[9] = t3) : t3 = $[9];
6896
- const slateEditor = t3, readOnly = useSelector(editorActor, _temp);
6897
- let t4, t5;
6898
- $[10] !== editorActor ? (t4 = (event) => {
6899
- editorActor.send(event);
6900
- }, t5 = (event_0, listener) => editorActor.on(event_0, listener), $[10] = editorActor, $[11] = t4, $[12] = t5) : (t4 = $[11], t5 = $[12]);
6934
+ $[4] !== editorActor || $[5] !== t2 ? (t3 = /* @__PURE__ */ jsx(RouteEventsToChanges, { editorActor, onChange: t2 }), $[4] = editorActor, $[5] = t2, $[6] = t3) : t3 = $[6];
6935
+ let t4;
6936
+ $[7] !== editable.getValue || $[8] !== editorActor || $[9] !== portableTextEditor || $[10] !== slateEditor.instance ? (t4 = /* @__PURE__ */ jsx(Synchronizer, { editorActor, getValue: editable.getValue, portableTextEditor, slateEditor: slateEditor.instance }), $[7] = editable.getValue, $[8] = editorActor, $[9] = portableTextEditor, $[10] = slateEditor.instance, $[11] = t4) : t4 = $[11];
6937
+ let t5;
6938
+ $[12] !== editorActor || $[13] !== props.children ? (t5 = /* @__PURE__ */ jsx(PortableTextEditorSelectionProvider, { editorActor, children: props.children }), $[12] = editorActor, $[13] = props.children, $[14] = t5) : t5 = $[14];
6901
6939
  let t6;
6902
- $[13] !== editorActor || $[14] !== slateEditor ? (t6 = {
6903
- editorActor,
6904
- slateEditor
6905
- }, $[13] = editorActor, $[14] = slateEditor, $[15] = t6) : t6 = $[15];
6940
+ $[15] !== portableTextEditor || $[16] !== t5 ? (t6 = /* @__PURE__ */ jsx(PortableTextEditorContext.Provider, { value: portableTextEditor, children: t5 }), $[15] = portableTextEditor, $[16] = t5, $[17] = t6) : t6 = $[17];
6906
6941
  let t7;
6907
- return $[16] !== readOnly || $[17] !== t4 || $[18] !== t5 || $[19] !== t6 ? (t7 = {
6908
- send: t4,
6909
- on: t5,
6910
- readOnly,
6911
- _internal: t6
6912
- }, $[16] = readOnly, $[17] = t4, $[18] = t5, $[19] = t6, $[20] = t7) : t7 = $[20], t7;
6942
+ $[18] !== slateEditor.initialValue || $[19] !== slateEditor.instance || $[20] !== t6 ? (t7 = /* @__PURE__ */ jsx(Slate, { editor: slateEditor.instance, initialValue: slateEditor.initialValue, children: t6 }), $[18] = slateEditor.initialValue, $[19] = slateEditor.instance, $[20] = t6, $[21] = t7) : t7 = $[21];
6943
+ let t8;
6944
+ $[22] !== editorActor || $[23] !== t7 ? (t8 = /* @__PURE__ */ jsx(EditorActorContext.Provider, { value: editorActor, children: t7 }), $[22] = editorActor, $[23] = t7, $[24] = t8) : t8 = $[24];
6945
+ let t9;
6946
+ return $[25] !== editor || $[26] !== t3 || $[27] !== t4 || $[28] !== t8 ? (t9 = /* @__PURE__ */ jsxs(EditorContext.Provider, { value: editor, children: [
6947
+ t3,
6948
+ t4,
6949
+ t8
6950
+ ] }), $[25] = editor, $[26] = t3, $[27] = t4, $[28] = t8, $[29] = t9) : t9 = $[29], t9;
6951
+ }
6952
+ function useEditorContext() {
6953
+ const editor = React.useContext(EditorContext);
6954
+ if (!editor)
6955
+ throw new Error("No Editor set. Use EditorProvider to set one.");
6956
+ return editor;
6913
6957
  }
6914
- function _temp(s) {
6915
- return s.context.readOnly;
6958
+ function EditorEventListener(props) {
6959
+ const $ = c(4), editor = useEditorContext(), on = useEffectEvent(props.on);
6960
+ let t0, t1;
6961
+ return $[0] !== editor || $[1] !== on ? (t0 = () => {
6962
+ const subscription = editor.on("*", on);
6963
+ return () => {
6964
+ subscription.unsubscribe();
6965
+ };
6966
+ }, t1 = [editor, on], $[0] = editor, $[1] = on, $[2] = t0, $[3] = t1) : (t0 = $[2], t1 = $[3]), useEffect(t0, t1), null;
6916
6967
  }
6917
6968
  export {
6969
+ EditorEventListener,
6970
+ EditorProvider,
6918
6971
  PortableTextEditable,
6919
6972
  PortableTextEditor,
6920
6973
  coreBehavior,
@@ -6926,6 +6979,7 @@ export {
6926
6979
  editorMachine,
6927
6980
  defaultKeyGenerator as keyGenerator,
6928
6981
  useEditor,
6982
+ useEditorContext,
6929
6983
  usePortableTextEditor,
6930
6984
  usePortableTextEditorSelection
6931
6985
  };