@portabletext/editor 3.1.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -5,7 +5,7 @@ import noop from "lodash/noop.js";
5
5
  import { createContext, useContext, useEffect, useState, useRef, forwardRef, Component, startTransition } from "react";
6
6
  import { Element as Element$1, Text, Range, Editor, Node, Point, Path, Transforms, Operation, deleteText, createEditor } from "slate";
7
7
  import { useSelected, useSlateSelector, useSlateStatic, ReactEditor, useSlate, Editable, withReact, Slate } from "slate-react";
8
- import debug$i from "debug";
8
+ import debug$h from "debug";
9
9
  import { DOMEditor, isDOMNode, EDITOR_TO_PENDING_SELECTION, IS_FOCUSED, IS_READ_ONLY } from "slate-dom";
10
10
  import { getBlockEndPoint, getBlockStartPoint, getBlockKeyFromSelectionPoint, isSelectionCollapsed, isEqualSelectionPoints, getChildKeyFromSelectionPoint, blockOffsetToSpanSelectionPoint, defaultKeyGenerator, parseBlocks, parseBlock, parseAnnotation, parseMarkDefs, parseSpan, parseInlineObject, isKeyedSegment, isListBlock, isTypedObject, getSelectionStartPoint, getSelectionEndPoint } from "./_chunks-es/util.slice-blocks.js";
11
11
  import isEqual from "lodash/isEqual.js";
@@ -29,10 +29,10 @@ import { EditorContext } from "./_chunks-es/use-editor.js";
29
29
  import { useEditor } from "./_chunks-es/use-editor.js";
30
30
  import { Subject } from "rxjs";
31
31
  const rootName = "sanity-pte:";
32
- debug$i(rootName);
32
+ debug$h(rootName);
33
33
  function debugWithName(name) {
34
34
  const namespace = `${rootName}${name}`;
35
- return debug$i && debug$i.enabled(namespace) ? debug$i(namespace) : debug$i(rootName);
35
+ return debug$h && debug$h.enabled(namespace) ? debug$h(namespace) : debug$h(rootName);
36
36
  }
37
37
  const VOID_CHILD_KEY = "void-child";
38
38
  function keepObjectEquality(object, keyMap) {
@@ -138,8 +138,8 @@ function fromSlateBlock(block, textBlockType, keyMap = {}) {
138
138
  ...typeof blockValue == "object" ? blockValue : {}
139
139
  }, keyMap);
140
140
  }
