@portabletext/editor 1.0.11 → 1.0.13

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.mjs CHANGED
@@ -5,7 +5,7 @@ import { useRef, useState, useMemo, useEffect, useCallback, createContext, useCo
5
5
  import { Editor, Element as Element$1, Range, Point, Text, Path, Transforms, Node, Operation, createEditor } from "slate";
6
6
  import { useSlateStatic, ReactEditor, useSelected, withReact, Slate, useSlate, Editable } from "slate-react";
7
7
  import debug$m from "debug";
8
- import { isKeySegment, isPortableTextSpan, isPortableTextTextBlock, isPortableTextListBlock } from "@sanity/types";
8
+ import { isKeySegment, isPortableTextSpan as isPortableTextSpan$1, isPortableTextTextBlock, isPortableTextListBlock } from "@sanity/types";
9
9
  import { styled } from "styled-components";
10
10
  import uniq from "lodash/uniq.js";
11
11
  import { Subject } from "rxjs";
@@ -185,8 +185,7 @@ function fromSlateValue(value, textBlockType, keyMap = {}) {
185
185
  });
186
186
  }
187
187
  function isEqualToEmptyEditor(children, schemaTypes) {
188
- var _a;
189
- return children === void 0 || children && Array.isArray(children) && children.length === 0 || children && Array.isArray(children) && children.length === 1 && Element$1.isElement(children[0]) && children[0]._type === schemaTypes.block.name && "style" in children[0] && children[0].style === schemaTypes.styles[0].value && !("listItem" in children[0]) && Array.isArray(children[0].children) && children[0].children.length === 1 && Text.isText(children[0].children[0]) && children[0].children[0]._type === "span" && !((_a = children[0].children[0].marks) != null && _a.join("")) && children[0].children[0].text === "";
188
+ return children === void 0 || children && Array.isArray(children) && children.length === 0 || children && Array.isArray(children) && children.length === 1 && Element$1.isElement(children[0]) && children[0]._type === schemaTypes.block.name && "style" in children[0] && children[0].style === schemaTypes.styles[0].value && !("listItem" in children[0]) && Array.isArray(children[0].children) && children[0].children.length === 1 && Text.isText(children[0].children[0]) && children[0].children[0]._type === "span" && !children[0].children[0].marks?.join("") && children[0].children[0].text === "";
190
189
  }