141
- function isEqualToEmptyEditor(blocks, schemaTypes) {
142
- if (blocks.length !== 1)
141
+ function isEqualToEmptyEditor(initialValue, blocks, schemaTypes) {
142
+ if (!blocks || blocks.length !== 1)
143
143
  return !1;
144
144
  const firstBlock = blocks.at(0);
145
145
  if (!firstBlock)
@@ -147,7 +147,7 @@ function isEqualToEmptyEditor(blocks, schemaTypes) {
147
147
  if (!Element$1.isElement(firstBlock) || firstBlock._type !== schemaTypes.block.name || "listItem" in firstBlock || !("style" in firstBlock) || firstBlock.style !== schemaTypes.styles.at(0)?.name || !Array.isArray(firstBlock.children) || firstBlock.children.length !== 1)
148
148
  return !1;
149
149
  const firstChild = firstBlock.children.at(0);
150
- return !(!firstChild || !Text.isText(firstChild) || !("_type" in firstChild) || firstChild._type !== schemaTypes.span.name || firstChild.text !== "" || firstChild.marks?.join(""));
150
+ return !(!firstChild || !Text.isText(firstChild) || !("_type" in firstChild) || firstChild._type !== schemaTypes.span.name || firstChild.text !== "" || firstChild.marks?.join("") || Object.keys(firstBlock).some((key) => key !== "_type" && key !== "_key" && key !== "children" && key !== "markDefs" && key !== "style") || isEqual(initialValue, [firstBlock]));
151
151
  }
152
152
  function getFocusBlock({
153
153
  editor
@@ -1538,7 +1538,7 @@ function toKeyName(name) {
1538
1538
  const keyName = name.toLowerCase();
1539
1539
  return aliases[keyName] ?? keyName;
1540
1540
  }
1541
- const debug$h = debugWithName("plugin:withHotKeys");
1541
+ const debug$g = debugWithName("plugin:withHotKeys");
1542
1542
  function createWithHotkeys(editorActor, portableTextEditor, hotkeysFromOptions) {
1543
1543
  const reservedHotkeys = ["enter", "tab", "shift", "delete", "end"], activeHotkeys = hotkeysFromOptions ?? {};
1544
1544
  return function(editor) {
@@ -1553,7 +1553,7 @@ function createWithHotkeys(editorActor, portableTextEditor, hotkeysFromOptions)
1553
1553
  const possibleMark = activeHotkeys[cat];
1554
1554
  if (possibleMark) {
1555
1555
  const mark = possibleMark[hotkey];
1556
- debug$h(`HotKey ${hotkey} to toggle ${mark}`), editorActor.send({
1556
+ debug$g(`HotKey ${hotkey} to toggle ${mark}`), editorActor.send({
1557
1557
  type: "behavior event",
1558
1558
  behaviorEvent: {
1559
1559
  type: "decorator.toggle",
@@ -1853,7 +1853,10 @@ const slateOperationCallback = ({
1853
1853
  });
1854
1854
  function createDecorate(schema, slateEditor) {
1855
1855
  return function([node, path]) {
1856
- if (isEqualToEmptyEditor(slateEditor.value, schema))
1856
+ const defaultStyle = schema.styles.at(0)?.name;
1857
+ if (slateEditor.value.length === 1 && isEmptyTextBlock({
1858
+ schema
1859
+ }, slateEditor.value[0]) && (!slateEditor.value[0].style || slateEditor.value[0].style === defaultStyle) && !slateEditor.value[0].listItem)
1857
1860
  return [{
1858
1861
  anchor: {
1859
1862
  path: [0, 0],
@@ -1882,7 +1885,7 @@ function createDecorate(schema, slateEditor) {
1882
1885
  }) || Range.includes(decoratedRange, path));
1883
1886
  };
1884
1887
  }
1885
- const RelayActorContext = createContext({}), debug$g = debugWithName("validate selection machine"), validateSelectionSetup = setup({
1888
+ const RelayActorContext = createContext({}), debug$f = debugWithName("validate selection machine"), validateSelectionSetup = setup({
1886
1889
  types: {
1887
1890
  context: {},
1888
1891
  input: {},
@@ -1954,12 +1957,12 @@ function validateSelection(slateEditor, editorElement) {
1954
1957
  const existingDOMRange = domSelection.getRangeAt(0);
1955
1958
  try {
1956
1959
  const newDOMRange = ReactEditor.toDOMRange(slateEditor, slateEditor.selection);
1957
- (newDOMRange.startOffset !== existingDOMRange.startOffset || newDOMRange.endOffset !== existingDOMRange.endOffset) && (debug$g("DOM range out of sync, validating selection"), domSelection?.removeAllRanges(), domSelection.addRange(newDOMRange));
1960
+ (newDOMRange.startOffset !== existingDOMRange.startOffset || newDOMRange.endOffset !== existingDOMRange.endOffset) && (debug$f("DOM range out of sync, validating selection"), domSelection?.removeAllRanges(), domSelection.addRange(newDOMRange));
1958
1961
  } catch {
1959
- debug$g("Could not resolve selection, selecting top document"), Transforms.deselect(slateEditor), slateEditor.children.length > 0 && Transforms.select(slateEditor, Editor.start(slateEditor, [])), slateEditor.onChange();
1962
+ debug$f("Could not resolve selection, selecting top document"), Transforms.deselect(slateEditor), slateEditor.children.length > 0 && Transforms.select(slateEditor, Editor.start(slateEditor, [])), slateEditor.onChange();
1960
1963
  }
1961
1964
  }
1962
- const debug$f = debugWithName("component:Editable"), PortableTextEditable = forwardRef(function(props, forwardedRef) {
1965
+ const debug$e = debugWithName("component:Editable"), PortableTextEditable = forwardRef(function(props, forwardedRef) {
1963
1966
  const $ = c(176);
1964
1967
  let hotkeys, onBeforeInput, onBlur, onClick, onCopy, onCut, onDrag, onDragEnd, onDragEnter, onDragLeave, onDragOver, onDragStart, onDrop, onFocus, onPaste, propsSelection, rangeDecorations, renderAnnotation, renderBlock, renderChild, renderDecorator, renderListItem, renderPlaceholder, renderStyle, restProps, scrollSelectionIntoView, spellCheck;
1965
1968
  $[0] !== props ? ({
@@ -2048,10 +2051,10 @@ const debug$f = debugWithName("component:Editable"), PortableTextEditable = forw
2048
2051
  let t14;
2049
2052
  $[63] !== editorActor || $[64] !== propsSelection || $[65] !== slateEditor ? (t14 = () => {
2050
2053
  if (propsSelection) {
2051
- debug$f(`Selection from props ${JSON.stringify(propsSelection)}`);
2054
+ debug$e(`Selection from props ${JSON.stringify(propsSelection)}`);
2052
2055
  const normalizedSelection = normalizeSelection(propsSelection, slateEditor.value);
2053
2056
  if (normalizedSelection !== null) {
2054
- debug$f(`Normalized selection from props ${JSON.stringify(normalizedSelection)}`);
2057
+ debug$e(`Normalized selection from props ${JSON.stringify(normalizedSelection)}`);
2055
2058
  const slateRange = toSlateRange({
2056
2059
  context: {
2057
2060
  schema: editorActor.getSnapshot().context.schema,
@@ -2163,8 +2166,8 @@ const debug$f = debugWithName("component:Editable"), PortableTextEditable = forw
2163
2166
  event_1.preventDefault(), relayActor.send({
2164
2167
  type: "loading"
2165
2168
  }), Promise.resolve(onPasteResult).then((result_1) => {
2166
- if (debug$f("Custom paste function from client resolved", result_1), !result_1 || !result_1.insert) {
2167
- debug$f("No result from custom paste handler, pasting normally");
2169
+ if (debug$e("Custom paste function from client resolved", result_1), !result_1 || !result_1.insert) {
2170
+ debug$e("No result from custom paste handler, pasting normally");
2168
2171
  const selection_1 = editorActor.getSnapshot().context.selection, position_1 = selection_1 ? {
2169
2172
  selection: selection_1
2170
2173
  } : void 0;
@@ -2232,7 +2235,7 @@ const debug$f = debugWithName("component:Editable"), PortableTextEditable = forw
2232
2235
  nativeEvent: event_1
2233
2236
  });
2234
2237
  }
2235
- debug$f("No result from custom paste handler, pasting normally");
2238
+ debug$e("No result from custom paste handler, pasting normally");
2236
2239
  }, $[85] = editorActor, $[86] = onPaste, $[87] = portableTextEditor, $[88] = relayActor, $[89] = slateEditor, $[90] = t21) : t21 = $[90];
2237
2240
  const handlePaste = t21;
2238
2241
  let t22;
@@ -2972,7 +2975,7 @@ function mergeIntoLastStep(steps, lastStep, op) {
2972
2975
  operations: [...lastStep.operations, op]
2973
2976
  }];
2974
2977
  }
2975
- const debug$e = debugWithName("plugin:history"), UNDO_STEP_LIMIT = 1e3;
2978
+ const debug$d = debugWithName("plugin:history"), UNDO_STEP_LIMIT = 1e3;
2976
2979
  function pluginHistory({
2977
2980
  editorActor,
2978
2981
  subscriptions
@@ -2989,7 +2992,7 @@ function pluginHistory({
2989
2992
  for (const patch of patches)
2990
2993
  if (!reset && patch.origin !== "local") {
2991
2994
  if (patch.type === "unset" && patch.path.length === 0) {
2992
- debug$e("Someone else cleared the content, resetting undo/redo history"), editor.history = {
2995
+ debug$d("Someone else cleared the content, resetting undo/redo history"), editor.history = {
2993
2996
  undos: [],
2994
2997
  redos: []
2995
2998
  }, remotePatches.splice(0, remotePatches.length), setWithHistory(editor, !0), reset = !0;
@@ -3074,7 +3077,15 @@ function getNextSpan({
3074
3077
  }
3075
3078
  return nextSpan;
3076
3079
  }
3077
- const debug$d = debugWithName("plugin:withPortableTextMarkModel");
3080
+ const PATCHING = /* @__PURE__ */ new WeakMap();
3081
+ function withoutPatching(editor, fn) {
3082
+ const prev = isPatching(editor);
3083
+ PATCHING.set(editor, !1), fn(), PATCHING.set(editor, prev);
3084
+ }
3085
+ function isPatching(editor) {
3086
+ return PATCHING.get(editor);
3087
+ }
3088
+ const debug$c = debugWithName("plugin:withPortableTextMarkModel");
3078
3089
  function createWithPortableTextMarkModel(editorActor) {
3079
3090
  return function(editor) {
3080
3091
  const {
@@ -3083,12 +3094,19 @@ function createWithPortableTextMarkModel(editorActor) {
3083
3094
  } = editor, decorators = editorActor.getSnapshot().context.schema.decorators.map((t) => t.name), defaultStyle = editorActor.getSnapshot().context.schema.styles.at(0)?.name;
3084
3095
  return editor.normalizeNode = (nodeEntry) => {
3085
3096
  const [node, path] = nodeEntry;
3086
- if (editor.isTextBlock(node)) {
3097
+ if (Editor.isEditor(node) && node.children.length === 0 && withoutPatching(editor, () => {
3098
+ withNormalizeNode(editor, () => {
3099
+ Transforms.insertNodes(editor, createPlaceholderBlock(editorActor.getSnapshot().context), {
3100
+ at: [0],
3101
+ select: !0
3102
+ });
3103
+ });
3104
+ }), editor.isTextBlock(node)) {
3087
3105
  const children = Node.children(editor, path);
3088
3106
  for (const [child, childPath] of children) {
3089
3107
  const nextNode = node.children[childPath[1] + 1];
3090
3108
  if (editor.isTextSpan(child) && editor.isTextSpan(nextNode) && child.marks?.every((mark) => nextNode.marks?.includes(mark)) && nextNode.marks?.every((mark) => child.marks?.includes(mark))) {
3091
- debug$d("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), withNormalizeNode(editor, () => {
3109
+ debug$c("Merging spans", JSON.stringify(child, null, 2), JSON.stringify(nextNode, null, 2)), withNormalizeNode(editor, () => {
3092
3110
  Transforms.mergeNodes(editor, {
3093
3111
  at: [childPath[0], childPath[1] + 1],
3094
3112
  voids: !0
@@ -3099,7 +3117,7 @@ function createWithPortableTextMarkModel(editorActor) {
3099
3117
  }
3100
3118
  }
3101
3119
  if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {
3102
- debug$d("Adding .markDefs to block node"), withNormalizeNode(editor, () => {
3120
+ debug$c("Adding .markDefs to block node"), withNormalizeNode(editor, () => {
3103
3121
  Transforms.setNodes(editor, {
3104
3122
  markDefs: []
3105
3123
  }, {
@@ -3109,7 +3127,7 @@ function createWithPortableTextMarkModel(editorActor) {
3109
3127
  return;
3110
3128
  }
3111
3129
  if (defaultStyle && editor.isTextBlock(node) && typeof node.style > "u") {
3112
- debug$d("Adding .style to block node"), withNormalizeNode(editor, () => {
3130
+ debug$c("Adding .style to block node"), withNormalizeNode(editor, () => {
3113
3131
  Transforms.setNodes(editor, {
3114
3132
  style: defaultStyle
3115
3133
  }, {
@@ -3119,7 +3137,7 @@ function createWithPortableTextMarkModel(editorActor) {
3119
3137
  return;
3120
3138
  }
3121
3139
  if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {
3122
- debug$d("Adding .marks to span node"), withNormalizeNode(editor, () => {
3140
+ debug$c("Adding .marks to span node"), withNormalizeNode(editor, () => {
3123
3141
  Transforms.setNodes(editor, {
3124
3142
  marks: []
3125
3143
  }, {
@@ -3131,7 +3149,7 @@ function createWithPortableTextMarkModel(editorActor) {
3131
3149
  if (editor.isTextSpan(node)) {
3132
3150
  const blockPath = Path.parent(path), [block] = Editor.node(editor, blockPath), decorators2 = editorActor.getSnapshot().context.schema.decorators.map((decorator) => decorator.name), annotations = node.marks?.filter((mark) => !decorators2.includes(mark));
3133
3151
  if (editor.isTextBlock(block) && node.text === "" && annotations && annotations.length > 0) {
3134
- debug$d("Removing annotations from empty span node"), withNormalizeNode(editor, () => {
3152
+ debug$c("Removing annotations from empty span node"), withNormalizeNode(editor, () => {
3135
3153
  Transforms.setNodes(editor, {
3136
3154
  marks: node.marks?.filter((mark) => decorators2.includes(mark))
3137
3155
  }, {
@@ -3147,7 +3165,7 @@ function createWithPortableTextMarkModel(editorActor) {
3147
3165
  if (editor.isTextSpan(child)) {
3148
3166
  const marks = child.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !node.markDefs?.find((def) => def._key === mark));
3149
3167
  if (orphanedAnnotations.length > 0) {
3150
- debug$d("Removing orphaned annotations from span node"), withNormalizeNode(editor, () => {
3168
+ debug$c("Removing orphaned annotations from span node"), withNormalizeNode(editor, () => {
3151
3169
  Transforms.setNodes(editor, {
3152
3170
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
3153
3171
  }, {
@@ -3163,7 +3181,7 @@ function createWithPortableTextMarkModel(editorActor) {
3163
3181
  if (editor.isTextBlock(block)) {
3164
3182
  const decorators2 = editorActor.getSnapshot().context.schema.decorators.map((decorator) => decorator.name), marks = node.marks ?? [], orphanedAnnotations = marks.filter((mark) => !decorators2.includes(mark) && !block.markDefs?.find((def) => def._key === mark));
3165
3183
  if (orphanedAnnotations.length > 0) {
3166
- debug$d("Removing orphaned annotations from span node"), withNormalizeNode(editor, () => {
3184
+ debug$c("Removing orphaned annotations from span node"), withNormalizeNode(editor, () => {
3167
3185
  Transforms.setNodes(editor, {
3168
3186
  marks: marks.filter((mark) => !orphanedAnnotations.includes(mark))
3169
3187
  }, {
@@ -3179,7 +3197,7 @@ function createWithPortableTextMarkModel(editorActor) {
3179
3197
  for (const markDef of markDefs)
3180
3198
  markDefKeys.has(markDef._key) || (markDefKeys.add(markDef._key), newMarkDefs.push(markDef));
3181
3199
  if (markDefs.length !== newMarkDefs.length) {
3182
- debug$d("Removing duplicate markDefs"), withNormalizeNode(editor, () => {
3200
+ debug$c("Removing duplicate markDefs"), withNormalizeNode(editor, () => {
3183
3201
  Transforms.setNodes(editor, {
3184
3202
  markDefs: newMarkDefs
3185
3203
  }, {
@@ -3192,7 +3210,7 @@ function createWithPortableTextMarkModel(editorActor) {
3192
3210
  if (editor.isTextBlock(node) && !editor.operations.some((op) => op.type === "merge_node" && "markDefs" in op.properties && op.path.length === 1)) {
3193
3211
  const newMarkDefs = (node.markDefs || []).filter((def) => node.children.find((child) => Text.isText(child) && Array.isArray(child.marks) && child.marks.includes(def._key)));
3194
3212
  if (node.markDefs && !isEqual(newMarkDefs, node.markDefs)) {
3195
- debug$d("Removing markDef not in use"), withNormalizeNode(editor, () => {
3213
+ debug$c("Removing markDef not in use"), withNormalizeNode(editor, () => {
3196
3214
  Transforms.setNodes(editor, {
3197
3215
  markDefs: newMarkDefs
3198
3216
  }, {
@@ -3284,7 +3302,7 @@ function createWithPortableTextMarkModel(editorActor) {
3284
3302
  const [targetBlock, targetPath] = Editor.node(editor, [op.path[0] - 1]);
3285
3303
  if (editor.isTextBlock(targetBlock)) {
3286
3304
  const oldDefs = Array.isArray(targetBlock.markDefs) && targetBlock.markDefs || [], newMarkDefs = uniq([...oldDefs, ...op.properties.markDefs]);
3287
- debug$d("Copying markDefs over to merged block", op), Transforms.setNodes(editor, {
3305
+ debug$c("Copying markDefs over to merged block", op), Transforms.setNodes(editor, {
3288
3306
  markDefs: newMarkDefs
3289
3307
  }, {
3290
3308
  at: targetPath,
@@ -3980,7 +3998,7 @@ function parse(textline) {
3980
3998
  function toInt(num) {
3981
3999
  return parseInt(num, 10);
3982
4000
  }
3983
- const debug$c = debugWithName("transformOperation");
4001
+ const debug$b = debugWithName("transformOperation");
3984
4002
  function transformOperation(editor, patch, operation, snapshot, previousSnapshot) {
3985
4003
  const transformedOperation = {
3986
4004
  ...operation
@@ -3989,16 +4007,16 @@ function transformOperation(editor, patch, operation, snapshot, previousSnapshot
3989
4007
  const insertBlockIndex = (snapshot || []).findIndex((blk) => isEqual({
3990
4008
  _key: blk._key
3991
4009
  }, patch.path[0]));
3992
- return debug$c(`Adjusting block path (+${patch.items.length}) for '${transformedOperation.type}' operation and patch '${patch.type}'`), [adjustBlockPath(transformedOperation, patch.items.length, insertBlockIndex)];
4010
+ return debug$b(`Adjusting block path (+${patch.items.length}) for '${transformedOperation.type}' operation and patch '${patch.type}'`), [adjustBlockPath(transformedOperation, patch.items.length, insertBlockIndex)];
3993
4011
  }
3994
4012
  if (patch.type === "unset" && patch.path.length === 1) {
3995
4013
  const unsetBlockIndex = (previousSnapshot || []).findIndex((blk) => isEqual({
3996
4014
  _key: blk._key
3997
4015
  }, patch.path[0]));
3998
- return "path" in transformedOperation && Array.isArray(transformedOperation.path) && transformedOperation.path[0] === unsetBlockIndex ? (debug$c("Skipping transformation that targeted removed block"), []) : [adjustBlockPath(transformedOperation, -1, unsetBlockIndex)];
4016
+ return "path" in transformedOperation && Array.isArray(transformedOperation.path) && transformedOperation.path[0] === unsetBlockIndex ? (debug$b("Skipping transformation that targeted removed block"), []) : [adjustBlockPath(transformedOperation, -1, unsetBlockIndex)];
3999
4017
  }
4000
4018
  if (patch.type === "unset" && patch.path.length === 0)
4001
- return debug$c(`Adjusting selection for unset everything patch and ${operation.type} operation`), [];
4019
+ return debug$b(`Adjusting selection for unset everything patch and ${operation.type} operation`), [];
4002
4020
  if (patch.type === "diffMatchPatch") {
4003
4021
  const operationTargetBlock = findOperationTargetBlock(editor, transformedOperation);
4004
4022
  return !operationTargetBlock || !isEqual({
@@ -4069,7 +4087,7 @@ function findOperationTargetBlock(editor, operation) {
4069
4087
  let block;
4070
4088
  return operation.type === "set_selection" && editor.selection ? block = editor.children[editor.selection.focus.path[0]] : "path" in operation && (block = editor.children[operation.path[0]]), block;
4071
4089
  }
4072
- const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOperationImplementation = ({
4090
+ const debug$a = debugWithName("behavior.operation.history.redo"), historyRedoOperationImplementation = ({
4073
4091
  operation
4074
4092
  }) => {
4075
4093
  const editor = operation.editor, {
@@ -4077,7 +4095,7 @@ const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOpe
4077
4095
  } = editor.history, remotePatches = getRemotePatches(editor);
4078
4096
  if (redos.length > 0) {
4079
4097
  const step = redos[redos.length - 1];
4080
- if (debug$b("Redoing", step), step.operations.length > 0) {
4098
+ if (debug$a("Redoing", step), step.operations.length > 0) {
4081
4099
  const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
4082
4100
  let transformedOperations = step.operations;
4083
4101
  otherPatches.forEach((item) => {
@@ -4094,7 +4112,7 @@ const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOpe
4094
4112
  });
4095
4113
  });
4096
4114
  } catch (err) {
4097
- debug$b("Could not perform redo step", err), remotePatches.splice(0, remotePatches.length), Transforms.deselect(editor), editor.history = {
4115
+ debug$a("Could not perform redo step", err), remotePatches.splice(0, remotePatches.length), Transforms.deselect(editor), editor.history = {
4098
4116
  undos: [],
4099
4117
  redos: []
4100
4118
  }, setWithHistory(editor, !0), setIsRedoing(editor, !1), editor.onChange();
@@ -4103,7 +4121,7 @@ const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOpe
4103
4121
  editor.history.undos.push(step), editor.history.redos.pop();
4104
4122
  }
4105
4123
  }
4106
- }, debug$a = debugWithName("behavior.operation.history.undo"), historyUndoOperationImplementation = ({
4124
+ }, debug$9 = debugWithName("behavior.operation.history.undo"), historyUndoOperationImplementation = ({
4107
4125
  operation
4108
4126
  }) => {
4109
4127
  const editor = operation.editor, {
@@ -4111,7 +4129,7 @@ const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOpe
4111
4129
  } = editor.history, remotePatches = getRemotePatches(editor);
4112
4130
  if (undos.length > 0) {
4113
4131
  const step = undos[undos.length - 1];
4114
- if (debug$a("Undoing", step), step.operations.length > 0) {
4132
+ if (debug$9("Undoing", step), step.operations.length > 0) {
4115
4133
  const otherPatches = remotePatches.filter((item) => item.time >= step.timestamp);
4116
4134
  let transformedOperations = step.operations;
4117
4135
  otherPatches.forEach((item) => {
@@ -4129,7 +4147,7 @@ const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOpe
4129
4147
  });
4130
4148
  });
4131
4149
  } catch (err) {
4132
- debug$a("Could not perform undo step", err), remotePatches.splice(0, remotePatches.length), Transforms.deselect(editor), editor.history = {
4150
+ debug$9("Could not perform undo step", err), remotePatches.splice(0, remotePatches.length), Transforms.deselect(editor), editor.history = {
4133
4151
  undos: [],
4134
4152
  redos: []
4135
4153
  }, setWithHistory(editor, !0), setIsUndoing(editor, !1), editor.onChange();
@@ -4583,7 +4601,7 @@ const debug$b = debugWithName("behavior.operation.history.redo"), historyRedoOpe
4583
4601
  }
4584
4602
  },
4585
4603
  mode: "highest"
4586
- }), operation.editor.children.length === 0 && Transforms.insertNodes(operation.editor, createPlaceholderBlock(context));
4604
+ });
4587
4605
  return;
4588
4606
  }
4589
4607
  if (operation.unit === "child") {
@@ -4699,7 +4717,11 @@ function insertBlock(options) {
4699
4717
  selection: options.at
4700
4718
  },
4701
4719
  blockIndexMap: editor.blockIndexMap
4702
- }) : editor.selection, start = at ? Range.start(at) : Editor.start(editor, []), end = at ? Range.end(at) : Editor.end(editor, []), [startBlock, startBlockPath] = Array.from(Editor.nodes(editor, {
4720
+ }) : editor.selection;
4721
+ editor.children.length === 0 && Transforms.insertNodes(editor, createPlaceholderBlock(context), {
4722
+ at: [0]
4723
+ });
4724
+ const start = at ? Range.start(at) : Editor.start(editor, []), end = at ? Range.end(at) : Editor.end(editor, []), [startBlock, startBlockPath] = Array.from(Editor.nodes(editor, {
4703
4725
  at: start,
4704
4726
  mode: "lowest",
4705
4727
  match: (node, path) => Element$1.isElement(node) && path.length <= start.path.length
@@ -5584,7 +5606,7 @@ function createApplyPatch(context) {
5584
5606
  changed = insertPatch(context, editor, patch);
5585
5607
  break;
5586
5608
  case "unset":
5587
- changed = unsetPatch(context, editor, patch);
5609
+ changed = unsetPatch(editor, patch);
5588
5610
  break;
5589
5611
  case "set":
5590
5612
  changed = setPatch(editor, patch);
@@ -5626,7 +5648,18 @@ function diffMatchPatch(editor, patch) {
5626
5648
  }
5627
5649
  function insertPatch(context, editor, patch) {
5628
5650
  const block = findBlock(editor.children, patch.path);
5629
- if (!block || patch.path.length > 1 && patch.path[1] !== "children")
5651
+ if (!block) {
5652
+ if (patch.path.length === 1 && patch.path[0] === 0) {
5653
+ const blocksToInsert = patch.items.map((item) => toSlateBlock(item, {
5654
+ schemaTypes: context.schema
5655
+ }, KEY_TO_SLATE_ELEMENT.get(editor)));
5656
+ return Transforms.insertNodes(editor, blocksToInsert, {
5657
+ at: [0]
5658
+ }), !0;
5659
+ }
5660
+ return !1;
5661
+ }
5662
+ if (patch.path.length > 1 && patch.path[1] !== "children")
5630
5663
  return !1;
5631
5664
  if (patch.path.length === 1) {
5632
5665
  const {
@@ -5634,7 +5667,7 @@ function insertPatch(context, editor, patch) {
5634
5667
  position: position2
5635
5668
  } = patch, blocksToInsert = items2.map((item) => toSlateBlock(item, {
5636
5669
  schemaTypes: context.schema
5637
- }, KEY_TO_SLATE_ELEMENT.get(editor))), targetBlockIndex = block.index, normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex, editorWasEmptyBefore = isEqualToEmptyEditor(editor.value, context.schema);
5670
+ }, KEY_TO_SLATE_ELEMENT.get(editor))), targetBlockIndex = block.index, normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex, editorWasEmptyBefore = isEqualToEmptyEditor(context.initialValue, editor.value, context.schema);
5638
5671
  return Transforms.insertNodes(editor, blocksToInsert, {
5639
5672
  at: [normalizedIdx2]
5640
5673
  }), editorWasEmptyBefore && typeof patch.path[0] == "number" && patch.path[0] === 0 && Transforms.removeNodes(editor, {
@@ -5791,9 +5824,8 @@ function setPatch(editor, patch) {
5791
5824
  return !1;
5792
5825
  return !0;
5793
5826
  }
5794
- function unsetPatch(context, editor, patch) {
5827
+ function unsetPatch(editor, patch) {
5795
5828
  if (patch.path.length === 0) {
5796
- const previousSelection = editor.selection;
5797
5829
  Transforms.deselect(editor);
5798
5830
  const children = Node.children(editor, [], {
5799
5831
  reverse: !0
@@ -5802,40 +5834,15 @@ function unsetPatch(context, editor, patch) {
5802
5834
  Transforms.removeNodes(editor, {
5803
5835
  at: path
5804
5836
  });
5805
- return Transforms.insertNodes(editor, createPlaceholderBlock(context)), previousSelection && Transforms.select(editor, {
5806
- anchor: {
5807
- path: [0, 0],
5808
- offset: 0
5809
- },
5810
- focus: {
5811
- path: [0, 0],
5812
- offset: 0
5813
- }
5814
- }), editor.onChange(), !0;
5837
+ return !0;
5815
5838
  }
5816
5839
  const block = findBlock(editor.children, patch.path);
5817
5840
  if (!block)
5818
5841
  return !1;
5819
- if (patch.path.length === 1) {
5820
- if (editor.children.length === 1) {
5821
- const previousSelection = editor.selection;
5822
- return Transforms.deselect(editor), Transforms.removeNodes(editor, {
5823
- at: [block.index]
5824
- }), Transforms.insertNodes(editor, createPlaceholderBlock(context)), previousSelection && Transforms.select(editor, {
5825
- anchor: {
5826
- path: [0, 0],
5827
- offset: 0
5828
- },
5829
- focus: {
5830
- path: [0, 0],
5831
- offset: 0
5832
- }
5833
- }), editor.onChange(), !0;
5834
- }
5842
+ if (patch.path.length === 1)
5835
5843
  return Transforms.removeNodes(editor, {
5836
5844
  at: [block.index]
5837
5845
  }), !0;
5838
- }
5839
5846
  const child = findBlockChild(block, patch.path);
5840
5847
  if (editor.isTextBlock(block.node) && child && patch.path[1] === "children" && patch.path.length === 3)
5841
5848
  return Transforms.removeNodes(editor, {
@@ -6218,15 +6225,7 @@ function moveNodePatch(schema, beforeValue, operation) {
6218
6225
  }
6219
6226
  return patches;
6220
6227
  }
6221
- const PATCHING = /* @__PURE__ */ new WeakMap();
6222
- function withoutPatching(editor, fn) {
6223
- const prev = isPatching(editor);
6224
- PATCHING.set(editor, !1), fn(), PATCHING.set(editor, prev);
6225
- }
6226
- function isPatching(editor) {
6227
- return PATCHING.get(editor);
6228
- }
6229
- const debug$9 = debugWithName("plugin:withPatches");
6228
+ const debug$8 = debugWithName("plugin:withPatches");
6230
6229
  function createWithPatches({
6231
6230
  editorActor,
6232
6231
  relayActor,
@@ -6251,7 +6250,7 @@ function createWithPatches({
6251
6250
  withoutPatching(editor, () => {
6252
6251
  pluginWithoutHistory(editor, () => {
6253
6252
  for (const patch of patches) {
6254
- debug$9.enabled && debug$9(`Handling remote patch ${JSON.stringify(patch)}`);
6253
+ debug$8.enabled && debug$8(`Handling remote patch ${JSON.stringify(patch)}`);
6255
6254
  try {
6256
6255
  changed = applyPatch(editor, patch);
6257
6256
  } catch (error) {
@@ -6269,17 +6268,17 @@ function createWithPatches({
6269
6268
  remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
6270
6269
  };
6271
6270
  return subscriptions.push(() => {
6272
- debug$9("Subscribing to remote patches");
6271
+ debug$8("Subscribing to remote patches");
6273
6272
  const sub = editorActor.on("patches", handlePatches);
6274
6273
  return () => {
6275
- debug$9("Unsubscribing to remote patches"), sub.unsubscribe();
6274
+ debug$8("Unsubscribing to remote patches"), sub.unsubscribe();
6276
6275
  };
6277
6276
  }), editor.apply = (operation) => {
6278
6277
  let patches = [];
6279
6278
  previousValue = editor.value;
6280
- const editorWasEmpty = isEqualToEmptyEditor(previousValue, editorActor.getSnapshot().context.schema);
6279
+ const editorWasEmpty = isEqualToEmptyEditor(editorActor.getSnapshot().context.initialValue, previousValue, editorActor.getSnapshot().context.schema);
6281
6280
  apply2(operation);
6282
- const editorIsEmpty = isEqualToEmptyEditor(editor.value, editorActor.getSnapshot().context.schema);
6281
+ const editorIsEmpty = isEqualToEmptyEditor(editorActor.getSnapshot().context.initialValue, editor.value, editorActor.getSnapshot().context.schema);
6283
6282
  if (!isPatching(editor))
6284
6283
  return editor;
6285
6284
  switch (editorWasEmpty && !editorIsEmpty && operation.type !== "set_selection" && patches.push(insert(previousValue, "before", [0])), operation.type) {
@@ -6326,35 +6325,6 @@ function createWithPatches({
6326
6325
  }, editor;
6327
6326
  };
6328
6327
  }
6329
- const debug$8 = debugWithName("plugin:withPlaceholderBlock");
6330
- function createWithPlaceholderBlock(editorActor) {
6331
- return function(editor) {
6332
- const {
6333
- apply: apply2
6334
- } = editor;
6335
- return editor.apply = (op) => {
6336
- if (editorActor.getSnapshot().matches({
6337
- "edit mode": "read only"
6338
- })) {
6339
- apply2(op);
6340
- return;
6341
- }
6342
- if (isChangingRemotely(editor)) {
6343
- apply2(op);
6344
- return;
6345
- }
6346
- if (isUndoing(editor) || isRedoing(editor)) {
6347
- apply2(op);
6348
- return;
6349
- }
6350
- if (op.type === "remove_node") {
6351
- const blockIndex = op.path.at(0), isLonelyBlock = op.path.length === 1 && blockIndex === 0 && editor.children.length === 1, isBlockObject = op.node._type !== editorActor.getSnapshot().context.schema.block.name;
6352
- isLonelyBlock && isBlockObject && (debug$8("Adding placeholder block"), Editor.insertNode(editor, createPlaceholderBlock(editorActor.getSnapshot().context)));
6353
- }
6354
- apply2(op);
6355
- }, editor;
6356
- };
6357
- }
6358
6328
  const debug$7 = debugWithName("plugin:withSchemaTypes");
6359
6329
  function createWithSchemaTypes({
6360
6330
  editorActor
@@ -6738,11 +6708,11 @@ const withPlugins = (editor, options) => {
6738
6708
  }), withUndoRedo = pluginHistory({
6739
6709
  editorActor,
6740
6710
  subscriptions: options.subscriptions
6741
- }), withPortableTextMarkModel = createWithPortableTextMarkModel(editorActor), withPlaceholderBlock = createWithPlaceholderBlock(editorActor);
6742
- return createWithEventListeners(editorActor)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPlaceholderBlock(withUndoRedo(withPatches(pluginUpdateValue(editorActor.getSnapshot().context, pluginUpdateSelection({
6711
+ }), withPortableTextMarkModel = createWithPortableTextMarkModel(editorActor);
6712
+ return createWithEventListeners(editorActor)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withUndoRedo(withPatches(pluginUpdateValue(editorActor.getSnapshot().context, pluginUpdateSelection({
6743
6713
  editorActor,
6744
6714
  editor: e
6745
- })))))))));
6715
+ }))))))));
6746
6716
  }, debug$6 = debugWithName("setup");
6747
6717
  function createSlateEditor(config) {
6748
6718
  debug$6("Creating new Slate editor instance");
@@ -6753,19 +6723,15 @@ function createSlateEditor(config) {
6753
6723
  relayActor: config.relayActor,
6754
6724
  subscriptions: config.subscriptions
6755
6725
  });
6756
- KEY_TO_SLATE_ELEMENT.set(instance, {}), buildIndexMaps({
6726
+ return KEY_TO_SLATE_ELEMENT.set(instance, {}), buildIndexMaps({
6757
6727
  schema: config.editorActor.getSnapshot().context.schema,
6758
6728
  value: instance.value
6759
6729
  }, {
6760
6730
  blockIndexMap: instance.blockIndexMap,
6761
6731
  listIndexMap: instance.listIndexMap
6762
- });
6763
- const initialValue = [toSlateBlock(placeholderBlock, {
6764
- schemaTypes: config.editorActor.getSnapshot().context.schema
6765
- })];
6766
- return {
6732
+ }), {
6767
6733
  instance,
6768
- initialValue
6734
+ initialValue: [placeholderBlock]
6769
6735
  };
6770
6736
  }
6771
6737
  function createEditorDom(sendBack, slateEditor) {
@@ -11766,10 +11732,8 @@ async function updateValue({
11766
11732
  let doneSyncing = !1, isChanged = !1, isValid = !0;
11767
11733
  const hadSelection = !!slateEditor.selection;
11768
11734
  if ((!value || value.length === 0) && (debug$2("Value is empty"), clearEditor({
11769
- context,
11770
11735
  slateEditor,
11771
- doneSyncing,
11772
- hadSelection
11736
+ doneSyncing
11773
11737
  }), isChanged = !0), value && value.length > 0)
11774
11738
  if (streamBlocks)
11775
11739
  await new Promise((resolve) => {
@@ -11876,10 +11840,8 @@ async function* getStreamedBlocks({
11876
11840
  index % 10 === 0 && await new Promise((resolve) => setTimeout(resolve, 0)), yield [block, index], index++;
11877
11841
  }
11878
11842
  function clearEditor({
11879
- context,
11880
11843
  slateEditor,
11881
- doneSyncing,
11882
- hadSelection
11844
+ doneSyncing
11883
11845
  }) {
11884
11846
  Editor.withoutNormalizing(slateEditor, () => {
11885
11847
  pluginWithoutHistory(slateEditor, () => {
@@ -11887,15 +11849,12 @@ function clearEditor({
11887
11849
  withoutPatching(slateEditor, () => {
11888
11850
  if (doneSyncing)
11889
11851
  return;
11890
- hadSelection && Transforms.deselect(slateEditor);
11891
11852
  const childrenLength = slateEditor.children.length;
11892
11853
  slateEditor.children.forEach((_, index) => {
11893
11854
  Transforms.removeNodes(slateEditor, {
11894
11855
  at: [childrenLength - 1 - index]
11895
11856
  });
11896
- }), Transforms.insertNodes(slateEditor, createPlaceholderBlock(context), {
11897
- at: [0]
11898
- }), hadSelection && Transforms.select(slateEditor, [0, 0]);
11857
+ });
11899
11858
  });
11900
11859
  });
11901
11860
  });