191
190
  const IS_PROCESSING_REMOTE_CHANGES = /* @__PURE__ */ new WeakMap(), IS_PROCESSING_LOCAL_CHANGES = /* @__PURE__ */ new WeakMap(), IS_DRAGGING = /* @__PURE__ */ new WeakMap(), IS_DRAGGING_BLOCK_ELEMENT = /* @__PURE__ */ new WeakMap(), IS_DRAGGING_ELEMENT_TARGET = /* @__PURE__ */ new WeakMap(), IS_DRAGGING_BLOCK_TARGET_POSITION = /* @__PURE__ */ new WeakMap(), KEY_TO_SLATE_ELEMENT = /* @__PURE__ */ new WeakMap(), KEY_TO_VALUE_ELEMENT = /* @__PURE__ */ new WeakMap(), SLATE_TO_PORTABLE_TEXT_RANGE = /* @__PURE__ */ new WeakMap(), DefaultObject = (props) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx("pre", { children: JSON.stringify(props.value, null, 2) }) }), DefaultBlockObject = styled.div`
192
191
  user-select: none;
@@ -655,13 +654,12 @@ function DefaultAnnotation(props) {
655
654
  return /* @__PURE__ */ jsx("span", { style: { color: "blue" }, onClick: handleClick, children: props.children });
656
655
  }
657
656
  function getPortableTextMemberSchemaTypes(portableTextType) {
658
- var _a, _b, _c;
659
657
  if (!portableTextType)
660
658
  throw new Error("Parameter 'portabletextType' missing (required)");
661
- const blockType = (_a = portableTextType.of) == null ? void 0 : _a.find(findBlockType);
659
+ const blockType = portableTextType.of?.find(findBlockType);
662
660
  if (!blockType)
663
661
  throw new Error("Block type is not defined in this schema (required)");
664
- const childrenField = (_b = blockType.fields) == null ? void 0 : _b.find((field) => field.name === "children");
662
+ const childrenField = blockType.fields?.find((field) => field.name === "children");
665
663
  if (!childrenField)
666
664
  throw new Error("Children field for block type found in schema (required)");
667
665
  const ofType = childrenField.type.of;
@@ -670,7 +668,7 @@ function getPortableTextMemberSchemaTypes(portableTextType) {
670
668
  const spanType = ofType.find((memberType) => memberType.name === "span");
671
669
  if (!spanType)
672
670
  throw new Error("Span type not found in schema (required)");
673
- const inlineObjectTypes = ofType.filter((memberType) => memberType.name !== "span") || [], blockObjectTypes = ((_c = portableTextType.of) == null ? void 0 : _c.filter((field) => field.name !== blockType.name)) || [];
671
+ const inlineObjectTypes = ofType.filter((memberType) => memberType.name !== "span") || [], blockObjectTypes = portableTextType.of?.filter((field) => field.name !== blockType.name) || [];
674
672
  return {
675
673
  styles: resolveEnabledStyles(blockType),
676
674
  decorators: resolveEnabledDecorators(spanType),
@@ -684,11 +682,10 @@ function getPortableTextMemberSchemaTypes(portableTextType) {
684
682
  };
685
683
  }
686
684
  function resolveEnabledStyles(blockType) {
687
- var _a, _b, _c;
688
- const styleField = (_a = blockType.fields) == null ? void 0 : _a.find((btField) => btField.name === "style");
685
+ const styleField = blockType.fields?.find((btField) => btField.name === "style");
689
686
  if (!styleField)
690
687
  throw new Error("A field with name 'style' is not defined in the block type (required).");
691
- const textStyles = ((_b = styleField.type.options) == null ? void 0 : _b.list) && ((_c = styleField.type.options.list) == null ? void 0 : _c.filter((style) => style.value));
688
+ const textStyles = styleField.type.options?.list && styleField.type.options.list?.filter((style) => style.value);
692
689
  if (!textStyles || textStyles.length === 0)
693
690
  throw new Error(
694
691
  "The style fields need at least one style defined. I.e: {title: 'Normal', value: 'normal'}."
@@ -699,11 +696,10 @@ function resolveEnabledDecorators(spanType) {
699
696
  return spanType.decorators;
700
697
  }
701
698
  function resolveEnabledListItems(blockType) {
702
- var _a, _b;
703
- const listField = (_a = blockType.fields) == null ? void 0 : _a.find((btField) => btField.name === "listItem");
699
+ const listField = blockType.fields?.find((btField) => btField.name === "listItem");
704
700
  if (!listField)
705
701
  throw new Error("A field with name 'listItem' is not defined in the block type (required).");
706
- const listItems = ((_b = listField.type.options) == null ? void 0 : _b.list) && listField.type.options.list.filter((list) => list.value);
702
+ const listItems = listField.type.options?.list && listField.type.options.list.filter((list) => list.value);
707
703
  if (!listItems)
708
704
  throw new Error("The list field need at least to be an empty array");
709
705
  return listItems;
@@ -718,7 +714,6 @@ function compileType(rawType) {
718
714
  }).get(rawType.name);
719
715
  }
720
716
  const debug$k = debugWithName("operationToPatches");
721
- debug$k.enabled = !1;
722
717
  function createOperationToPatches(types) {
723
718
  const textBlockName = types.block.name;
724
719
  function insertTextPatch(editor, operation, beforeValue) {
@@ -781,7 +776,7 @@ function createOperationToPatches(types) {
781
776
  function insertNodePatch(editor, operation, beforeValue) {
782
777
  const block = beforeValue[operation.path[0]], isTextBlock = editor.isTextBlock(block);
783
778
  if (operation.path.length === 1) {
784
- const position = operation.path[0] === 0 ? "before" : "after", beforeBlock = beforeValue[operation.path[0] - 1], targetKey = operation.path[0] === 0 ? block == null ? void 0 : block._key : beforeBlock == null ? void 0 : beforeBlock._key;
779
+ const position = operation.path[0] === 0 ? "before" : "after", beforeBlock = beforeValue[operation.path[0] - 1], targetKey = operation.path[0] === 0 ? block?._key : beforeBlock?._key;
785
780
  return targetKey ? [
786
781
  insert([fromSlateValue([operation.node], textBlockName)[0]], position, [
787
782
  { _key: targetKey }
@@ -883,7 +878,7 @@ function createOperationToPatches(types) {
883
878
  function mergeNodePatch(editor, operation, beforeValue) {
884
879
  const patches = [], block = beforeValue[operation.path[0]], targetBlock = editor.children[operation.path[0]];
885
880
  if (operation.path.length === 1)
886
- if (block != null && block._key) {
881
+ if (block?._key) {
887
882
  const newBlock = fromSlateValue([editor.children[operation.path[0] - 1]], textBlockName)[0];
888
883
  patches.push(set(newBlock, [{ _key: newBlock._key }])), patches.push(unset([{ _key: block._key }]));
889
884
  } else
@@ -981,7 +976,6 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
981
976
  }
982
977
  },
983
978
  insertChild: (type, value) => {
984
- var _a;
985
979
  if (!editor.selection)
986
980
  throw new Error("The editor has no selection");
987
981
  const [focusBlock] = Array.from(
@@ -1013,14 +1007,13 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1013
1007
  return isSpanNode && focusNode._type !== types.span.name && (debug$j("Inserting span child next to inline object child, moving selection + 1"), editor.move({ distance: 1, unit: "character" })), Transforms.insertNodes(editor, child, {
1014
1008
  select: !0,
1015
1009
  at: editor.selection
1016
- }), editor.onChange(), ((_a = toPortableTextRange(
1010
+ }), editor.onChange(), toPortableTextRange(
1017
1011
  fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1018
1012
  editor.selection,
1019
1013
  types
1020
- )) == null ? void 0 : _a.focus.path) || [];
1014
+ )?.focus.path || [];
1021
1015
  },
1022
1016
  insertBlock: (type, value) => {
1023
- var _a, _b, _c;
1024
1017
  const block = toSlateValue(
1025
1018
  [
1026
1019
  {
@@ -1039,11 +1032,11 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1039
1032
  reverse: !0
1040
1033
  })
1041
1034
  )[0];
1042
- return Editor.insertNode(editor, block), lastBlock && isEqualToEmptyEditor([lastBlock[0]], types) && Transforms.removeNodes(editor, { at: lastBlock[1] }), editor.onChange(), (_b = (_a = toPortableTextRange(
1035
+ return Editor.insertNode(editor, block), lastBlock && isEqualToEmptyEditor([lastBlock[0]], types) && Transforms.removeNodes(editor, { at: lastBlock[1] }), editor.onChange(), toPortableTextRange(
1043
1036
  fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1044
1037
  editor.selection,
1045
1038
  types
1046
- )) == null ? void 0 : _a.focus.path) != null ? _b : [];
1039
+ )?.focus.path ?? [];
1047
1040
  }
1048
1041
  const focusBlock = Array.from(
1049
1042
  Editor.nodes(editor, {
@@ -1051,11 +1044,11 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1051
1044
  match: (n) => n._type === types.block.name
1052
1045
  })
1053
1046
  )[0];
1054
- return Editor.insertNode(editor, block), focusBlock && isEqualToEmptyEditor([focusBlock[0]], types) && Transforms.removeNodes(editor, { at: focusBlock[1] }), editor.onChange(), ((_c = toPortableTextRange(
1047
+ return Editor.insertNode(editor, block), focusBlock && isEqualToEmptyEditor([focusBlock[0]], types) && Transforms.removeNodes(editor, { at: focusBlock[1] }), editor.onChange(), toPortableTextRange(
1055
1048
  fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
1056
1049
  editor.selection,
1057
1050
  types
1058
- )) == null ? void 0 : _c.focus.path) || [];
1051
+ )?.focus.path || [];
1059
1052
  },
1060
1053
  hasBlockStyle: (style) => {
1061
1054
  try {
@@ -1111,7 +1104,6 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1111
1104
  return node;
1112
1105
  },
1113
1106
  activeAnnotations: () => {
1114
- var _a;
1115
1107
  if (!editor.selection || editor.selection.focus.path.length < 2)
1116
1108
  return [];
1117
1109
  try {
@@ -1121,9 +1113,9 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1121
1113
  });
1122
1114
  for (const [span, path] of spans) {
1123
1115
  const [block] = Editor.node(editor, path, { depth: 1 });
1124
- editor.isTextBlock(block) && ((_a = block.markDefs) == null || _a.forEach((def) => {
1116
+ editor.isTextBlock(block) && block.markDefs?.forEach((def) => {
1125
1117
  Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
1126
- }));
1118
+ });
1127
1119
  }
1128
1120
  return activeAnnotations;
1129
1121
  } catch {
@@ -1141,27 +1133,16 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1141
1133
  })
1142
1134
  ];
1143
1135
  if (spans.length === 0 || spans.some(
1144
- ([span]) => {
1145
- var _a;
1146
- return !isPortableTextSpan(span) || !span.marks || ((_a = span.marks) == null ? void 0 : _a.length) === 0;
1147
- }
1136
+ ([span]) => !isPortableTextSpan$1(span) || !span.marks || span.marks?.length === 0
1148
1137
  ))
1149
1138
  return !1;
1150
1139
  const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
1151
1140
  const [block] = Editor.node(editor, path, { depth: 1 });
1152
1141
  return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
1153
1142
  }, []);
1154
- return spans.every(([span]) => {
1155
- var _a;
1156
- if (!isPortableTextSpan(span)) return !1;
1157
- const spanMarkDefs = (_a = span.marks) == null ? void 0 : _a.map(
1158
- (markKey) => {
1159
- var _a2;
1160
- return (_a2 = selectionMarkDefs.find((def) => (def == null ? void 0 : def._key) === markKey)) == null ? void 0 : _a2._type;
1161
- }
1162
- );
1163
- return spanMarkDefs == null ? void 0 : spanMarkDefs.includes(annotationType);
1164
- });
1143
+ return spans.every(([span]) => isPortableTextSpan$1(span) ? span.marks?.map(
1144
+ (markKey) => selectionMarkDefs.find((def) => def?._key === markKey)?._type
1145
+ )?.includes(annotationType) : !1);
1165
1146
  } catch {
1166
1147
  return !1;
1167
1148
  }
@@ -1221,7 +1202,7 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1221
1202
  if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
1222
1203
  throw new Error("Invalid range");
1223
1204
  if (range) {
1224
- if (!(options != null && options.mode) || (options == null ? void 0 : options.mode) === "selected") {
1205
+ if (!options?.mode || options?.mode === "selected") {
1225
1206
  debug$j("Deleting content in selection"), Transforms.delete(editor, {
1226
1207
  at: range,
1227
1208
  hanging: !0,
@@ -1229,11 +1210,11 @@ function createWithEditableAPI(portableTextEditor, types, keyGenerator) {
1229
1210
  }), editor.onChange();
1230
1211
  return;
1231
1212
  }
1232
- (options == null ? void 0 : options.mode) === "blocks" && (debug$j("Deleting blocks touched by selection"), Transforms.removeNodes(editor, {
1213
+ options?.mode === "blocks" && (debug$j("Deleting blocks touched by selection"), Transforms.removeNodes(editor, {
1233
1214
  at: range,
1234
1215
  voids: !0,
1235
1216
  match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && Element$1.isElement(node)
1236
- })), (options == null ? void 0 : options.mode) === "children" && (debug$j("Deleting children touched by selection"), Transforms.removeNodes(editor, {
1217
+ })), options?.mode === "children" && (debug$j("Deleting children touched by selection"), Transforms.removeNodes(editor, {
1237
1218
  at: range,
1238
1219
  voids: !0,
1239
1220
  match: (node) => node._type === types.span.name || // Text children
@@ -1332,6 +1313,10 @@ function withPreserveKeys(editor, fn) {
1332
1313
  const prev = isPreservingKeys(editor);
1333
1314
  PRESERVE_KEYS.set(editor, !0), fn(), PRESERVE_KEYS.set(editor, prev);
1334
1315
  }
1316
+ function withoutPreserveKeys(editor, fn) {
1317
+ const prev = isPreservingKeys(editor);
1318
+ PRESERVE_KEYS.set(editor, !1), fn(), PRESERVE_KEYS.set(editor, prev);
1319
+ }
1335
1320
  function isPreservingKeys(editor) {
1336
1321
  return PRESERVE_KEYS.get(editor);
1337
1322
  }
@@ -1342,17 +1327,27 @@ function createWithObjectKeys(schemaTypes, keyGenerator) {
1342
1327
  return editor.apply = (operation) => {
1343
1328
  if (operation.type === "split_node") {
1344
1329
  const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.properties);
1345
- operation.properties = {
1346
- ...operation.properties,
1347
- ...withNewKey ? { _key: keyGenerator() } : {}
1348
- };
1330
+ apply2({
1331
+ ...operation,
1332
+ properties: {
1333
+ ...operation.properties,
1334
+ ...withNewKey ? { _key: keyGenerator() } : {}
1335
+ }
1336
+ });
1337
+ return;
1349
1338
  }
1350
1339
  if (operation.type === "insert_node") {
1351
1340
  const withNewKey = !isPreservingKeys(editor) || !("_key" in operation.node);
1352
- Editor.isEditor(operation.node) || (operation.node = {
1353
- ...operation.node,
1354
- ...withNewKey ? { _key: keyGenerator() } : {}
1355
- });
1341
+ if (!Editor.isEditor(operation.node)) {
1342
+ apply2({
1343
+ ...operation,
1344
+ node: {
1345
+ ...operation.node,
1346
+ ...withNewKey ? { _key: keyGenerator() } : {}
1347
+ }
1348
+ });
1349
+ return;
1350
+ }
1356
1351
  }
1357
1352
  apply2(operation);
1358
1353
  }, editor.normalizeNode = (entry) => {
@@ -2240,7 +2235,7 @@ function findBlockAndChildFromPath(editor, path) {
2240
2235
  const isMatch = isKeyedSegment(path[2]) ? node._key === path[2]._key : index === path[2];
2241
2236
  return isMatch && (childIndex = index), isMatch;
2242
2237
  });
2243
- return child ? { block, child, blockPath, childPath: blockPath == null ? void 0 : blockPath.concat(childIndex) } : { block, blockPath, child: void 0, childPath: void 0 };
2238
+ return child ? { block, child, blockPath, childPath: blockPath?.concat(childIndex) } : { block, blockPath, child: void 0, childPath: void 0 };
2244
2239
  }
2245
2240
  function withRemoteChanges(editor, fn) {
2246
2241
  const prev = isChangingRemotely(editor) || !1;
@@ -2329,11 +2324,12 @@ function createWithUndoRedo(options) {
2329
2324
  )
2330
2325
  );
2331
2326
  });
2327
+ const reversedOperations = transformedOperations.map(Operation.inverse).reverse();
2332
2328
  try {
2333
2329
  Editor.withoutNormalizing(editor, () => {
2334
2330
  withPreserveKeys(editor, () => {
2335
2331
  withoutSaving(editor, () => {
2336
- transformedOperations.map(Operation.inverse).reverse().forEach((op) => {
2332
+ reversedOperations.forEach((op) => {
2337
2333
  editor.apply(op);
2338
2334
  });
2339
2335
  });
@@ -2406,14 +2402,13 @@ function transformOperation(editor, patch, operation, snapshot, previousSnapshot
2406
2402
  if (patch.type === "diffMatchPatch") {
2407
2403
  const operationTargetBlock = findOperationTargetBlock(editor, transformedOperation);
2408
2404
  return !operationTargetBlock || !isEqual({ _key: operationTargetBlock._key }, patch.path[0]) ? [transformedOperation] : (parse(patch.value).forEach((diffPatch) => {
2409
- var _a, _b, _c, _d;
2410
2405
  let adjustOffsetBy = 0, changedOffset = diffPatch.utf8Start1;
2411
2406
  const { diffs } = diffPatch;
2412
2407
  if (diffs.forEach((diff2, index) => {
2413
2408
  const [diffType, text] = diff2;
2414
2409
  diffType === DIFF_INSERT ? (adjustOffsetBy += text.length, changedOffset += text.length) : diffType === DIFF_DELETE ? (adjustOffsetBy -= text.length, changedOffset -= text.length) : diffType === DIFF_EQUAL && (diffs.slice(index).every(([dType]) => dType === DIFF_EQUAL) || (changedOffset += text.length));
2415
2410
  }), transformedOperation.type === "insert_text" && changedOffset < transformedOperation.offset && (transformedOperation.offset += adjustOffsetBy), transformedOperation.type === "remove_text" && changedOffset <= transformedOperation.offset - transformedOperation.text.length && (transformedOperation.offset += adjustOffsetBy), transformedOperation.type === "set_selection") {
2416
- const currentFocus = (_a = transformedOperation.properties) != null && _a.focus ? { ...transformedOperation.properties.focus } : void 0, currentAnchor = (_b = transformedOperation == null ? void 0 : transformedOperation.properties) != null && _b.anchor ? { ...transformedOperation.properties.anchor } : void 0, newFocus = (_c = transformedOperation == null ? void 0 : transformedOperation.newProperties) != null && _c.focus ? { ...transformedOperation.newProperties.focus } : void 0, newAnchor = (_d = transformedOperation == null ? void 0 : transformedOperation.newProperties) != null && _d.anchor ? { ...transformedOperation.newProperties.anchor } : void 0;
2411
+ const currentFocus = transformedOperation.properties?.focus ? { ...transformedOperation.properties.focus } : void 0, currentAnchor = transformedOperation?.properties?.anchor ? { ...transformedOperation.properties.anchor } : void 0, newFocus = transformedOperation?.newProperties?.focus ? { ...transformedOperation.newProperties.focus } : void 0, newAnchor = transformedOperation?.newProperties?.anchor ? { ...transformedOperation.newProperties.anchor } : void 0;
2417
2412
  (currentFocus && currentAnchor || newFocus && newAnchor) && ([currentFocus, currentAnchor, newFocus, newAnchor].forEach((point) => {
2418
2413
  point && changedOffset < point.offset && (point.offset += adjustOffsetBy);
2419
2414
  }), currentFocus && currentAnchor && (transformedOperation.properties = {
@@ -2429,14 +2424,13 @@ function transformOperation(editor, patch, operation, snapshot, previousSnapshot
2429
2424
  return [transformedOperation];
2430
2425
  }
2431
2426
  function adjustBlockPath(operation, level, blockIndex) {
2432
- var _a, _b, _c, _d;
2433
2427
  const transformedOperation = { ...operation };
2434
2428
  if (blockIndex >= 0 && transformedOperation.type !== "set_selection" && Array.isArray(transformedOperation.path) && transformedOperation.path[0] >= blockIndex + level && transformedOperation.path[0] + level > -1) {
2435
2429
  const newPath = [transformedOperation.path[0] + level, ...transformedOperation.path.slice(1)];
2436
2430
  transformedOperation.path = newPath;
2437
2431
  }
2438
2432
  if (transformedOperation.type === "set_selection") {
2439
- const currentFocus = (_a = transformedOperation.properties) != null && _a.focus ? { ...transformedOperation.properties.focus } : void 0, currentAnchor = (_b = transformedOperation == null ? void 0 : transformedOperation.properties) != null && _b.anchor ? { ...transformedOperation.properties.anchor } : void 0, newFocus = (_c = transformedOperation == null ? void 0 : transformedOperation.newProperties) != null && _c.focus ? { ...transformedOperation.newProperties.focus } : void 0, newAnchor = (_d = transformedOperation == null ? void 0 : transformedOperation.newProperties) != null && _d.anchor ? { ...transformedOperation.newProperties.anchor } : void 0;
2433
+ const currentFocus = transformedOperation.properties?.focus ? { ...transformedOperation.properties.focus } : void 0, currentAnchor = transformedOperation?.properties?.anchor ? { ...transformedOperation.properties.anchor } : void 0, newFocus = transformedOperation?.newProperties?.focus ? { ...transformedOperation.newProperties.focus } : void 0, newAnchor = transformedOperation?.newProperties?.anchor ? { ...transformedOperation.newProperties.anchor } : void 0;
2440
2434
  (currentFocus && currentAnchor || newFocus && newAnchor) && ([currentFocus, currentAnchor, newFocus, newAnchor].forEach((point) => {
2441
2435
  point && point.path[0] >= blockIndex + level && point.path[0] + level > -1 && (point.path = [point.path[0] + level, ...point.path.slice(1)]);
2442
2436
  }), currentFocus && currentAnchor && (transformedOperation.properties = {
@@ -2734,8 +2728,23 @@ function createWithPortableTextLists(types) {
2734
2728
  }, editor;
2735
2729
  };
2736
2730
  }
2731
+ function isPortableTextSpan(node) {
2732
+ 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"));
2733
+ }
2734
+ function isPortableTextBlock(node) {
2735
+ return (
2736
+ // A block doesn't _have_ to be named 'block' - to differentiate between
2737
+ // allowed child types and marks, one might name them differently
2738
+ typeof node._type == "string" && // Toolkit-types like nested spans are @-prefixed
2739
+ node._type[0] !== "@" && // `markDefs` isn't _required_ per say, but if it's there, it needs to be an array
2740
+ (!("markDefs" in node) || !node.markDefs || Array.isArray(node.markDefs) && // Every mark definition needs to have an `_key` to be mappable in child spans
2741
+ node.markDefs.every((def) => typeof def._key == "string")) && // `children` is required and needs to be an array
2742
+ "children" in node && Array.isArray(node.children) && // All children are objects with `_type` (usually spans, but can contain other stuff)
2743
+ node.children.every((child) => typeof child == "object" && "_type" in child)
2744
+ );
2745
+ }
2737
2746
  const debug$c = debugWithName("plugin:withPortableTextMarkModel");
2738
- function createWithPortableTextMarkModel(types, change$) {
2747
+ function createWithPortableTextMarkModel(types, change$, keyGenerator) {
2739
2748
  return function(editor) {
2740
2749
  const { apply: apply2, normalizeNode } = editor, decorators = types.decorators.map((t) => t.value), forceNewSelection = () => {
2741
2750
  editor.selection && (Transforms.select(editor, { ...editor.selection }), editor.selection = { ...editor.selection });
@@ -2761,10 +2770,7 @@ function createWithPortableTextMarkModel(types, change$) {
2761
2770
  );
2762
2771
  if (annotationMarks.length > 0) {
2763
2772
  const [block] = Editor.node(editor, Path.parent(path)), orphanedMarks = editor.isTextBlock(block) && annotationMarks.filter(
2764
- (mark) => {
2765
- var _a;
2766
- return !((_a = block.markDefs) != null && _a.find((def) => def._key === mark));
2767
- }
2773
+ (mark) => !block.markDefs?.find((def) => def._key === mark)
2768
2774
  ) || [];
2769
2775
  orphanedMarks.length > 0 && (debug$c("Removing orphaned .marks from span node"), Transforms.setNodes(
2770
2776
  editor,
@@ -2816,10 +2822,9 @@ function createWithPortableTextMarkModel(types, change$) {
2816
2822
  ), editor.onChange());
2817
2823
  }
2818
2824
  }, editor.apply = (op) => {
2819
- var _a, _b;
2820
2825
  if (op.type === "insert_text") {
2821
2826
  const { selection } = editor;
2822
- if (selection && Range.isCollapsed(selection) && (_b = (_a = Editor.marks(editor)) == null ? void 0 : _a.marks) != null && _b.some((mark) => !decorators.includes(mark))) {
2827
+ if (selection && Range.isCollapsed(selection) && Editor.marks(editor)?.marks?.some((mark) => !decorators.includes(mark))) {
2823
2828
  const [node] = Array.from(
2824
2829
  Editor.nodes(editor, {
2825
2830
  mode: "lowest",
@@ -2829,18 +2834,41 @@ function createWithPortableTextMarkModel(types, change$) {
2829
2834
  })
2830
2835
  )[0] || [void 0];
2831
2836
  if (Text.isText(node) && node.text.length === selection.focus.offset && Array.isArray(node.marks) && node.marks.length > 0) {
2832
- apply2(op), Transforms.splitNodes(editor, {
2833
- match: Text.isText,
2834
- at: { ...selection.focus, offset: selection.focus.offset }
2835
- });
2836
2837
  const marksWithoutAnnotationMarks = ({
2837
2838
  ...Editor.marks(editor) || {}
2838
2839
  }.marks || []).filter((mark) => decorators.includes(mark));
2839
- Transforms.setNodes(
2840
- editor,
2841
- { marks: marksWithoutAnnotationMarks },
2842
- { at: Path.next(selection.focus.path) }
2843
- ), debug$c("Inserting text at end of annotation");
2840
+ Transforms.insertNodes(editor, {
2841
+ _type: "span",
2842
+ _key: keyGenerator(),
2843
+ text: op.text,
2844
+ marks: marksWithoutAnnotationMarks
2845
+ }), debug$c("Inserting text at end of annotation");
2846
+ return;
2847
+ }
2848
+ }
2849
+ }
2850
+ if (op.type === "remove_text") {
2851
+ const node = Array.from(
2852
+ Editor.nodes(editor, {
2853
+ mode: "lowest",
2854
+ at: { path: op.path, offset: op.offset },
2855
+ match: (n) => n._type === types.span.name,
2856
+ voids: !1
2857
+ })
2858
+ )[0][0], block = Editor.node(editor, Path.parent(op.path))[0];
2859
+ if (node && isPortableTextSpan(node) && block && isPortableTextBlock(block)) {
2860
+ const markDefs = block.markDefs ?? [], nodeHasAnnotations = (node.marks ?? []).some(
2861
+ (mark) => markDefs.find((markDef) => markDef._key === mark)
2862
+ ), deletingPartOfTheNode = op.offset !== 0, deletingFromTheEnd = op.offset + op.text.length === node.text.length;
2863
+ if (nodeHasAnnotations && deletingPartOfTheNode && deletingFromTheEnd) {
2864
+ Editor.withoutNormalizing(editor, () => {
2865
+ withoutPreserveKeys(editor, () => {
2866
+ Transforms.splitNodes(editor, {
2867
+ match: Text.isText,
2868
+ at: { path: op.path, offset: op.offset }
2869
+ });
2870
+ }), Transforms.removeNodes(editor, { at: Path.next(op.path) });
2871
+ }), editor.onChange();
2844
2872
  return;
2845
2873
  }
2846
2874
  }
@@ -2853,10 +2881,7 @@ function createWithPortableTextMarkModel(types, change$) {
2853
2881
  const splitTextNodes = [
2854
2882
  ...Editor.nodes(editor, { at: editor.selection, match: Text.isText })
2855
2883
  ];
2856
- if (splitTextNodes.every((node) => {
2857
- var _a;
2858
- return (_a = node[0].marks) == null ? void 0 : _a.includes(mark);
2859
- }))
2884
+ if (splitTextNodes.every((node) => node[0].marks?.includes(mark)))
2860
2885
  return editor.removeMark(mark), editor;
2861
2886
  Editor.withoutNormalizing(editor, () => {
2862
2887
  splitTextNodes.forEach(([node, path]) => {
@@ -2925,9 +2950,8 @@ function createWithPortableTextMarkModel(types, change$) {
2925
2950
  Editor.nodes(editor, { match: Text.isText, at: editor.selection })
2926
2951
  );
2927
2952
  return Range.isExpanded(editor.selection) ? selectedNodes.every((n) => {
2928
- var _a;
2929
2953
  const [node] = n;
2930
- return (_a = node.marks) == null ? void 0 : _a.includes(mark);
2954
+ return node.marks?.includes(mark);
2931
2955
  }) : ({
2932
2956
  ...Editor.marks(editor) || {}
2933
2957
  }.marks || []).includes(mark);
@@ -2937,18 +2961,22 @@ function createWithPortableTextMarkModel(types, change$) {
2937
2961
  };
2938
2962
  function mergeSpans(editor) {
2939
2963
  const { selection } = editor;
2940
- if (selection)
2941
- for (const [node, path] of Array.from(
2964
+ if (selection) {
2965
+ const textNodesInSelection = Array.from(
2942
2966
  Editor.nodes(editor, {
2943
- at: Editor.range(editor, [selection.anchor.path[0]], [selection.focus.path[0]])
2967
+ at: Editor.range(editor, [selection.anchor.path[0]], [selection.focus.path[0]]),
2968
+ match: Text.isText,
2969
+ reverse: !0
2944
2970
  })
2945
- ).reverse()) {
2971
+ );
2972
+ for (const [node, path] of textNodesInSelection) {
2946
2973
  const [parent] = path.length > 1 ? Editor.node(editor, Path.parent(path)) : [void 0], nextPath = [path[0], path[1] + 1];
2947
2974
  if (editor.isTextBlock(parent)) {
2948
2975
  const nextNode = parent.children[nextPath[1]];
2949
- Text.isText(node) && Text.isText(nextNode) && isEqual(nextNode.marks, node.marks) && (debug$c("Merging spans"), Transforms.mergeNodes(editor, { at: nextPath, voids: !0 }), editor.onChange());
2976
+ Text.isText(nextNode) && isEqual(nextNode.marks, node.marks) && (debug$c("Merging spans"), Transforms.mergeNodes(editor, { at: nextPath, voids: !0 }), editor.onChange());
2950
2977
  }
2951
2978
  }
2979
+ }
2952
2980
  }
2953
2981
  }
2954
2982
  const debug$b = debugWithName("plugin:withPortableTextSelections"), debugVerbose$2 = debug$b.enabled && !1;
@@ -2987,7 +3015,7 @@ function createWithSchemaTypes({
2987
3015
  keyGenerator
2988
3016
  }) {
2989
3017
  return function(editor) {
2990
- editor.isTextBlock = (value) => isPortableTextTextBlock(value) && value._type === schemaTypes.block.name, editor.isTextSpan = (value) => isPortableTextSpan(value) && value._type == schemaTypes.span.name, editor.isListBlock = (value) => isPortableTextListBlock(value) && value._type === schemaTypes.block.name, editor.isVoid = (element) => schemaTypes.block.name !== element._type && (schemaTypes.blockObjects.map((obj) => obj.name).includes(element._type) || schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type)), editor.isInline = (element) => schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type) && "__inline" in element && element.__inline === !0;
3018
+ editor.isTextBlock = (value) => isPortableTextTextBlock(value) && value._type === schemaTypes.block.name, editor.isTextSpan = (value) => isPortableTextSpan$1(value) && value._type == schemaTypes.span.name, editor.isListBlock = (value) => isPortableTextListBlock(value) && value._type === schemaTypes.block.name, editor.isVoid = (element) => schemaTypes.block.name !== element._type && (schemaTypes.blockObjects.map((obj) => obj.name).includes(element._type) || schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type)), editor.isInline = (element) => schemaTypes.inlineObjects.map((obj) => obj.name).includes(element._type) && "__inline" in element && element.__inline === !0;
2991
3019
  const { normalizeNode } = editor;
2992
3020
  return editor.normalizeNode = (entry) => {
2993
3021
  const [node, path] = entry;
@@ -3060,7 +3088,6 @@ function createWithHotkeys(types, portableTextEditor, hotkeysFromOptions) {
3060
3088
  const reservedHotkeys = ["enter", "tab", "shift", "delete", "end"], activeHotkeys = hotkeysFromOptions || DEFAULT_HOTKEYS;
3061
3089
  return function(editor) {
3062
3090
  return editor.pteWithHotKeys = (event) => {
3063
- var _a, _b, _c, _d, _e, _f;
3064
3091
  Object.keys(activeHotkeys).forEach((cat) => {
3065
3092
  if (cat === "marks")
3066
3093
  for (const hotkey in activeHotkeys[cat]) {
@@ -3107,7 +3134,7 @@ function createWithHotkeys(types, portableTextEditor, hotkeysFromOptions) {
3107
3134
  }
3108
3135
  }
3109
3136
  if (isBackspace && editor.selection && editor.selection.focus.path[0] === 0 && Range.isCollapsed(editor.selection)) {
3110
- const focusBlock = Node.descendant(editor, editor.selection.focus.path.slice(0, 1)), nextPath = Path.next(editor.selection.focus.path.slice(0, 1)), nextBlock = Node.has(editor, nextPath), isTextBlock = isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && ((_b = (_a = focusBlock.children) == null ? void 0 : _a[0]) == null ? void 0 : _b.text) === "";
3137
+ const focusBlock = Node.descendant(editor, editor.selection.focus.path.slice(0, 1)), nextPath = Path.next(editor.selection.focus.path.slice(0, 1)), nextBlock = Node.has(editor, nextPath), isTextBlock = isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && focusBlock.children?.[0]?.text === "";
3111
3138
  if (nextBlock && isTextBlock && isEmptyFocusBlock) {
3112
3139
  event.preventDefault(), event.stopPropagation(), Transforms.removeNodes(editor, { match: (n) => n === focusBlock }), editor.onChange();
3113
3140
  return;
@@ -3117,7 +3144,7 @@ function createWithHotkeys(types, portableTextEditor, hotkeysFromOptions) {
3117
3144
  const prevPath = Path.previous(editor.selection.focus.path.slice(0, 1)), prevBlock = Node.descendant(editor, prevPath), focusBlock = Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
3118
3145
  if (prevBlock && focusBlock && Editor.isVoid(editor, prevBlock) && editor.selection.focus.offset === 0) {
3119
3146
  debug$8("Preventing deleting void block above"), event.preventDefault(), event.stopPropagation();
3120
- const isTextBlock = isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && ((_d = (_c = focusBlock.children) == null ? void 0 : _c[0]) == null ? void 0 : _d.text) === "";
3147
+ const isTextBlock = isPortableTextTextBlock(focusBlock), isEmptyFocusBlock = isTextBlock && focusBlock.children.length === 1 && focusBlock.children?.[0]?.text === "";
3121
3148
  if (!isTextBlock || isEmptyFocusBlock) {
3122
3149
  Transforms.removeNodes(editor, { match: (n) => n === focusBlock }), Transforms.select(editor, prevPath), editor.onChange();
3123
3150
  return;
@@ -3133,17 +3160,17 @@ function createWithHotkeys(types, portableTextEditor, hotkeysFromOptions) {
3133
3160
  const nextBlock = Node.descendant(
3134
3161
  editor,
3135
3162
  Path.next(editor.selection.focus.path.slice(0, 1))
3136
- ), focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = Node.descendant(editor, focusBlockPath), isEmptyFocusBlock = isPortableTextTextBlock(focusBlock) && focusBlock.children.length === 1 && ((_f = (_e = focusBlock.children) == null ? void 0 : _e[0]) == null ? void 0 : _f.text) === "";
3163
+ ), focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = Node.descendant(editor, focusBlockPath), isEmptyFocusBlock = isPortableTextTextBlock(focusBlock) && focusBlock.children.length === 1 && focusBlock.children?.[0]?.text === "";
3137
3164
  if (nextBlock && focusBlock && !Editor.isVoid(editor, focusBlock) && Editor.isVoid(editor, nextBlock) && isEmptyFocusBlock) {
3138
3165
  debug$8("Preventing deleting void block below"), event.preventDefault(), event.stopPropagation(), Transforms.removeNodes(editor, { match: (n) => n === focusBlock }), Transforms.select(editor, focusBlockPath), editor.onChange();
3139
3166
  return;
3140
3167
  }
3141
3168
  }
3142
3169
  if ((isTab || isShiftTab) && editor.selection) {
3143
- const [focusChild] = Editor.node(editor, editor.selection.focus, { depth: 2 }), [focusBlock] = isPortableTextSpan(focusChild) ? Editor.node(editor, editor.selection.focus, { depth: 1 }) : [], hasAnnotationFocus = focusChild && isPortableTextTextBlock(focusBlock) && isPortableTextSpan(focusChild) && (focusChild.marks || []).filter(
3170
+ const [focusChild] = Editor.node(editor, editor.selection.focus, { depth: 2 }), [focusBlock] = isPortableTextSpan$1(focusChild) ? Editor.node(editor, editor.selection.focus, { depth: 1 }) : [], hasAnnotationFocus = focusChild && isPortableTextTextBlock(focusBlock) && isPortableTextSpan$1(focusChild) && (focusChild.marks || []).filter(
3144
3171
  (m) => (focusBlock.markDefs || []).map((def) => def._key).includes(m)
3145
3172
  ).length > 0, [start] = Range.edges(editor.selection), atStartOfNode = Editor.isStart(editor, start, start.path);
3146
- focusChild && isPortableTextSpan(focusChild) && (!hasAnnotationFocus || atStartOfNode) && editor.pteIncrementBlockLevels(isShiftTab) && event.preventDefault();
3173
+ focusChild && isPortableTextSpan$1(focusChild) && (!hasAnnotationFocus || atStartOfNode) && editor.pteIncrementBlockLevels(isShiftTab) && event.preventDefault();
3147
3174
  }
3148
3175
  if (isEnter && !isShiftEnter && editor.selection) {
3149
3176
  const focusBlockPath = editor.selection.focus.path.slice(0, 1), focusBlock = Node.descendant(editor, focusBlockPath);
@@ -3438,13 +3465,7 @@ function validateValue(value, types, keyGenerator) {
3438
3465
  const debug$7 = debugWithName("plugin:withInsertData");
3439
3466
  function createWithInsertData(change$, schemaTypes, keyGenerator) {
3440
3467
  return function(editor) {
3441
- const blockTypeName = schemaTypes.block.name, spanTypeName = schemaTypes.span.name, whitespaceOnPasteMode = schemaTypes.block.options.unstable_whitespaceOnPasteMode, toPlainText = (blocks) => blocks.map((block) => {
3442
- var _a;
3443
- return editor.isTextBlock(block) ? block.children.map((child) => {
3444
- var _a2;
3445
- return child._type === spanTypeName ? child.text : `[${((_a2 = schemaTypes.inlineObjects.find((t) => t.name === child._type)) == null ? void 0 : _a2.title) || "Object"}]`;
3446
- }).join("") : `[${((_a = schemaTypes.blockObjects.find((t) => t.name === block._type)) == null ? void 0 : _a.title) || "Object"}]`;
3447
- }).join(`
3468
+ const blockTypeName = schemaTypes.block.name, spanTypeName = schemaTypes.span.name, whitespaceOnPasteMode = schemaTypes.block.options.unstable_whitespaceOnPasteMode, toPlainText = (blocks) => blocks.map((block) => editor.isTextBlock(block) ? block.children.map((child) => child._type === spanTypeName ? child.text : `[${schemaTypes.inlineObjects.find((t) => t.name === child._type)?.title || "Object"}]`).join("") : `[${schemaTypes.blockObjects.find((t) => t.name === block._type)?.title || "Object"}]`).join(`
3448
3469
 
3449
3470
  `);
3450
3471
  return editor.setFragmentData = (data, originEvent) => {
@@ -3476,7 +3497,6 @@ function createWithInsertData(change$, schemaTypes, keyGenerator) {
3476
3497
  const fragment = editor.getFragment(), portableText = fromSlateValue(fragment, blockTypeName), asJSON = JSON.stringify(portableText), asPlainText = toPlainText(portableText);
3477
3498
  data.clearData(), data.setData("text/plain", asPlainText), data.setData("text/html", asHTML), data.setData("application/json", asJSON), data.setData("application/x-portable-text", asJSON), debug$7("text", asPlainText), data.setData("application/x-portable-text-event-origin", originEvent || "external"), debug$7("Set fragment data", asJSON, asHTML);
3478
3499
  }, editor.insertPortableTextData = (data) => {
3479
- var _a, _b;
3480
3500
  if (!editor.selection)
3481
3501
  return !1;
3482
3502
  const pText = data.getData("application/x-portable-text"), origin = data.getData("application/x-portable-text-event-origin");
@@ -3490,8 +3510,8 @@ function createWithInsertData(change$, schemaTypes, keyGenerator) {
3490
3510
  spanTypeName,
3491
3511
  schemaTypes
3492
3512
  ), validation = validateValue(parsed, schemaTypes, keyGenerator);
3493
- if (!validation.valid && !((_a = validation.resolution) != null && _a.autoResolve)) {
3494
- const errorDescription = `${(_b = validation.resolution) == null ? void 0 : _b.description}`;
3513
+ if (!validation.valid && !validation.resolution?.autoResolve) {
3514
+ const errorDescription = `${validation.resolution?.description}`;
3495
3515
  return change$.next({
3496
3516
  type: "error",
3497
3517
  level: "warning",
@@ -3505,7 +3525,6 @@ function createWithInsertData(change$, schemaTypes, keyGenerator) {
3505
3525
  }
3506
3526
  return !1;
3507
3527
  }, editor.insertTextOrHTMLData = (data) => {
3508
- var _a;
3509
3528
  if (!editor.selection)
3510
3529
  return debug$7("No selection, not inserting"), !1;
3511
3530
  change$.next({ type: "loading", isLoading: !0 });
@@ -3531,7 +3550,7 @@ function createWithInsertData(change$, schemaTypes, keyGenerator) {
3531
3550
  const validation = validateValue(portableText, schemaTypes, keyGenerator);
3532
3551
  if (!validation.valid) {
3533
3552
  const errorDescription = `Could not validate the resulting portable text to insert.
3534
- ${(_a = validation.resolution) == null ? void 0 : _a.description}
3553
+ ${validation.resolution?.description}
3535
3554
  Try to insert as plain text (shift-paste) instead.`;
3536
3555
  return change$.next({
3537
3556
  type: "error",
@@ -3638,7 +3657,11 @@ const originalFnMap = /* @__PURE__ */ new WeakMap(), withPlugins = (editor, opti
3638
3657
  readOnly,
3639
3658
  patches$,
3640
3659
  blockSchemaType: schemaTypes.block
3641
- }), withPortableTextMarkModel = createWithPortableTextMarkModel(schemaTypes, change$), withPortableTextBlockStyle = createWithPortableTextBlockStyle(schemaTypes), withPlaceholderBlock = createWithPlaceholderBlock(), withInsertBreak = createWithInsertBreak(schemaTypes), withUtils = createWithUtils({ keyGenerator, schemaTypes, portableTextEditor }), withPortableTextSelections = createWithPortableTextSelections(change$, schemaTypes);
3660
+ }), withPortableTextMarkModel = createWithPortableTextMarkModel(
3661
+ schemaTypes,
3662
+ change$,
3663
+ keyGenerator
3664
+ ), withPortableTextBlockStyle = createWithPortableTextBlockStyle(schemaTypes), withPlaceholderBlock = createWithPlaceholderBlock(), withInsertBreak = createWithInsertBreak(schemaTypes), withUtils = createWithUtils({ keyGenerator, schemaTypes, portableTextEditor }), withPortableTextSelections = createWithPortableTextSelections(change$, schemaTypes);
3642
3665
  return e.destroy = () => {
3643
3666
  const originalFunctions = originalFnMap.get(e);
3644
3667
  if (!originalFunctions)
@@ -3796,15 +3819,14 @@ function useSyncValue(props) {
3796
3819
  isChanged = !0;
3797
3820
  }
3798
3821
  slateValueFromProps.forEach((currentBlock, currentBlockIndex) => {
3799
- var _a, _b, _c, _d, _e;
3800
3822
  const oldBlock = slateEditor.children[currentBlockIndex];
3801
3823
  if (oldBlock && !isEqual(currentBlock, oldBlock) && isValid) {
3802
3824
  const validationValue = [value[currentBlockIndex]], validation = validateValue(validationValue, schemaTypes, keyGenerator);
3803
- !validation.valid && (_a = validation.resolution) != null && _a.autoResolve && ((_b = validation.resolution) == null ? void 0 : _b.patches.length) > 0 && !readOnly && previousValue.current && previousValue.current !== value && (console.warn(
3804
- `${validation.resolution.action} for block with _key '${validationValue[0]._key}'. ${(_c = validation.resolution) == null ? void 0 : _c.description}`
3825
+ !validation.valid && validation.resolution?.autoResolve && validation.resolution?.patches.length > 0 && !readOnly && previousValue.current && previousValue.current !== value && (console.warn(
3826
+ `${validation.resolution.action} for block with _key '${validationValue[0]._key}'. ${validation.resolution?.description}`
3805
3827
  ), validation.resolution.patches.forEach((patch) => {
3806
3828
  change$.next({ type: "patch", patch });
3807
- })), validation.valid || (_d = validation.resolution) != null && _d.autoResolve ? (oldBlock._key === currentBlock._key ? (debug$5.enabled && debug$5("Updating block", oldBlock, currentBlock), _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex)) : (debug$5.enabled && debug$5("Replacing block", oldBlock, currentBlock), _replaceBlock(slateEditor, currentBlock, currentBlockIndex)), isChanged = !0) : (change$.next({
3829
+ })), validation.valid || validation.resolution?.autoResolve ? (oldBlock._key === currentBlock._key ? (debug$5.enabled && debug$5("Updating block", oldBlock, currentBlock), _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex)) : (debug$5.enabled && debug$5("Replacing block", oldBlock, currentBlock), _replaceBlock(slateEditor, currentBlock, currentBlockIndex)), isChanged = !0) : (change$.next({
3808
3830
  type: "invalidValue",
3809
3831
  resolution: validation.resolution,
3810
3832
  value
@@ -3815,7 +3837,7 @@ function useSyncValue(props) {
3815
3837
  debug$5.enabled && debug$5(
3816
3838
  "Validating and inserting new block in the end of the value",
3817
3839
  currentBlock
3818
- ), validation.valid || (_e = validation.resolution) != null && _e.autoResolve ? withPreserveKeys(slateEditor, () => {
3840
+ ), validation.valid || validation.resolution?.autoResolve ? withPreserveKeys(slateEditor, () => {
3819
3841
  Transforms.insertNodes(slateEditor, currentBlock, {
3820
3842
  at: [currentBlockIndex]
3821
3843
  });
@@ -3885,9 +3907,9 @@ function _updateBlock(slateEditor, currentBlock, oldBlock, currentBlockIndex) {
3885
3907
  }));
3886
3908
  }
3887
3909
  ), currentBlock.children.forEach((currentBlockChild, currentBlockChildIndex) => {
3888
- const oldBlockChild = oldBlock.children[currentBlockChildIndex], isChildChanged = !isEqual(currentBlockChild, oldBlockChild), isTextChanged = !isEqual(currentBlockChild.text, oldBlockChild == null ? void 0 : oldBlockChild.text), path = [currentBlockIndex, currentBlockChildIndex];
3910
+ const oldBlockChild = oldBlock.children[currentBlockChildIndex], isChildChanged = !isEqual(currentBlockChild, oldBlockChild), isTextChanged = !isEqual(currentBlockChild.text, oldBlockChild?.text), path = [currentBlockIndex, currentBlockChildIndex];
3889
3911
  if (isChildChanged)
3890
- if (currentBlockChild._key === (oldBlockChild == null ? void 0 : oldBlockChild._key)) {
3912
+ if (currentBlockChild._key === oldBlockChild?._key) {
3891
3913
  debug$5("Updating changed child", currentBlockChild, oldBlockChild), Transforms.setNodes(slateEditor, currentBlockChild, {
3892
3914
  at: path
3893
3915
  });
@@ -4003,16 +4025,22 @@ function PortableTextEditorSelectionProvider(props) {
4003
4025
  };
4004
4026
  }, [change$]), /* @__PURE__ */ jsx(PortableTextEditorSelectionContext.Provider, { value: selection, children: props.children });
4005
4027
  }
4006
- var __defProp = Object.defineProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
4007
4028
  const debug$2 = debugWithName("component:PortableTextEditor");
4008
4029
  class PortableTextEditor extends Component {
4030
+ /**
4031
+ * An observable of all the editor changes.
4032
+ */
4033
+ change$ = new Subject();
4034
+ /**
4035
+ * A lookup table for all the relevant schema types for this portable text type.
4036
+ */
4037
+ schemaTypes;
4038
+ /**
4039
+ * The editor API (currently implemented with Slate).
4040
+ */
4041
+ editable;
4009
4042
  constructor(props) {
4010
- if (super(props), __publicField(this, "change$", new Subject()), __publicField(this, "schemaTypes"), __publicField(this, "editable"), __publicField(this, "setEditable", (editable) => {
4011
- this.editable = { ...this.editable, ...editable };
4012
- }), __publicField(this, "getValue", () => {
4013
- if (this.editable)
4014
- return this.editable.getValue();
4015
- }), !props.schemaType)
4043
+ if (super(props), !props.schemaType)
4016
4044
  throw new Error('PortableTextEditor: missing "schemaType" property');
4017
4045
  props.incomingPatches$ && console.warn("The prop 'incomingPatches$' is deprecated and renamed to 'patches$'"), this.change$.next({ type: "loading", isLoading: !0 }), this.schemaTypes = getPortableTextMemberSchemaTypes(
4018
4046
  props.schemaType.hasOwnProperty("jsonType") ? props.schemaType : compileType(props.schemaType)
@@ -4023,6 +4051,13 @@ class PortableTextEditor extends Component {
4023
4051
  this.props.schemaType.hasOwnProperty("jsonType") ? this.props.schemaType : compileType(this.props.schemaType)
4024
4052
  )), this.props.editorRef !== prevProps.editorRef && this.props.editorRef && (this.props.editorRef.current = this);
4025
4053
  }
4054
+ setEditable = (editable) => {
4055
+ this.editable = { ...this.editable, ...editable };
4056
+ };
4057
+ getValue = () => {
4058
+ if (this.editable)
4059
+ return this.editable.getValue();
4060
+ };
4026
4061
  render() {
4027
4062
  const { onChange, value, children, patches$, incomingPatches$ } = this.props, { change$ } = this, _patches$ = incomingPatches$ || patches$, maxBlocks = typeof this.props.maxBlocks > "u" ? void 0 : parseInt(this.props.maxBlocks.toString(), 10) || void 0, readOnly = !!this.props.readOnly, keyGenerator = this.props.keyGenerator || defaultKeyGenerator;
4028
4063
  return /* @__PURE__ */ jsx(
@@ -4048,99 +4083,59 @@ class PortableTextEditor extends Component {
4048
4083
  }
4049
4084
  );
4050
4085
  }
4086
+ // Static API methods
4087
+ static activeAnnotations = (editor) => editor && editor.editable ? editor.editable.activeAnnotations() : [];
4088
+ static isAnnotationActive = (editor, annotationType) => editor && editor.editable ? editor.editable.isAnnotationActive(annotationType) : !1;
4089
+ static addAnnotation = (editor, type, value) => editor.editable?.addAnnotation(type, value);
4090
+ static blur = (editor) => {
4091
+ debug$2("Host blurred"), editor.editable?.blur();
4092
+ };
4093
+ static delete = (editor, selection, options) => editor.editable?.delete(selection, options);
4094
+ static findDOMNode = (editor, element) => editor.editable?.findDOMNode(element);
4095
+ static findByPath = (editor, path) => editor.editable?.findByPath(path) || [];
4096
+ static focus = (editor) => {
4097
+ debug$2("Host requesting focus"), editor.editable?.focus();
4098
+ };
4099
+ static focusBlock = (editor) => editor.editable?.focusBlock();
4100
+ static focusChild = (editor) => editor.editable?.focusChild();
4101
+ static getSelection = (editor) => editor.editable ? editor.editable.getSelection() : null;
4102
+ static getValue = (editor) => editor.editable?.getValue();
4103
+ static hasBlockStyle = (editor, blockStyle) => editor.editable?.hasBlockStyle(blockStyle);
4104
+ static hasListStyle = (editor, listStyle) => editor.editable?.hasListStyle(listStyle);
4105
+ static isCollapsedSelection = (editor) => editor.editable?.isCollapsedSelection();
4106
+ static isExpandedSelection = (editor) => editor.editable?.isExpandedSelection();
4107
+ static isMarkActive = (editor, mark) => editor.editable?.isMarkActive(mark);
4108
+ static insertChild = (editor, type, value) => (debug$2("Host inserting child"), editor.editable?.insertChild(type, value));
4109
+ static insertBlock = (editor, type, value) => editor.editable?.insertBlock(type, value);
4110
+ static insertBreak = (editor) => editor.editable?.insertBreak();
4111
+ static isVoid = (editor, element) => editor.editable?.isVoid(element);
4112
+ static isObjectPath = (editor, path) => {
4113
+ if (!path || !Array.isArray(path)) return !1;
4114
+ const isChildObjectEditPath = path.length > 3 && path[1] === "children";
4115
+ return path.length > 1 && path[1] !== "children" || isChildObjectEditPath;
4116
+ };
4117
+ static marks = (editor) => editor.editable?.marks();
4118
+ static select = (editor, selection) => {
4119
+ debug$2("Host setting selection", selection), editor.editable?.select(selection);
4120
+ };
4121
+ static removeAnnotation = (editor, type) => editor.editable?.removeAnnotation(type);
4122
+ static toggleBlockStyle = (editor, blockStyle) => (debug$2("Host is toggling block style"), editor.editable?.toggleBlockStyle(blockStyle));
4123
+ static toggleList = (editor, listStyle) => editor.editable?.toggleList(listStyle);
4124
+ static toggleMark = (editor, mark) => {
4125
+ debug$2("Host toggling mark", mark), editor.editable?.toggleMark(mark);
4126
+ };
4127
+ static getFragment = (editor) => (debug$2("Host getting fragment"), editor.editable?.getFragment());
4128
+ static undo = (editor) => {
4129
+ debug$2("Host undoing"), editor.editable?.undo();
4130
+ };
4131
+ static redo = (editor) => {
4132
+ debug$2("Host redoing"), editor.editable?.redo();
4133
+ };
4134
+ static isSelectionsOverlapping = (editor, selectionA, selectionB) => editor.editable?.isSelectionsOverlapping(selectionA, selectionB);
4051
4135
  }
4052
- __publicField(PortableTextEditor, "activeAnnotations", (editor) => editor && editor.editable ? editor.editable.activeAnnotations() : []), __publicField(PortableTextEditor, "isAnnotationActive", (editor, annotationType) => editor && editor.editable ? editor.editable.isAnnotationActive(annotationType) : !1), __publicField(PortableTextEditor, "addAnnotation", (editor, type, value) => {
4053
- var _a;
4054
- return (_a = editor.editable) == null ? void 0 : _a.addAnnotation(type, value);
4055
- }), __publicField(PortableTextEditor, "blur", (editor) => {
4056
- var _a;
4057
- debug$2("Host blurred"), (_a = editor.editable) == null || _a.blur();
4058
- }), __publicField(PortableTextEditor, "delete", (editor, selection, options) => {
4059
- var _a;
4060
- return (_a = editor.editable) == null ? void 0 : _a.delete(selection, options);
4061
- }), __publicField(PortableTextEditor, "findDOMNode", (editor, element) => {
4062
- var _a;
4063
- return (_a = editor.editable) == null ? void 0 : _a.findDOMNode(element);
4064
- }), __publicField(PortableTextEditor, "findByPath", (editor, path) => {
4065
- var _a;
4066
- return ((_a = editor.editable) == null ? void 0 : _a.findByPath(path)) || [];
4067
- }), __publicField(PortableTextEditor, "focus", (editor) => {
4068
- var _a;
4069
- debug$2("Host requesting focus"), (_a = editor.editable) == null || _a.focus();
4070
- }), __publicField(PortableTextEditor, "focusBlock", (editor) => {
4071
- var _a;
4072
- return (_a = editor.editable) == null ? void 0 : _a.focusBlock();
4073
- }), __publicField(PortableTextEditor, "focusChild", (editor) => {
4074
- var _a;
4075
- return (_a = editor.editable) == null ? void 0 : _a.focusChild();
4076
- }), __publicField(PortableTextEditor, "getSelection", (editor) => editor.editable ? editor.editable.getSelection() : null), __publicField(PortableTextEditor, "getValue", (editor) => {
4077
- var _a;
4078
- return (_a = editor.editable) == null ? void 0 : _a.getValue();
4079
- }), __publicField(PortableTextEditor, "hasBlockStyle", (editor, blockStyle) => {
4080
- var _a;
4081
- return (_a = editor.editable) == null ? void 0 : _a.hasBlockStyle(blockStyle);
4082
- }), __publicField(PortableTextEditor, "hasListStyle", (editor, listStyle) => {
4083
- var _a;
4084
- return (_a = editor.editable) == null ? void 0 : _a.hasListStyle(listStyle);
4085
- }), __publicField(PortableTextEditor, "isCollapsedSelection", (editor) => {
4086
- var _a;
4087
- return (_a = editor.editable) == null ? void 0 : _a.isCollapsedSelection();
4088
- }), __publicField(PortableTextEditor, "isExpandedSelection", (editor) => {
4089
- var _a;
4090
- return (_a = editor.editable) == null ? void 0 : _a.isExpandedSelection();
4091
- }), __publicField(PortableTextEditor, "isMarkActive", (editor, mark) => {
4092
- var _a;
4093
- return (_a = editor.editable) == null ? void 0 : _a.isMarkActive(mark);
4094
- }), __publicField(PortableTextEditor, "insertChild", (editor, type, value) => {
4095
- var _a;
4096
- return debug$2("Host inserting child"), (_a = editor.editable) == null ? void 0 : _a.insertChild(type, value);
4097
- }), __publicField(PortableTextEditor, "insertBlock", (editor, type, value) => {
4098
- var _a;
4099
- return (_a = editor.editable) == null ? void 0 : _a.insertBlock(type, value);
4100
- }), __publicField(PortableTextEditor, "insertBreak", (editor) => {
4101
- var _a;
4102
- return (_a = editor.editable) == null ? void 0 : _a.insertBreak();
4103
- }), __publicField(PortableTextEditor, "isVoid", (editor, element) => {
4104
- var _a;
4105
- return (_a = editor.editable) == null ? void 0 : _a.isVoid(element);
4106
- }), __publicField(PortableTextEditor, "isObjectPath", (editor, path) => {
4107
- if (!path || !Array.isArray(path)) return !1;
4108
- const isChildObjectEditPath = path.length > 3 && path[1] === "children";
4109
- return path.length > 1 && path[1] !== "children" || isChildObjectEditPath;
4110
- }), __publicField(PortableTextEditor, "marks", (editor) => {
4111
- var _a;
4112
- return (_a = editor.editable) == null ? void 0 : _a.marks();
4113
- }), __publicField(PortableTextEditor, "select", (editor, selection) => {
4114
- var _a;
4115
- debug$2("Host setting selection", selection), (_a = editor.editable) == null || _a.select(selection);
4116
- }), __publicField(PortableTextEditor, "removeAnnotation", (editor, type) => {
4117
- var _a;
4118
- return (_a = editor.editable) == null ? void 0 : _a.removeAnnotation(type);
4119
- }), __publicField(PortableTextEditor, "toggleBlockStyle", (editor, blockStyle) => {
4120
- var _a;
4121
- return debug$2("Host is toggling block style"), (_a = editor.editable) == null ? void 0 : _a.toggleBlockStyle(blockStyle);
4122
- }), __publicField(PortableTextEditor, "toggleList", (editor, listStyle) => {
4123
- var _a;
4124
- return (_a = editor.editable) == null ? void 0 : _a.toggleList(listStyle);
4125
- }), __publicField(PortableTextEditor, "toggleMark", (editor, mark) => {
4126
- var _a;
4127
- debug$2("Host toggling mark", mark), (_a = editor.editable) == null || _a.toggleMark(mark);
4128
- }), __publicField(PortableTextEditor, "getFragment", (editor) => {
4129
- var _a;
4130
- return debug$2("Host getting fragment"), (_a = editor.editable) == null ? void 0 : _a.getFragment();
4131
- }), __publicField(PortableTextEditor, "undo", (editor) => {
4132
- var _a;
4133
- debug$2("Host undoing"), (_a = editor.editable) == null || _a.undo();
4134
- }), __publicField(PortableTextEditor, "redo", (editor) => {
4135
- var _a;
4136
- debug$2("Host redoing"), (_a = editor.editable) == null || _a.redo();
4137
- }), __publicField(PortableTextEditor, "isSelectionsOverlapping", (editor, selectionA, selectionB) => {
4138
- var _a;
4139
- return (_a = editor.editable) == null ? void 0 : _a.isSelectionsOverlapping(selectionA, selectionB);
4140
- });
4141
4136
  const debug$1 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (props) => {
4142
4137
  const { attributes, children, leaf, schemaTypes, renderChild, renderDecorator, renderAnnotation } = props, spanRef = useRef(null), portableTextEditor = usePortableTextEditor(), blockSelected = useSelected(), [focused, setFocused] = useState(!1), [selected, setSelected] = useState(!1), block = children.props.parent, path = useMemo(
4143
- () => block ? [{ _key: block == null ? void 0 : block._key }, "children", { _key: leaf._key }] : [],
4138
+ () => block ? [{ _key: block?._key }, "children", { _key: leaf._key }] : [],
4144
4139
  [block, leaf._key]
4145
4140
  ), decoratorValues = useMemo(
4146
4141
  () => schemaTypes.decorators.map((dec) => dec.value),
@@ -4150,10 +4145,7 @@ const debug$1 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
4150
4145
  [decoratorValues, leaf.marks]
4151
4146
  ), annotationMarks = Array.isArray(leaf.marks) ? leaf.marks : EMPTY_MARKS, annotations = useMemo(
4152
4147
  () => annotationMarks.map(
4153
- (mark) => {
4154
- var _a;
4155
- return !decoratorValues.includes(mark) && ((_a = block == null ? void 0 : block.markDefs) == null ? void 0 : _a.find((def) => def._key === mark));
4156
- }
4148
+ (mark) => !decoratorValues.includes(mark) && block?.markDefs?.find((def) => def._key === mark)
4157
4149
  ).filter(Boolean),
4158
4150
  [annotationMarks, block, decoratorValues]
4159
4151
  ), shouldTrackSelectionAndFocus = annotations.length > 0 && blockSelected;
@@ -4464,7 +4456,7 @@ const debug$1 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
4464
4456
  debug("Pasting normally"), slateEditor.insertData(event.clipboardData);
4465
4457
  return;
4466
4458
  }
4467
- const value = PortableTextEditor.getValue(portableTextEditor), ptRange = toPortableTextRange(value, slateEditor.selection, schemaTypes), path = (ptRange == null ? void 0 : ptRange.focus.path) || [], onPasteResult = onPaste({ event, value, path, schemaTypes });
4459
+ const value = PortableTextEditor.getValue(portableTextEditor), path = toPortableTextRange(value, slateEditor.selection, schemaTypes)?.focus.path || [], onPasteResult = onPaste({ event, value, path, schemaTypes });
4468
4460
  onPasteResult === void 0 ? (debug("No result from custom paste handler, pasting normally"), slateEditor.insertData(event.clipboardData)) : (change$.next({ type: "loading", isLoading: !0 }), Promise.resolve(onPasteResult).then((result) => {
4469
4461
  debug("Custom paste function from client resolved", result), !result || !result.insert ? (debug("No result from custom paste handler, pasting normally"), slateEditor.insertData(event.clipboardData)) : result.insert ? slateEditor.insertFragment(
4470
4462
  toSlateValue(result.insert, { schemaTypes })
@@ -4520,7 +4512,7 @@ const debug$1 = debugWithName("components:Leaf"), EMPTY_MARKS = [], Leaf = (prop
4520
4512
  const existingDOMRange = domSelection.getRangeAt(0);
4521
4513
  try {
4522
4514
  const newDOMRange = ReactEditor.toDOMRange(slateEditor, slateEditor.selection);
4523
- (newDOMRange.startOffset !== existingDOMRange.startOffset || newDOMRange.endOffset !== existingDOMRange.endOffset) && (debug("DOM range out of sync, validating selection"), domSelection == null || domSelection.removeAllRanges(), domSelection.addRange(newDOMRange));
4515
+ (newDOMRange.startOffset !== existingDOMRange.startOffset || newDOMRange.endOffset !== existingDOMRange.endOffset) && (debug("DOM range out of sync, validating selection"), domSelection?.removeAllRanges(), domSelection.addRange(newDOMRange));
4524
4516
  } catch {
4525
4517
  debug("Could not resolve selection, selecting top document"), Transforms.deselect(slateEditor), slateEditor.children.length > 0 && Transforms.select(slateEditor, [0, 0]), slateEditor.onChange();
4526
4518
  }