@portabletext/editor 1.44.12 → 1.44.14

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.
@@ -4,120 +4,6 @@ function _interopDefaultCompat(e) {
4
4
  return e && typeof e == "object" && "default" in e ? e : { default: e };
5
5
  }
6
6
  var React__default = /* @__PURE__ */ _interopDefaultCompat(React), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$g), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), flatten__default = /* @__PURE__ */ _interopDefaultCompat(flatten), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), uniq__default = /* @__PURE__ */ _interopDefaultCompat(uniq), getRandomValues__default = /* @__PURE__ */ _interopDefaultCompat(getRandomValues), get__default = /* @__PURE__ */ _interopDefaultCompat(get), isUndefined__default = /* @__PURE__ */ _interopDefaultCompat(isUndefined), omitBy__default = /* @__PURE__ */ _interopDefaultCompat(omitBy), omit__default = /* @__PURE__ */ _interopDefaultCompat(omit), startCase__default = /* @__PURE__ */ _interopDefaultCompat(startCase);
7
- function createEditorSchema(portableTextType) {
8
- if (!portableTextType)
9
- throw new Error("Parameter 'portabletextType' missing (required)");
10
- const blockType = portableTextType.of?.find(findBlockType);
11
- if (!blockType)
12
- throw new Error("Block type is not defined in this schema (required)");
13
- const childrenField = blockType.fields?.find((field) => field.name === "children");
14
- if (!childrenField)
15
- throw new Error("Children field for block type found in schema (required)");
16
- const ofType = childrenField.type.of;
17
- if (!ofType)
18
- throw new Error("Valid types for block children not found in schema (required)");
19
- const spanType = ofType.find((memberType) => memberType.name === "span");
20
- if (!spanType)
21
- throw new Error("Span type not found in schema (required)");
22
- const inlineObjectTypes = ofType.filter((memberType) => memberType.name !== "span") || [], blockObjectTypes = portableTextType.of?.filter((field) => field.name !== blockType.name) || [];
23
- return {
24
- styles: resolveEnabledStyles(blockType),
25
- decorators: resolveEnabledDecorators(spanType),
26
- lists: resolveEnabledListItems(blockType),
27
- block: blockType,
28
- span: spanType,
29
- portableText: portableTextType,
30
- inlineObjects: inlineObjectTypes,
31
- blockObjects: blockObjectTypes,
32
- annotations: spanType.annotations
33
- };
34
- }
35
- function resolveEnabledStyles(blockType) {
36
- const styleField = blockType.fields?.find((btField) => btField.name === "style");
37
- if (!styleField)
38
- throw new Error("A field with name 'style' is not defined in the block type (required).");
39
- const textStyles = styleField.type.options?.list && styleField.type.options.list?.filter((style) => style.value);
40
- if (!textStyles || textStyles.length === 0)
41
- throw new Error("The style fields need at least one style defined. I.e: {title: 'Normal', value: 'normal'}.");
42
- return textStyles;
43
- }
44
- function resolveEnabledDecorators(spanType) {
45
- return spanType.decorators;
46
- }
47
- function resolveEnabledListItems(blockType) {
48
- const listField = blockType.fields?.find((btField) => btField.name === "listItem");
49
- if (!listField)
50
- throw new Error("A field with name 'listItem' is not defined in the block type (required).");
51
- const listItems = listField.type.options?.list && listField.type.options.list.filter((list) => list.value);
52
- if (!listItems)
53
- throw new Error("The list field need at least to be an empty array");
54
- return listItems;
55
- }
56
- function findBlockType(type) {
57
- return type.type ? findBlockType(type.type) : type.name === "block" ? type : null;
58
- }
59
- function defineSchema(definition) {
60
- return definition;
61
- }
62
- function compileSchemaDefinition(definition) {
63
- const blockObjects = definition?.blockObjects?.map((blockObject) => types.defineType({
64
- type: "object",
65
- // Very naive way to work around `SanitySchema.compile` adding default
66
- // fields to objects with the name `image`
67
- name: blockObject.name === "image" ? "tmp-image" : blockObject.name,
68
- title: blockObject.name === "image" && blockObject.title === void 0 ? "Image" : blockObject.title,
69
- fields: []
70
- })) ?? [], inlineObjects = definition?.inlineObjects?.map((inlineObject) => types.defineType({
71
- type: "object",
72
- name: inlineObject.name,
73
- title: inlineObject.title,
74
- fields: []
75
- })) ?? [], portableTextSchema = types.defineField({
76
- type: "array",
77
- name: "portable-text",
78
- of: [...blockObjects.map((blockObject) => ({
79
- type: blockObject.name
80
- })), {
81
- type: "block",
82
- name: "block",
83
- of: inlineObjects.map((inlineObject) => ({
84
- type: inlineObject.name
85
- })),
86
- marks: {
87
- decorators: definition?.decorators?.map((decorator) => ({
88
- title: decorator.title ?? startCase__default.default(decorator.name),
89
- value: decorator.name
90
- })) ?? [],
91
- annotations: definition?.annotations?.map((annotation) => ({
92
- name: annotation.name,
93
- type: "object",
94
- title: annotation.title
95
- })) ?? []
96
- },
97
- lists: definition?.lists?.map((list) => ({
98
- value: list.name,
99
- title: list.title ?? startCase__default.default(list.name)
100
- })) ?? [],
101
- styles: definition?.styles?.map((style) => ({
102
- value: style.name,
103
- title: style.title ?? startCase__default.default(style.name)
104
- })) ?? []
105
- }]
106
- }), schema$1 = schema.Schema.compile({
107
- types: [portableTextSchema, ...blockObjects, ...inlineObjects]
108
- }).get("portable-text"), pteSchema = createEditorSchema(schema$1);
109
- return {
110
- ...pteSchema,
111
- blockObjects: pteSchema.blockObjects.map((blockObject) => blockObject.name === "tmp-image" ? {
112
- ...blockObject,
113
- name: "image",
114
- type: {
115
- ...blockObject.type,
116
- name: "image"
117
- }
118
- } : blockObject)
119
- };
120
- }
121
7
  const rootName = "sanity-pte:";
122
8
  debug__default.default(rootName);
123
9
  function debugWithName(name) {
@@ -231,319 +117,86 @@ function fromSlateValue(value, textBlockType, keyMap = {}) {
231
117
  function isEqualToEmptyEditor(children, schemaTypes) {
232
118
  return children === void 0 || children && Array.isArray(children) && children.length === 0 || children && Array.isArray(children) && children.length === 1 && slate.Element.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 && slate.Text.isText(children[0].children[0]) && children[0].children[0]._type === "span" && !children[0].children[0].marks?.join("") && children[0].children[0].text === "";
233
119
  }
234
- function getFocusBlock({
235
- editor
236
- }) {
237
- if (!editor.selection)
238
- return [void 0, void 0];
239
- try {
240
- return slate.Editor.node(editor, editor.selection.focus.path.slice(0, 1)) ?? [void 0, void 0];
241
- } catch {
242
- return [void 0, void 0];
243
- }
244
- }
245
- function getPointBlock({
246
- editor,
247
- point
248
- }) {
249
- try {
250
- const [block] = slate.Editor.node(editor, point.path.slice(0, 1)) ?? [void 0, void 0];
251
- return block ? [block, point.path] : [void 0, void 0];
252
- } catch {
253
- return [void 0, void 0];
254
- }
255
- }
256
- function getFocusChild({
257
- editor
258
- }) {
259
- const [focusBlock, focusBlockPath] = getFocusBlock({
260
- editor
261
- }), childIndex = editor.selection?.focus.path.at(1);
262
- if (!focusBlock || !focusBlockPath || childIndex === void 0)
263
- return [void 0, void 0];
264
- try {
265
- const focusChild = slate.Node.child(focusBlock, childIndex);
266
- return focusChild ? [focusChild, [...focusBlockPath, childIndex]] : [void 0, void 0];
267
- } catch {
268
- return [void 0, void 0];
269
- }
270
- }
271
- function getPointChild({
272
- editor,
273
- point
274
- }) {
275
- const [block, blockPath] = getPointBlock({
276
- editor,
277
- point
278
- }), childIndex = point.path.at(1);
279
- if (!block || !blockPath || childIndex === void 0)
280
- return [void 0, void 0];
281
- try {
282
- const pointChild = slate.Node.child(block, childIndex);
283
- return pointChild ? [pointChild, [...blockPath, childIndex]] : [void 0, void 0];
284
- } catch {
285
- return [void 0, void 0];
286
- }
287
- }
288
- function getFirstBlock({
289
- editor
290
- }) {
291
- const firstBlockPath = slate.Editor.start(editor, []).path.at(0);
292
- try {
293
- return firstBlockPath !== void 0 ? slate.Editor.node(editor, [firstBlockPath]) ?? [void 0, void 0] : [void 0, void 0];
294
- } catch {
295
- return [void 0, void 0];
296
- }
297
- }
298
- function getLastBlock({
299
- editor
300
- }) {
301
- const lastBlockPath = slate.Editor.end(editor, []).path.at(0);
302
- try {
303
- return lastBlockPath !== void 0 ? slate.Editor.node(editor, [lastBlockPath]) ?? [void 0, void 0] : [void 0, void 0];
304
- } catch {
305
- return [void 0, void 0];
306
- }
307
- }
308
- function getNodeBlock({
309
- editor,
310
- schema: schema2,
311
- node
312
- }) {
313
- if (slate.Editor.isEditor(node))
314
- return;
315
- if (isBlockElement({
316
- editor,
317
- schema: schema2
318
- }, node))
319
- return elementToBlock({
320
- schema: schema2,
321
- element: node
322
- });
323
- const parent = Array.from(slate.Editor.nodes(editor, {
324
- mode: "highest",
325
- at: [],
326
- match: (n) => isBlockElement({
327
- editor,
328
- schema: schema2
329
- }, n) && n.children.some((child) => child._key === node._key)
330
- })).at(0)?.at(0);
331
- return slate.Element.isElement(parent) ? elementToBlock({
332
- schema: schema2,
333
- element: parent
334
- }) : void 0;
335
- }
336
- function elementToBlock({
337
- schema: schema2,
338
- element
339
- }) {
340
- return fromSlateValue([element], schema2.block.name)?.at(0);
341
- }
342
- function isBlockElement({
343
- editor,
344
- schema: schema2
345
- }, node) {
346
- return slate.Element.isElement(node) && !editor.isInline(node) && (schema2.block.name === node._type || schema2.blockObjects.some((blockObject) => blockObject.name === node._type));
347
- }
348
- function isListItemActive({
349
- editor,
350
- listItem
351
- }) {
352
- if (!editor.selection)
353
- return !1;
354
- const selectedBlocks = [...slate.Editor.nodes(editor, {
355
- at: editor.selection,
356
- match: (node) => editor.isTextBlock(node)
357
- })];
358
- return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => editor.isListBlock(node) && node.listItem === listItem) : !1;
359
- }
360
- function isStyleActive({
361
- editor,
362
- style
363
- }) {
364
- if (!editor.selection)
365
- return !1;
366
- const selectedBlocks = [...slate.Editor.nodes(editor, {
367
- at: editor.selection,
368
- match: (node) => editor.isTextBlock(node)
369
- })];
370
- return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => node.style === style) : !1;
371
- }
372
- function slateRangeToSelection({
373
- schema: schema2,
374
- editor,
375
- range
376
- }) {
377
- const [anchorBlock] = getPointBlock({
378
- editor,
379
- point: range.anchor
380
- }), [focusBlock] = getPointBlock({
381
- editor,
382
- point: range.focus
383
- });
384
- if (!anchorBlock || !focusBlock)
385
- return null;
386
- const [anchorChild] = anchorBlock._type === schema2.block.name ? getPointChild({
387
- editor,
388
- point: range.anchor
389
- }) : [void 0, void 0], [focusChild] = focusBlock._type === schema2.block.name ? getPointChild({
390
- editor,
391
- point: range.focus
392
- }) : [void 0, void 0], selection = {
393
- anchor: {
394
- path: [{
395
- _key: anchorBlock._key
396
- }],
397
- offset: range.anchor.offset
398
- },
399
- focus: {
400
- path: [{
401
- _key: focusBlock._key
402
- }],
403
- offset: range.focus.offset
404
- },
405
- backward: slate.Range.isBackward(range)
406
- };
407
- return anchorChild && (selection.anchor.path.push("children"), selection.anchor.path.push({
408
- _key: anchorChild._key
409
- })), focusChild && (selection.focus.path.push("children"), selection.focus.path.push({
410
- _key: focusChild._key
411
- })), selection;
412
- }
413
- function toSlatePath(path, editor) {
414
- if (!editor)
415
- return [];
416
- const [block, blockPath] = Array.from(slate.Editor.nodes(editor, {
417
- at: [],
418
- match: (n) => types.isKeySegment(path[0]) && n._key === path[0]._key
419
- }))[0] || [void 0, void 0];
420
- if (!block || !slate.Element.isElement(block))
421
- return [];
422
- if (editor.isVoid(block))
423
- return [blockPath[0], 0];
424
- const childPath = [path[2]], childIndex = block.children.findIndex((child) => isEqual__default.default([{
425
- _key: child._key
426
- }], childPath));
427
- if (childIndex >= 0 && block.children[childIndex]) {
428
- const child = block.children[childIndex];
429
- return slate.Element.isElement(child) && editor.isVoid(child) ? blockPath.concat(childIndex).concat(0) : blockPath.concat(childIndex);
430
- }
431
- return [blockPath[0], 0];
432
- }
433
- function toSlateRange(selection, editor) {
434
- if (!selection || !editor)
435
- return null;
436
- const anchor = {
437
- path: toSlatePath(selection.anchor.path, editor),
438
- offset: selection.anchor.offset
439
- }, focus = {
440
- path: toSlatePath(selection.focus.path, editor),
441
- offset: selection.focus.offset
442
- };
443
- return focus.path.length === 0 || anchor.path.length === 0 ? null : anchor && focus ? {
444
- anchor,
445
- focus
446
- } : null;
447
- }
448
- function moveRangeByOperation(range, operation) {
449
- const anchor = slate.Point.transform(range.anchor, operation), focus = slate.Point.transform(range.focus, operation);
450
- return anchor === null || focus === null ? null : slate.Point.equals(anchor, range.anchor) && slate.Point.equals(focus, range.focus) ? range : {
451
- anchor,
452
- focus
453
- };
454
- }
455
- const IS_PROCESSING_REMOTE_CHANGES = /* @__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(), EditorActorContext = React.createContext({}), PortableTextEditorContext = React.createContext(null), usePortableTextEditor = () => {
456
- const editor = React.useContext(PortableTextEditorContext);
457
- if (!editor)
458
- throw new Error("The `usePortableTextEditor` hook must be used inside the <PortableTextEditor> component's context.");
459
- return editor;
460
- };
461
- function compileType(rawType) {
462
- return schema.Schema.compile({
463
- name: "blockTypeSchema",
464
- types: [rawType]
465
- }).get(rawType.name);
466
- }
467
- const mutationMachine = xstate.setup({
468
- types: {
469
- context: {},
470
- events: {},
471
- input: {},
472
- emitted: {}
473
- },
474
- actions: {
475
- "emit has pending patches": xstate.emit({
476
- type: "has pending patches"
477
- }),
478
- "emit mutations": xstate.enqueueActions(({
479
- context,
480
- enqueue
481
- }) => {
482
- for (const bulk of context.pendingMutations)
483
- enqueue.emit({
484
- type: "mutation",
485
- patches: bulk.patches,
486
- snapshot: bulk.value
487
- });
488
- }),
489
- "clear pending mutations": xstate.assign({
490
- pendingMutations: []
491
- }),
492
- "defer patch": xstate.assign({
493
- pendingMutations: ({
494
- context,
495
- event
496
- }) => {
497
- if (xstate.assertEvent(event, "patch"), context.pendingMutations.length === 0)
498
- return [{
499
- actionId: event.actionId,
500
- value: event.value,
501
- patches: [event.patch]
502
- }];
503
- const lastBulk = context.pendingMutations.at(-1);
504
- return lastBulk && lastBulk.actionId === event.actionId ? context.pendingMutations.slice(0, -1).concat({
505
- value: event.value,
506
- actionId: lastBulk.actionId,
507
- patches: [...lastBulk.patches, event.patch]
508
- }) : context.pendingMutations.concat({
509
- value: event.value,
510
- actionId: event.actionId,
511
- patches: [event.patch]
512
- });
513
- }
514
- })
515
- },
516
- actors: {
517
- "type listener": xstate.fromCallback(({
518
- input,
519
- sendBack
520
- }) => {
521
- const originalApply = input.slateEditor.apply;
522
- return input.slateEditor.apply = (op) => {
523
- op.type === "insert_text" || op.type === "remove_text" ? sendBack({
524
- type: "typing"
525
- }) : sendBack({
526
- type: "not typing"
527
- }), originalApply(op);
528
- }, () => {
529
- input.slateEditor.apply = originalApply;
530
- };
531
- })
532
- },
533
- guards: {
534
- "is typing": xstate.stateIn({
535
- typing: "typing"
536
- }),
537
- "no pending mutations": ({
538
- context
539
- }) => context.pendingMutations.length === 0,
540
- "slate is normalizing": ({
541
- context
542
- }) => slate.Editor.isNormalizing(context.slateEditor)
543
- },
544
- delays: {
545
- "mutation debounce": process.env.NODE_ENV === "test" ? 250 : 0,
546
- "type debounce": process.env.NODE_ENV === "test" ? 0 : 250
120
+ const IS_PROCESSING_REMOTE_CHANGES = /* @__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(), mutationMachine = xstate.setup({
121
+ types: {
122
+ context: {},
123
+ events: {},
124
+ input: {},
125
+ emitted: {}
126
+ },
127
+ actions: {
128
+ "emit has pending patches": xstate.emit({
129
+ type: "has pending patches"
130
+ }),
131
+ "emit mutations": xstate.enqueueActions(({
132
+ context,
133
+ enqueue
134
+ }) => {
135
+ for (const bulk of context.pendingMutations)
136
+ enqueue.emit({
137
+ type: "mutation",
138
+ patches: bulk.patches,
139
+ snapshot: bulk.value
140
+ });
141
+ }),
142
+ "clear pending mutations": xstate.assign({
143
+ pendingMutations: []
144
+ }),
145
+ "defer patch": xstate.assign({
146
+ pendingMutations: ({
147
+ context,
148
+ event
149
+ }) => {
150
+ if (xstate.assertEvent(event, "patch"), context.pendingMutations.length === 0)
151
+ return [{
152
+ actionId: event.actionId,
153
+ value: event.value,
154
+ patches: [event.patch]
155
+ }];
156
+ const lastBulk = context.pendingMutations.at(-1);
157
+ return lastBulk && lastBulk.actionId === event.actionId ? context.pendingMutations.slice(0, -1).concat({
158
+ value: event.value,
159
+ actionId: lastBulk.actionId,
160
+ patches: [...lastBulk.patches, event.patch]
161
+ }) : context.pendingMutations.concat({
162
+ value: event.value,
163
+ actionId: event.actionId,
164
+ patches: [event.patch]
165
+ });
166
+ }
167
+ })
168
+ },
169
+ actors: {
170
+ "type listener": xstate.fromCallback(({
171
+ input,
172
+ sendBack
173
+ }) => {
174
+ const originalApply = input.slateEditor.apply;
175
+ return input.slateEditor.apply = (op) => {
176
+ op.type === "insert_text" || op.type === "remove_text" ? sendBack({
177
+ type: "typing"
178
+ }) : sendBack({
179
+ type: "not typing"
180
+ }), originalApply(op);
181
+ }, () => {
182
+ input.slateEditor.apply = originalApply;
183
+ };
184
+ })
185
+ },
186
+ guards: {
187
+ "is typing": xstate.stateIn({
188
+ typing: "typing"
189
+ }),
190
+ "no pending mutations": ({
191
+ context
192
+ }) => context.pendingMutations.length === 0,
193
+ "slate is normalizing": ({
194
+ context
195
+ }) => slate.Editor.isNormalizing(context.slateEditor)
196
+ },
197
+ delays: {
198
+ "mutation debounce": process.env.NODE_ENV === "test" ? 250 : 0,
199
+ "type debounce": process.env.NODE_ENV === "test" ? 0 : 250
547
200
  }
548
201
  }).createMachine({
549
202
  id: "mutation",
@@ -2650,17 +2303,26 @@ const converterJson = {
2650
2303
  snapshot,
2651
2304
  event
2652
2305
  }) => {
2653
- const blocks = blockTools.htmlToBlocks(event.data, snapshot.context.schema.portableText, {
2306
+ const parsedBlocks = blockTools.htmlToBlocks(event.data, snapshot.context.schema.portableText, {
2654
2307
  keyGenerator: snapshot.context.keyGenerator,
2655
2308
  unstable_whitespaceOnPasteMode: snapshot.context.schema.block.options.unstable_whitespaceOnPasteMode
2309
+ }).flatMap((block) => {
2310
+ const parsedBlock = parseBlocks.parseBlock({
2311
+ context: snapshot.context,
2312
+ block,
2313
+ options: {
2314
+ refreshKeys: !1
2315
+ }
2316
+ });
2317
+ return parsedBlock ? [parsedBlock] : [];
2656
2318
  });
2657
- return blocks.length === 0 ? {
2319
+ return parsedBlocks.length === 0 ? {
2658
2320
  type: "deserialization.failure",
2659
2321
  mimeType: "text/html",
2660
2322
  reason: "No blocks deserialized"
2661
2323
  } : {
2662
2324
  type: "deserialization.success",
2663
- data: blocks,
2325
+ data: parsedBlocks,
2664
2326
  mimeType: "text/html"
2665
2327
  };
2666
2328
  }
@@ -2692,16 +2354,25 @@ const converterJson = {
2692
2354
  snapshot,
2693
2355
  event
2694
2356
  }) => {
2695
- const textToHtml = `<html><body>${escapeHtml(event.data).split(/\n{2,}/).map((line) => line ? `<p>${line.replace(/(?:\r\n|\r|\n)/g, "<br/>")}</p>` : "<p></p>").join("")}</body></html>`, blocks = blockTools.htmlToBlocks(textToHtml, snapshot.context.schema.portableText, {
2357
+ const textToHtml = `<html><body>${escapeHtml(event.data).split(/\n{2,}/).map((line) => line ? `<p>${line.replace(/(?:\r\n|\r|\n)/g, "<br/>")}</p>` : "<p></p>").join("")}</body></html>`, parsedBlocks = blockTools.htmlToBlocks(textToHtml, snapshot.context.schema.portableText, {
2696
2358
  keyGenerator: snapshot.context.keyGenerator
2359
+ }).flatMap((block) => {
2360
+ const parsedBlock = parseBlocks.parseBlock({
2361
+ context: snapshot.context,
2362
+ block,
2363
+ options: {
2364
+ refreshKeys: !1
2365
+ }
2366
+ });
2367
+ return parsedBlock ? [parsedBlock] : [];
2697
2368
  });
2698
- return blocks.length === 0 ? {
2369
+ return parsedBlocks.length === 0 ? {
2699
2370
  type: "deserialization.failure",
2700
2371
  mimeType: "text/plain",
2701
2372
  reason: "No blocks deserialized"
2702
2373
  } : {
2703
2374
  type: "deserialization.success",
2704
- data: blocks,
2375
+ data: parsedBlocks,
2705
2376
  mimeType: "text/plain"
2706
2377
  };
2707
2378
  }
@@ -2718,7 +2389,66 @@ const converterJson = {
2718
2389
  function escapeHtml(str) {
2719
2390
  return String(str).replace(/[&<>"'`=/]/g, (s) => entityMap[s]);
2720
2391
  }
2721
- const coreConverters = [converterJson, converterPortableText, converterTextHtml, converterTextPlain], debug$c = debugWithName("operationToPatches");
2392
+ const coreConverters = [converterJson, converterPortableText, converterTextHtml, converterTextPlain];
2393
+ function compileType(rawType) {
2394
+ return schema.Schema.compile({
2395
+ name: "blockTypeSchema",
2396
+ types: [rawType]
2397
+ }).get(rawType.name);
2398
+ }
2399
+ function createEditorSchema(portableTextType) {
2400
+ if (!portableTextType)
2401
+ throw new Error("Parameter 'portabletextType' missing (required)");
2402
+ const blockType = portableTextType.of?.find(findBlockType);
2403
+ if (!blockType)
2404
+ throw new Error("Block type is not defined in this schema (required)");
2405
+ const childrenField = blockType.fields?.find((field) => field.name === "children");
2406
+ if (!childrenField)
2407
+ throw new Error("Children field for block type found in schema (required)");
2408
+ const ofType = childrenField.type.of;
2409
+ if (!ofType)
2410
+ throw new Error("Valid types for block children not found in schema (required)");
2411
+ const spanType = ofType.find((memberType) => memberType.name === "span");
2412
+ if (!spanType)
2413
+ throw new Error("Span type not found in schema (required)");
2414
+ const inlineObjectTypes = ofType.filter((memberType) => memberType.name !== "span") || [], blockObjectTypes = portableTextType.of?.filter((field) => field.name !== blockType.name) || [];
2415
+ return {
2416
+ styles: resolveEnabledStyles(blockType),
2417
+ decorators: resolveEnabledDecorators(spanType),
2418
+ lists: resolveEnabledListItems(blockType),
2419
+ block: blockType,
2420
+ span: spanType,
2421
+ portableText: portableTextType,
2422
+ inlineObjects: inlineObjectTypes,
2423
+ blockObjects: blockObjectTypes,
2424
+ annotations: spanType.annotations
2425
+ };
2426
+ }
2427
+ function resolveEnabledStyles(blockType) {
2428
+ const styleField = blockType.fields?.find((btField) => btField.name === "style");
2429
+ if (!styleField)
2430
+ throw new Error("A field with name 'style' is not defined in the block type (required).");
2431
+ const textStyles = styleField.type.options?.list && styleField.type.options.list?.filter((style) => style.value);
2432
+ if (!textStyles || textStyles.length === 0)
2433
+ throw new Error("The style fields need at least one style defined. I.e: {title: 'Normal', value: 'normal'}.");
2434
+ return textStyles;
2435
+ }
2436
+ function resolveEnabledDecorators(spanType) {
2437
+ return spanType.decorators;
2438
+ }
2439
+ function resolveEnabledListItems(blockType) {
2440
+ const listField = blockType.fields?.find((btField) => btField.name === "listItem");
2441
+ if (!listField)
2442
+ throw new Error("A field with name 'listItem' is not defined in the block type (required).");
2443
+ const listItems = listField.type.options?.list && listField.type.options.list.filter((list) => list.value);
2444
+ if (!listItems)
2445
+ throw new Error("The list field need at least to be an empty array");
2446
+ return listItems;
2447
+ }
2448
+ function findBlockType(type) {
2449
+ return type.type ? findBlockType(type.type) : type.name === "block" ? type : null;
2450
+ }
2451
+ const debug$c = debugWithName("operationToPatches");
2722
2452
  function createOperationToPatches(types2) {
2723
2453
  const textBlockName = types2.block.name;
2724
2454
  function insertTextPatch(editor, operation, beforeValue) {
@@ -3481,494 +3211,169 @@ function isDecoratorActive({
3481
3211
  ...slate.Editor.marks(editor) || {}
3482
3212
  }.marks || []).includes(decorator);
3483
3213
  }
3484
- const debug$a = debugWithName("API:editable");
3485
- function createEditableAPI(editor, editorActor) {
3486
- const types2 = editorActor.getSnapshot().context.schema;
3487
- return {
3488
- focus: () => {
3489
- editorActor.send({
3490
- type: "behavior event",
3491
- behaviorEvent: {
3492
- type: "focus"
3493
- },
3494
- editor
3495
- });
3496
- },
3497
- blur: () => {
3498
- editorActor.send({
3499
- type: "behavior event",
3500
- behaviorEvent: {
3501
- type: "blur"
3502
- },
3503
- editor
3504
- });
3505
- },
3506
- toggleMark: (mark) => {
3507
- editorActor.send({
3508
- type: "behavior event",
3509
- behaviorEvent: {
3510
- type: "decorator.toggle",
3511
- decorator: mark
3512
- },
3513
- editor
3514
- });
3515
- },
3516
- toggleList: (listItem) => {
3517
- editorActor.send({
3518
- type: "behavior event",
3519
- behaviorEvent: {
3520
- type: "list item.toggle",
3521
- listItem
3522
- },
3523
- editor
3214
+ const addAnnotationActionImplementation = ({
3215
+ context,
3216
+ action
3217
+ }) => {
3218
+ const editor = action.editor;
3219
+ if (!editor.selection || slate.Range.isCollapsed(editor.selection))
3220
+ return;
3221
+ let paths, spanPath, markDefPath;
3222
+ const markDefPaths = [], selectedBlocks = slate.Editor.nodes(editor, {
3223
+ at: editor.selection,
3224
+ match: (node) => editor.isTextBlock(node),
3225
+ reverse: slate.Range.isBackward(editor.selection)
3226
+ });
3227
+ for (const [block, blockPath] of selectedBlocks) {
3228
+ if (block.children.length === 0 || block.children.length === 1 && block.children[0].text === "")
3229
+ continue;
3230
+ const annotationKey = context.keyGenerator(), markDefs = block.markDefs ?? [];
3231
+ markDefs.find((markDef) => markDef._type === action.annotation.name && markDef._key === annotationKey) === void 0 && (slate.Transforms.setNodes(editor, {
3232
+ markDefs: [...markDefs, {
3233
+ _type: action.annotation.name,
3234
+ _key: annotationKey,
3235
+ ...action.annotation.value
3236
+ }]
3237
+ }, {
3238
+ at: blockPath
3239
+ }), markDefPath = [{
3240
+ _key: block._key
3241
+ }, "markDefs", {
3242
+ _key: annotationKey
3243
+ }], slate.Range.isBackward(editor.selection) ? markDefPaths.unshift(markDefPath) : markDefPaths.push(markDefPath)), slate.Transforms.setNodes(editor, {}, {
3244
+ match: slate.Text.isText,
3245
+ split: !0
3246
+ });
3247
+ const children = slate.Node.children(editor, blockPath);
3248
+ for (const [span, path] of children) {
3249
+ if (!editor.isTextSpan(span) || !slate.Range.includes(editor.selection, path))
3250
+ continue;
3251
+ const marks = span.marks ?? [], existingSameTypeAnnotations = marks.filter((mark) => markDefs.some((markDef) => markDef._key === mark && markDef._type === action.annotation.name));
3252
+ slate.Transforms.setNodes(editor, {
3253
+ marks: [...marks.filter((mark) => !existingSameTypeAnnotations.includes(mark)), annotationKey]
3254
+ }, {
3255
+ at: path
3256
+ }), spanPath = [{
3257
+ _key: block._key
3258
+ }, "children", {
3259
+ _key: span._key
3260
+ }];
3261
+ }
3262
+ }
3263
+ return markDefPath && spanPath && (paths = {
3264
+ markDefPath,
3265
+ markDefPaths,
3266
+ spanPath
3267
+ }), paths;
3268
+ }, removeAnnotationActionImplementation = ({
3269
+ action
3270
+ }) => {
3271
+ const editor = action.editor;
3272
+ if (editor.selection)
3273
+ if (slate.Range.isCollapsed(editor.selection)) {
3274
+ const [block, blockPath] = slate.Editor.node(editor, editor.selection, {
3275
+ depth: 1
3524
3276
  });
3525
- },
3526
- toggleBlockStyle: (style) => {
3527
- editorActor.send({
3528
- type: "behavior event",
3529
- behaviorEvent: {
3530
- type: "style.toggle",
3531
- style
3532
- },
3533
- editor
3277
+ if (!editor.isTextBlock(block))
3278
+ return;
3279
+ const potentialAnnotations = (block.markDefs ?? []).filter((markDef) => markDef._type === action.annotation.name), [selectedChild, selectedChildPath] = slate.Editor.node(editor, editor.selection, {
3280
+ depth: 2
3534
3281
  });
3535
- },
3536
- isMarkActive: (mark) => {
3537
- try {
3538
- return isDecoratorActive({
3539
- editor,
3540
- decorator: mark
3282
+ if (!editor.isTextSpan(selectedChild))
3283
+ return;
3284
+ const annotationToRemove = selectedChild.marks?.find((mark) => potentialAnnotations.some((markDef) => markDef._key === mark));
3285
+ if (!annotationToRemove)
3286
+ return;
3287
+ const previousSpansWithSameAnnotation = [];
3288
+ for (const [child, childPath] of slate.Node.children(editor, blockPath, {
3289
+ reverse: !0
3290
+ }))
3291
+ if (editor.isTextSpan(child) && slate.Path.isBefore(childPath, selectedChildPath))
3292
+ if (child.marks?.includes(annotationToRemove))
3293
+ previousSpansWithSameAnnotation.push([child, childPath]);
3294
+ else
3295
+ break;
3296
+ const nextSpansWithSameAnnotation = [];
3297
+ for (const [child, childPath] of slate.Node.children(editor, blockPath))
3298
+ if (editor.isTextSpan(child) && slate.Path.isAfter(childPath, selectedChildPath))
3299
+ if (child.marks?.includes(annotationToRemove))
3300
+ nextSpansWithSameAnnotation.push([child, childPath]);
3301
+ else
3302
+ break;
3303
+ for (const [child, childPath] of [...previousSpansWithSameAnnotation, [selectedChild, selectedChildPath], ...nextSpansWithSameAnnotation])
3304
+ slate.Transforms.setNodes(editor, {
3305
+ marks: child.marks?.filter((mark) => mark !== annotationToRemove)
3306
+ }, {
3307
+ at: childPath
3541
3308
  });
3542
- } catch (err) {
3543
- return console.warn(err), !1;
3544
- }
3545
- },
3546
- marks: () => ({
3547
- ...slate.Editor.marks(editor) || {}
3548
- }).marks || [],
3549
- undo: () => {
3550
- editorActor.send({
3551
- type: "behavior event",
3552
- behaviorEvent: {
3553
- type: "history.undo"
3554
- },
3555
- editor
3309
+ } else {
3310
+ slate.Transforms.setNodes(editor, {}, {
3311
+ match: (node) => editor.isTextSpan(node),
3312
+ split: !0,
3313
+ hanging: !0
3556
3314
  });
3557
- },
3558
- redo: () => {
3559
- editorActor.send({
3560
- type: "behavior event",
3561
- behaviorEvent: {
3562
- type: "history.redo"
3563
- },
3564
- editor
3315
+ const blocks = slate.Editor.nodes(editor, {
3316
+ at: editor.selection,
3317
+ match: (node) => editor.isTextBlock(node)
3565
3318
  });
3566
- },
3567
- select: (selection) => {
3568
- const slateSelection = toSlateRange(selection, editor);
3569
- slateSelection ? slate.Transforms.select(editor, slateSelection) : slate.Transforms.deselect(editor), editor.onChange();
3570
- },
3571
- focusBlock: () => {
3572
- if (editor.selection) {
3573
- const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
3574
- if (block)
3575
- return fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
3576
- }
3577
- },
3578
- focusChild: () => {
3579
- if (editor.selection) {
3580
- const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
3581
- if (block && editor.isTextBlock(block))
3582
- return fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0].children[editor.selection.focus.path[1]];
3583
- }
3584
- },
3585
- insertChild: (type, value) => {
3586
- if (type.name !== types2.span.name)
3587
- return editorActor.send({
3588
- type: "behavior event",
3589
- behaviorEvent: {
3590
- type: "insert.inline object",
3591
- inlineObject: {
3592
- name: type.name,
3593
- value
3594
- }
3595
- },
3596
- editor
3597
- }), editor.selection ? slateRangeToSelection({
3598
- schema: editorActor.getSnapshot().context.schema,
3599
- editor,
3600
- range: editor.selection
3601
- })?.focus.path ?? [] : [];
3602
- if (!editor.selection)
3603
- throw new Error("The editor has no selection");
3604
- const [focusBlock] = Array.from(slate.Editor.nodes(editor, {
3605
- at: editor.selection.focus.path.slice(0, 1),
3606
- match: (n) => n._type === types2.block.name
3607
- }))[0] || [void 0];
3608
- if (!focusBlock)
3609
- throw new Error("No focused text block");
3610
- if (type.name !== types2.span.name && !types2.inlineObjects.some((t) => t.name === type.name))
3611
- throw new Error("This type cannot be inserted as a child to a text block");
3612
- const child = toSlateValue([{
3613
- _key: editorActor.getSnapshot().context.keyGenerator(),
3614
- _type: types2.block.name,
3615
- children: [{
3616
- _key: editorActor.getSnapshot().context.keyGenerator(),
3617
- _type: type.name,
3618
- ...value || {}
3619
- }]
3620
- }], {
3621
- schemaTypes: editorActor.getSnapshot().context.schema
3622
- })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types2.span.name, focusNode = slate.Node.get(editor, focusChildPath);
3623
- return isSpanNode && focusNode._type !== types2.span.name && (debug$a("Inserting span child next to inline object child, moving selection + 1"), editor.move({
3624
- distance: 1,
3625
- unit: "character"
3626
- })), slate.Transforms.insertNodes(editor, child, {
3627
- select: !0,
3628
- at: editor.selection
3629
- }), editor.onChange(), editor.selection ? slateRangeToSelection({
3630
- schema: editorActor.getSnapshot().context.schema,
3631
- editor,
3632
- range: editor.selection
3633
- })?.focus.path ?? [] : [];
3634
- },
3635
- insertBlock: (type, value) => (editorActor.send({
3636
- type: "behavior event",
3637
- behaviorEvent: {
3638
- type: "insert.block",
3639
- block: {
3640
- _type: type.name,
3641
- ...value || {}
3642
- },
3643
- placement: "auto"
3644
- },
3645
- editor
3646
- }), editor.selection ? slateRangeToSelection({
3647
- schema: editorActor.getSnapshot().context.schema,
3648
- editor,
3649
- range: editor.selection
3650
- })?.focus.path ?? [] : []),
3651
- hasBlockStyle: (style) => {
3652
- try {
3653
- return isStyleActive({
3654
- editor,
3655
- style
3656
- });
3657
- } catch {
3658
- return !1;
3659
- }
3660
- },
3661
- hasListStyle: (listItem) => {
3662
- try {
3663
- return isListItemActive({
3664
- editor,
3665
- listItem
3666
- });
3667
- } catch {
3668
- return !1;
3669
- }
3670
- },
3671
- isVoid: (element) => ![types2.block.name, types2.span.name].includes(element._type),
3672
- findByPath: (path) => {
3673
- const slatePath = toSlateRange({
3674
- focus: {
3675
- path,
3676
- offset: 0
3677
- },
3678
- anchor: {
3679
- path,
3680
- offset: 0
3681
- }
3682
- }, editor);
3683
- if (slatePath) {
3684
- const [block, blockPath] = slate.Editor.node(editor, slatePath.focus.path.slice(0, 1));
3685
- if (block && blockPath && typeof block._key == "string") {
3686
- if (path.length === 1 && slatePath.focus.path.length === 1)
3687
- return [fromSlateValue([block], types2.block.name)[0], [{
3688
- _key: block._key
3689
- }]];
3690
- const ptBlock = fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
3691
- if (editor.isTextBlock(ptBlock)) {
3692
- const ptChild = ptBlock.children[slatePath.focus.path[1]];
3693
- if (ptChild)
3694
- return [ptChild, [{
3695
- _key: block._key
3696
- }, "children", {
3697
- _key: ptChild._key
3698
- }]];
3699
- }
3700
- }
3701
- }
3702
- return [void 0, void 0];
3703
- },
3704
- findDOMNode: (element) => {
3705
- let node;
3706
- try {
3707
- const [item] = Array.from(slate.Editor.nodes(editor, {
3708
- at: [],
3709
- match: (n) => n._key === element._key
3710
- }) || [])[0] || [void 0];
3711
- node = slateReact.ReactEditor.toDOMNode(editor, item);
3712
- } catch {
3713
- }
3714
- return node;
3715
- },
3716
- activeAnnotations: () => {
3717
- if (!editor.selection || editor.selection.focus.path.length < 2)
3718
- return [];
3719
- try {
3720
- const activeAnnotations = [], spans = slate.Editor.nodes(editor, {
3721
- at: editor.selection,
3722
- match: (node) => slate.Text.isText(node) && node.marks !== void 0 && Array.isArray(node.marks) && node.marks.length > 0
3723
- });
3724
- for (const [span, path] of spans) {
3725
- const [block] = slate.Editor.node(editor, path, {
3726
- depth: 1
3727
- });
3728
- editor.isTextBlock(block) && block.markDefs?.forEach((def) => {
3729
- slate.Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
3730
- });
3731
- }
3732
- return activeAnnotations;
3733
- } catch {
3734
- return [];
3735
- }
3736
- },
3737
- isAnnotationActive: (annotationType) => isAnnotationActive({
3738
- editor,
3739
- annotation: {
3740
- name: annotationType
3741
- }
3742
- }),
3743
- addAnnotation: (type, value) => {
3744
- let paths;
3745
- return slate.Editor.withoutNormalizing(editor, () => {
3746
- paths = addAnnotationActionImplementation({
3747
- context: {
3748
- keyGenerator: editorActor.getSnapshot().context.keyGenerator,
3749
- schema: types2
3750
- },
3751
- action: {
3752
- annotation: {
3753
- name: type.name,
3754
- value: value ?? {}
3755
- },
3756
- editor
3757
- }
3758
- });
3759
- }), editor.onChange(), paths;
3760
- },
3761
- delete: (selection, options) => {
3762
- if (selection) {
3763
- const range = toSlateRange(selection, editor);
3764
- if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
3765
- throw new Error("Invalid range");
3766
- if (range) {
3767
- if (!options?.mode || options?.mode === "selected") {
3768
- debug$a("Deleting content in selection"), slate.Transforms.delete(editor, {
3769
- at: range,
3770
- hanging: !0,
3771
- voids: !0
3772
- }), editor.onChange();
3773
- return;
3774
- }
3775
- options?.mode === "blocks" && (debug$a("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
3776
- at: range,
3777
- voids: !0,
3778
- match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && slate.Element.isElement(node)
3779
- })), options?.mode === "children" && (debug$a("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
3780
- at: range,
3781
- voids: !0,
3782
- match: (node) => node._type === types2.span.name || // Text children
3783
- !editor.isTextBlock(node) && slate.Element.isElement(node)
3784
- })), editor.children.length === 0 && (editor.children = [editor.pteCreateTextBlock({
3785
- decorators: []
3786
- })]), editor.onChange();
3787
- }
3788
- }
3789
- },
3790
- removeAnnotation: (type) => {
3791
- editorActor.send({
3792
- type: "behavior event",
3793
- behaviorEvent: {
3794
- type: "annotation.remove",
3795
- annotation: {
3796
- name: type.name
3797
- }
3798
- },
3799
- editor
3800
- });
3801
- },
3802
- getSelection: () => {
3803
- let ptRange = null;
3804
- if (editor.selection) {
3805
- const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
3806
- if (existing)
3807
- return existing;
3808
- ptRange = slateRangeToSelection({
3809
- schema: editorActor.getSnapshot().context.schema,
3810
- editor,
3811
- range: editor.selection
3812
- }), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
3813
- }
3814
- return ptRange;
3815
- },
3816
- getValue: () => fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
3817
- isCollapsedSelection: () => !!editor.selection && slate.Range.isCollapsed(editor.selection),
3818
- isExpandedSelection: () => !!editor.selection && slate.Range.isExpanded(editor.selection),
3819
- insertBreak: () => {
3820
- editor.insertBreak(), editor.onChange();
3821
- },
3822
- getFragment: () => fromSlateValue(editor.getFragment(), types2.block.name),
3823
- isSelectionsOverlapping: (selectionA, selectionB) => {
3824
- const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
3825
- return slate.Range.isRange(rangeA) && slate.Range.isRange(rangeB) && slate.Range.includes(rangeA, rangeB);
3826
- }
3827
- };
3828
- }
3829
- function isAnnotationActive({
3830
- editor,
3831
- annotation
3832
- }) {
3833
- if (!editor.selection || editor.selection.focus.path.length < 2)
3834
- return !1;
3835
- try {
3836
- const spans = [...slate.Editor.nodes(editor, {
3837
- at: editor.selection,
3838
- match: (node) => slate.Text.isText(node)
3839
- })];
3840
- if (spans.length === 0 || spans.some(([span]) => !types.isPortableTextSpan(span) || !span.marks || span.marks?.length === 0)) return !1;
3841
- const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
3842
- const [block] = slate.Editor.node(editor, path, {
3843
- depth: 1
3844
- });
3845
- return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
3846
- }, []);
3847
- return spans.every(([span]) => types.isPortableTextSpan(span) ? span.marks?.map((markKey) => selectionMarkDefs.find((def) => def?._key === markKey)?._type)?.includes(annotation.name) : !1);
3848
- } catch {
3849
- return !1;
3850
- }
3851
- }
3852
- const addAnnotationActionImplementation = ({
3853
- context,
3854
- action
3855
- }) => {
3856
- const editor = action.editor;
3857
- if (!editor.selection || slate.Range.isCollapsed(editor.selection))
3858
- return;
3859
- let paths, spanPath, markDefPath;
3860
- const markDefPaths = [], selectedBlocks = slate.Editor.nodes(editor, {
3861
- at: editor.selection,
3862
- match: (node) => editor.isTextBlock(node),
3863
- reverse: slate.Range.isBackward(editor.selection)
3864
- });
3865
- for (const [block, blockPath] of selectedBlocks) {
3866
- if (block.children.length === 0 || block.children.length === 1 && block.children[0].text === "")
3867
- continue;
3868
- const annotationKey = context.keyGenerator(), markDefs = block.markDefs ?? [];
3869
- markDefs.find((markDef) => markDef._type === action.annotation.name && markDef._key === annotationKey) === void 0 && (slate.Transforms.setNodes(editor, {
3870
- markDefs: [...markDefs, {
3871
- _type: action.annotation.name,
3872
- _key: annotationKey,
3873
- ...action.annotation.value
3874
- }]
3875
- }, {
3876
- at: blockPath
3877
- }), markDefPath = [{
3878
- _key: block._key
3879
- }, "markDefs", {
3880
- _key: annotationKey
3881
- }], slate.Range.isBackward(editor.selection) ? markDefPaths.unshift(markDefPath) : markDefPaths.push(markDefPath)), slate.Transforms.setNodes(editor, {}, {
3882
- match: slate.Text.isText,
3883
- split: !0
3884
- });
3885
- const children = slate.Node.children(editor, blockPath);
3886
- for (const [span, path] of children) {
3887
- if (!editor.isTextSpan(span) || !slate.Range.includes(editor.selection, path))
3888
- continue;
3889
- const marks = span.marks ?? [], existingSameTypeAnnotations = marks.filter((mark) => markDefs.some((markDef) => markDef._key === mark && markDef._type === action.annotation.name));
3890
- slate.Transforms.setNodes(editor, {
3891
- marks: [...marks.filter((mark) => !existingSameTypeAnnotations.includes(mark)), annotationKey]
3892
- }, {
3893
- at: path
3894
- }), spanPath = [{
3895
- _key: block._key
3896
- }, "children", {
3897
- _key: span._key
3898
- }];
3899
- }
3900
- }
3901
- return markDefPath && spanPath && (paths = {
3902
- markDefPath,
3903
- markDefPaths,
3904
- spanPath
3905
- }), paths;
3906
- }, removeAnnotationActionImplementation = ({
3907
- action
3908
- }) => {
3909
- const editor = action.editor;
3910
- if (debug$a("Removing annotation", action.annotation.name), !!editor.selection)
3911
- if (slate.Range.isCollapsed(editor.selection)) {
3912
- const [block, blockPath] = slate.Editor.node(editor, editor.selection, {
3913
- depth: 1
3914
- });
3915
- if (!editor.isTextBlock(block))
3916
- return;
3917
- const potentialAnnotations = (block.markDefs ?? []).filter((markDef) => markDef._type === action.annotation.name), [selectedChild, selectedChildPath] = slate.Editor.node(editor, editor.selection, {
3918
- depth: 2
3919
- });
3920
- if (!editor.isTextSpan(selectedChild))
3921
- return;
3922
- const annotationToRemove = selectedChild.marks?.find((mark) => potentialAnnotations.some((markDef) => markDef._key === mark));
3923
- if (!annotationToRemove)
3924
- return;
3925
- const previousSpansWithSameAnnotation = [];
3926
- for (const [child, childPath] of slate.Node.children(editor, blockPath, {
3927
- reverse: !0
3928
- }))
3929
- if (editor.isTextSpan(child) && slate.Path.isBefore(childPath, selectedChildPath))
3930
- if (child.marks?.includes(annotationToRemove))
3931
- previousSpansWithSameAnnotation.push([child, childPath]);
3932
- else
3933
- break;
3934
- const nextSpansWithSameAnnotation = [];
3935
- for (const [child, childPath] of slate.Node.children(editor, blockPath))
3936
- if (editor.isTextSpan(child) && slate.Path.isAfter(childPath, selectedChildPath))
3937
- if (child.marks?.includes(annotationToRemove))
3938
- nextSpansWithSameAnnotation.push([child, childPath]);
3939
- else
3940
- break;
3941
- for (const [child, childPath] of [...previousSpansWithSameAnnotation, [selectedChild, selectedChildPath], ...nextSpansWithSameAnnotation])
3942
- slate.Transforms.setNodes(editor, {
3943
- marks: child.marks?.filter((mark) => mark !== annotationToRemove)
3944
- }, {
3945
- at: childPath
3946
- });
3947
- } else {
3948
- slate.Transforms.setNodes(editor, {}, {
3949
- match: (node) => editor.isTextSpan(node),
3950
- split: !0,
3951
- hanging: !0
3952
- });
3953
- const blocks = slate.Editor.nodes(editor, {
3954
- at: editor.selection,
3955
- match: (node) => editor.isTextBlock(node)
3956
- });
3957
- for (const [block, blockPath] of blocks) {
3958
- const children = slate.Node.children(editor, blockPath);
3959
- for (const [child, childPath] of children) {
3960
- if (!editor.isTextSpan(child) || !slate.Range.includes(editor.selection, childPath))
3961
- continue;
3962
- const markDefs = block.markDefs ?? [], marks = child.marks ?? [], marksWithoutAnnotation = marks.filter((mark) => markDefs.find((markDef2) => markDef2._key === mark)?._type !== action.annotation.name);
3963
- marksWithoutAnnotation.length !== marks.length && slate.Transforms.setNodes(editor, {
3964
- marks: marksWithoutAnnotation
3965
- }, {
3966
- at: childPath
3967
- });
3968
- }
3319
+ for (const [block, blockPath] of blocks) {
3320
+ const children = slate.Node.children(editor, blockPath);
3321
+ for (const [child, childPath] of children) {
3322
+ if (!editor.isTextSpan(child) || !slate.Range.includes(editor.selection, childPath))
3323
+ continue;
3324
+ const markDefs = block.markDefs ?? [], marks = child.marks ?? [], marksWithoutAnnotation = marks.filter((mark) => markDefs.find((markDef2) => markDef2._key === mark)?._type !== action.annotation.name);
3325
+ marksWithoutAnnotation.length !== marks.length && slate.Transforms.setNodes(editor, {
3326
+ marks: marksWithoutAnnotation
3327
+ }, {
3328
+ at: childPath
3329
+ });
3330
+ }
3969
3331
  }
3970
3332
  }
3971
- }, blockSetBehaviorActionImplementation = ({
3333
+ };
3334
+ function toSlatePath(path, editor) {
3335
+ if (!editor)
3336
+ return [];
3337
+ const [block, blockPath] = Array.from(slate.Editor.nodes(editor, {
3338
+ at: [],
3339
+ match: (n) => types.isKeySegment(path[0]) && n._key === path[0]._key
3340
+ }))[0] || [void 0, void 0];
3341
+ if (!block || !slate.Element.isElement(block))
3342
+ return [];
3343
+ if (editor.isVoid(block))
3344
+ return [blockPath[0], 0];
3345
+ const childPath = [path[2]], childIndex = block.children.findIndex((child) => isEqual__default.default([{
3346
+ _key: child._key
3347
+ }], childPath));
3348
+ if (childIndex >= 0 && block.children[childIndex]) {
3349
+ const child = block.children[childIndex];
3350
+ return slate.Element.isElement(child) && editor.isVoid(child) ? blockPath.concat(childIndex).concat(0) : blockPath.concat(childIndex);
3351
+ }
3352
+ return [blockPath[0], 0];
3353
+ }
3354
+ function toSlateRange(selection, editor) {
3355
+ if (!selection || !editor)
3356
+ return null;
3357
+ const anchor = {
3358
+ path: toSlatePath(selection.anchor.path, editor),
3359
+ offset: selection.anchor.offset
3360
+ }, focus = {
3361
+ path: toSlatePath(selection.focus.path, editor),
3362
+ offset: selection.focus.offset
3363
+ };
3364
+ return focus.path.length === 0 || anchor.path.length === 0 ? null : anchor && focus ? {
3365
+ anchor,
3366
+ focus
3367
+ } : null;
3368
+ }
3369
+ function moveRangeByOperation(range, operation) {
3370
+ const anchor = slate.Point.transform(range.anchor, operation), focus = slate.Point.transform(range.focus, operation);
3371
+ return anchor === null || focus === null ? null : slate.Point.equals(anchor, range.anchor) && slate.Point.equals(focus, range.focus) ? range : {
3372
+ anchor,
3373
+ focus
3374
+ };
3375
+ }
3376
+ const blockSetBehaviorActionImplementation = ({
3972
3377
  context,
3973
3378
  action
3974
3379
  }) => {
@@ -4082,7 +3487,187 @@ const addAnnotationActionImplementation = ({
4082
3487
  action
4083
3488
  }) => {
4084
3489
  slateReact.ReactEditor.blur(action.editor);
4085
- }, decoratorAddActionImplementation = ({
3490
+ };
3491
+ function getFocusBlock({
3492
+ editor
3493
+ }) {
3494
+ if (!editor.selection)
3495
+ return [void 0, void 0];
3496
+ try {
3497
+ return slate.Editor.node(editor, editor.selection.focus.path.slice(0, 1)) ?? [void 0, void 0];
3498
+ } catch {
3499
+ return [void 0, void 0];
3500
+ }
3501
+ }
3502
+ function getPointBlock({
3503
+ editor,
3504
+ point
3505
+ }) {
3506
+ try {
3507
+ const [block] = slate.Editor.node(editor, point.path.slice(0, 1)) ?? [void 0, void 0];
3508
+ return block ? [block, point.path] : [void 0, void 0];
3509
+ } catch {
3510
+ return [void 0, void 0];
3511
+ }
3512
+ }
3513
+ function getFocusChild({
3514
+ editor
3515
+ }) {
3516
+ const [focusBlock, focusBlockPath] = getFocusBlock({
3517
+ editor
3518
+ }), childIndex = editor.selection?.focus.path.at(1);
3519
+ if (!focusBlock || !focusBlockPath || childIndex === void 0)
3520
+ return [void 0, void 0];
3521
+ try {
3522
+ const focusChild = slate.Node.child(focusBlock, childIndex);
3523
+ return focusChild ? [focusChild, [...focusBlockPath, childIndex]] : [void 0, void 0];
3524
+ } catch {
3525
+ return [void 0, void 0];
3526
+ }
3527
+ }
3528
+ function getPointChild({
3529
+ editor,
3530
+ point
3531
+ }) {
3532
+ const [block, blockPath] = getPointBlock({
3533
+ editor,
3534
+ point
3535
+ }), childIndex = point.path.at(1);
3536
+ if (!block || !blockPath || childIndex === void 0)
3537
+ return [void 0, void 0];
3538
+ try {
3539
+ const pointChild = slate.Node.child(block, childIndex);
3540
+ return pointChild ? [pointChild, [...blockPath, childIndex]] : [void 0, void 0];
3541
+ } catch {
3542
+ return [void 0, void 0];
3543
+ }
3544
+ }
3545
+ function getFirstBlock({
3546
+ editor
3547
+ }) {
3548
+ const firstBlockPath = slate.Editor.start(editor, []).path.at(0);
3549
+ try {
3550
+ return firstBlockPath !== void 0 ? slate.Editor.node(editor, [firstBlockPath]) ?? [void 0, void 0] : [void 0, void 0];
3551
+ } catch {
3552
+ return [void 0, void 0];
3553
+ }
3554
+ }
3555
+ function getLastBlock({
3556
+ editor
3557
+ }) {
3558
+ const lastBlockPath = slate.Editor.end(editor, []).path.at(0);
3559
+ try {
3560
+ return lastBlockPath !== void 0 ? slate.Editor.node(editor, [lastBlockPath]) ?? [void 0, void 0] : [void 0, void 0];
3561
+ } catch {
3562
+ return [void 0, void 0];
3563
+ }
3564
+ }
3565
+ function getNodeBlock({
3566
+ editor,
3567
+ schema: schema2,
3568
+ node
3569
+ }) {
3570
+ if (slate.Editor.isEditor(node))
3571
+ return;
3572
+ if (isBlockElement({
3573
+ editor,
3574
+ schema: schema2
3575
+ }, node))
3576
+ return elementToBlock({
3577
+ schema: schema2,
3578
+ element: node
3579
+ });
3580
+ const parent = Array.from(slate.Editor.nodes(editor, {
3581
+ mode: "highest",
3582
+ at: [],
3583
+ match: (n) => isBlockElement({
3584
+ editor,
3585
+ schema: schema2
3586
+ }, n) && n.children.some((child) => child._key === node._key)
3587
+ })).at(0)?.at(0);
3588
+ return slate.Element.isElement(parent) ? elementToBlock({
3589
+ schema: schema2,
3590
+ element: parent
3591
+ }) : void 0;
3592
+ }
3593
+ function elementToBlock({
3594
+ schema: schema2,
3595
+ element
3596
+ }) {
3597
+ return fromSlateValue([element], schema2.block.name)?.at(0);
3598
+ }
3599
+ function isBlockElement({
3600
+ editor,
3601
+ schema: schema2
3602
+ }, node) {
3603
+ return slate.Element.isElement(node) && !editor.isInline(node) && (schema2.block.name === node._type || schema2.blockObjects.some((blockObject) => blockObject.name === node._type));
3604
+ }
3605
+ function isListItemActive({
3606
+ editor,
3607
+ listItem
3608
+ }) {
3609
+ if (!editor.selection)
3610
+ return !1;
3611
+ const selectedBlocks = [...slate.Editor.nodes(editor, {
3612
+ at: editor.selection,
3613
+ match: (node) => editor.isTextBlock(node)
3614
+ })];
3615
+ return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => editor.isListBlock(node) && node.listItem === listItem) : !1;
3616
+ }
3617
+ function isStyleActive({
3618
+ editor,
3619
+ style
3620
+ }) {
3621
+ if (!editor.selection)
3622
+ return !1;
3623
+ const selectedBlocks = [...slate.Editor.nodes(editor, {
3624
+ at: editor.selection,
3625
+ match: (node) => editor.isTextBlock(node)
3626
+ })];
3627
+ return selectedBlocks.length > 0 ? selectedBlocks.every(([node]) => node.style === style) : !1;
3628
+ }
3629
+ function slateRangeToSelection({
3630
+ schema: schema2,
3631
+ editor,
3632
+ range
3633
+ }) {
3634
+ const [anchorBlock] = getPointBlock({
3635
+ editor,
3636
+ point: range.anchor
3637
+ }), [focusBlock] = getPointBlock({
3638
+ editor,
3639
+ point: range.focus
3640
+ });
3641
+ if (!anchorBlock || !focusBlock)
3642
+ return null;
3643
+ const [anchorChild] = anchorBlock._type === schema2.block.name ? getPointChild({
3644
+ editor,
3645
+ point: range.anchor
3646
+ }) : [void 0, void 0], [focusChild] = focusBlock._type === schema2.block.name ? getPointChild({
3647
+ editor,
3648
+ point: range.focus
3649
+ }) : [void 0, void 0], selection = {
3650
+ anchor: {
3651
+ path: [{
3652
+ _key: anchorBlock._key
3653
+ }],
3654
+ offset: range.anchor.offset
3655
+ },
3656
+ focus: {
3657
+ path: [{
3658
+ _key: focusBlock._key
3659
+ }],
3660
+ offset: range.focus.offset
3661
+ },
3662
+ backward: slate.Range.isBackward(range)
3663
+ };
3664
+ return anchorChild && (selection.anchor.path.push("children"), selection.anchor.path.push({
3665
+ _key: anchorChild._key
3666
+ })), focusChild && (selection.focus.path.push("children"), selection.focus.path.push({
3667
+ _key: focusChild._key
3668
+ })), selection;
3669
+ }
3670
+ const decoratorAddActionImplementation = ({
4086
3671
  context,
4087
3672
  action
4088
3673
  }) => {
@@ -4497,7 +4082,7 @@ const insertTextActionImplementation = ({
4497
4082
  }) => {
4498
4083
  const newSelection = toSlateRange(action.selection, action.editor);
4499
4084
  newSelection ? slate.Transforms.select(action.editor, newSelection) : slate.Transforms.deselect(action.editor);
4500
- }, debug$9 = debugWithName("behaviors:action"), behaviorActionImplementations = {
4085
+ }, debug$a = debugWithName("behaviors:action"), behaviorActionImplementations = {
4501
4086
  "annotation.add": addAnnotationActionImplementation,
4502
4087
  "annotation.remove": removeAnnotationActionImplementation,
4503
4088
  "block.set": blockSetBehaviorActionImplementation,
@@ -4528,7 +4113,7 @@ function performAction({
4528
4113
  context,
4529
4114
  action
4530
4115
  }) {
4531
- switch (debug$9(JSON.stringify(omit__default.default(action, ["editor"]), null, 2)), action.type) {
4116
+ switch (debug$a(JSON.stringify(omit__default.default(action, ["editor"]), null, 2)), action.type) {
4532
4117
  case "annotation.add": {
4533
4118
  behaviorActionImplementations["annotation.add"]({
4534
4119
  context,
@@ -4963,13 +4548,13 @@ function createWithObjectKeys(editorActor, schemaTypes) {
4963
4548
  }, editor;
4964
4549
  };
4965
4550
  }
4966
- const debug$8 = debugWithName("applyPatches"), debugVerbose = debug$8.enabled && !0;
4551
+ const debug$9 = debugWithName("applyPatches"), debugVerbose = debug$9.enabled && !0;
4967
4552
  function createApplyPatch(schemaTypes) {
4968
4553
  return (editor, patch) => {
4969
4554
  let changed = !1;
4970
- debugVerbose && (debug$8(`
4555
+ debugVerbose && (debug$9(`
4971
4556
 
4972
- NEW PATCH =============================================================`), debug$8(JSON.stringify(patch, null, 2)));
4557
+ NEW PATCH =============================================================`), debug$9(JSON.stringify(patch, null, 2)));
4973
4558
  try {
4974
4559
  switch (patch.type) {
4975
4560
  case "insert":
@@ -4985,7 +4570,7 @@ NEW PATCH =============================================================`), debug
4985
4570
  changed = diffMatchPatch(editor, patch);
4986
4571
  break;
4987
4572
  default:
4988
- debug$8("Unhandled patch", patch.type);
4573
+ debug$9("Unhandled patch", patch.type);
4989
4574
  }
4990
4575
  } catch (err) {
4991
4576
  console.error(err);
@@ -5000,9 +4585,9 @@ function diffMatchPatch(editor, patch) {
5000
4585
  childPath
5001
4586
  } = findBlockAndChildFromPath(editor, patch.path);
5002
4587
  if (!block)
5003
- return debug$8("Block not found"), !1;
4588
+ return debug$9("Block not found"), !1;
5004
4589
  if (!child || !childPath)
5005
- return debug$8("Child not found"), !1;
4590
+ return debug$9("Child not found"), !1;
5006
4591
  if (!(block && editor.isTextBlock(block) && patch.path.length === 4 && patch.path[1] === "children" && patch.path[3] === "text") || !slate.Text.isText(child))
5007
4592
  return !1;
5008
4593
  const patches2 = parse(patch.value), [newValue] = apply(patches2, child.text, {
@@ -5032,9 +4617,9 @@ function insertPatch(editor, patch, schemaTypes) {
5032
4617
  childPath: targetChildPath
5033
4618
  } = findBlockAndChildFromPath(editor, patch.path);
5034
4619
  if (!targetBlock || !targetBlockPath)
5035
- return debug$8("Block not found"), !1;
4620
+ return debug$9("Block not found"), !1;
5036
4621
  if (patch.path.length > 1 && patch.path[1] !== "children")
5037
- return debug$8("Ignoring patch targeting void value"), !1;
4622
+ return debug$9("Ignoring patch targeting void value"), !1;
5038
4623
  if (patch.path.length === 1) {
5039
4624
  const {
5040
4625
  items: items2,
@@ -5042,7 +4627,7 @@ function insertPatch(editor, patch, schemaTypes) {
5042
4627
  } = patch, blocksToInsert = toSlateValue(items2, {
5043
4628
  schemaTypes
5044
4629
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetBlockIndex = targetBlockPath[0], normalizedIdx2 = position2 === "after" ? targetBlockIndex + 1 : targetBlockIndex;
5045
- return debug$8(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
4630
+ return debug$9(`Inserting blocks at path [${normalizedIdx2}]`), debugState(editor, "before"), slate.Transforms.insertNodes(editor, blocksToInsert, {
5046
4631
  at: [normalizedIdx2]
5047
4632
  }), debugState(editor, "after"), !0;
5048
4633
  }
@@ -5051,14 +4636,14 @@ function insertPatch(editor, patch, schemaTypes) {
5051
4636
  position
5052
4637
  } = patch;
5053
4638
  if (!targetChild || !targetChildPath)
5054
- return debug$8("Child not found"), !1;
4639
+ return debug$9("Child not found"), !1;
5055
4640
  const childrenToInsert = targetBlock && toSlateValue([{
5056
4641
  ...targetBlock,
5057
4642
  children: items
5058
4643
  }], {
5059
4644
  schemaTypes
5060
4645
  }, KEY_TO_SLATE_ELEMENT.get(editor)), targetChildIndex = targetChildPath[1], normalizedIdx = position === "after" ? targetChildIndex + 1 : targetChildIndex, childInsertPath = [targetChildPath[0], normalizedIdx];
5061
- return debug$8(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
4646
+ return debug$9(`Inserting children at path ${childInsertPath}`), debugState(editor, "before"), childrenToInsert && slate.Element.isElement(childrenToInsert[0]) && slate.Transforms.insertNodes(editor, childrenToInsert[0].children, {
5062
4647
  at: childInsertPath
5063
4648
  }), debugState(editor, "after"), !0;
5064
4649
  }
@@ -5072,14 +4657,14 @@ function setPatch(editor, patch) {
5072
4657
  childPath
5073
4658
  } = findBlockAndChildFromPath(editor, patch.path);
5074
4659
  if (!block)
5075
- return debug$8("Block not found"), !1;
4660
+ return debug$9("Block not found"), !1;
5076
4661
  const isTextBlock = editor.isTextBlock(block);
5077
4662
  if (isTextBlock && patch.path.length > 1 && patch.path[1] !== "children")
5078
- return debug$8("Ignoring setting void value"), !1;
4663
+ return debug$9("Ignoring setting void value"), !1;
5079
4664
  if (debugState(editor, "before"), isTextBlock && child && childPath) {
5080
4665
  if (slate.Text.isText(value) && slate.Text.isText(child)) {
5081
4666
  const newText = child.text;
5082
- value.text !== newText && (debug$8("Setting text property"), editor.apply({
4667
+ value.text !== newText && (debug$9("Setting text property"), editor.apply({
5083
4668
  type: "remove_text",
5084
4669
  path: childPath,
5085
4670
  offset: 0,
@@ -5091,7 +4676,7 @@ function setPatch(editor, patch) {
5091
4676
  text: value.text
5092
4677
  }), editor.onChange());
5093
4678
  } else
5094
- debug$8("Setting non-text property"), editor.apply({
4679
+ debug$9("Setting non-text property"), editor.apply({
5095
4680
  type: "set_node",
5096
4681
  path: childPath,
5097
4682
  properties: {},
@@ -5099,7 +4684,7 @@ function setPatch(editor, patch) {
5099
4684
  });
5100
4685
  return !0;
5101
4686
  } else if (slate.Element.isElement(block) && patch.path.length === 1 && blockPath) {
5102
- debug$8("Setting block property");
4687
+ debug$9("Setting block property");
5103
4688
  const {
5104
4689
  children,
5105
4690
  ...nextRest
@@ -5116,7 +4701,7 @@ function setPatch(editor, patch) {
5116
4701
  ...prevRest
5117
4702
  },
5118
4703
  newProperties: nextRest
5119
- }), debug$8("Setting children"), block.children.forEach((c, cIndex) => {
4704
+ }), debug$9("Setting children"), block.children.forEach((c, cIndex) => {
5120
4705
  editor.apply({
5121
4706
  type: "remove_node",
5122
4707
  path: blockPath.concat(block.children.length - 1 - cIndex),
@@ -5147,7 +4732,7 @@ function setPatch(editor, patch) {
5147
4732
  }
5148
4733
  function unsetPatch(editor, patch) {
5149
4734
  if (patch.path.length === 0) {
5150
- debug$8("Removing everything"), debugState(editor, "before");
4735
+ debug$9("Removing everything"), debugState(editor, "before");
5151
4736
  const previousSelection = editor.selection;
5152
4737
  return slate.Transforms.deselect(editor), editor.children.forEach((_child, i) => {
5153
4738
  slate.Transforms.removeNodes(editor, {
@@ -5174,13 +4759,13 @@ function unsetPatch(editor, patch) {
5174
4759
  } = findBlockAndChildFromPath(editor, patch.path);
5175
4760
  if (patch.path.length === 1) {
5176
4761
  if (!block || !blockPath)
5177
- return debug$8("Block not found"), !1;
4762
+ return debug$9("Block not found"), !1;
5178
4763
  const blockIndex = blockPath[0];
5179
- return debug$8(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
4764
+ return debug$9(`Removing block at path [${blockIndex}]`), debugState(editor, "before"), slate.Transforms.removeNodes(editor, {
5180
4765
  at: [blockIndex]
5181
4766
  }), debugState(editor, "after"), !0;
5182
4767
  }
5183
- return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$8("Child not found"), !1) : (debug$8(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose && debug$8(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
4768
+ return editor.isTextBlock(block) && patch.path[1] === "children" && patch.path.length === 3 ? !child || !childPath ? (debug$9("Child not found"), !1) : (debug$9(`Unsetting child at path ${JSON.stringify(childPath)}`), debugState(editor, "before"), debugVerbose && debug$9(`Removing child at path ${JSON.stringify(childPath)}`), slate.Transforms.removeNodes(editor, {
5184
4769
  at: childPath
5185
4770
  }), debugState(editor, "after"), !0) : !1;
5186
4771
  }
@@ -5188,7 +4773,7 @@ function isKeyedSegment(segment) {
5188
4773
  return typeof segment == "object" && "_key" in segment;
5189
4774
  }
5190
4775
  function debugState(editor, stateName) {
5191
- debugVerbose && (debug$8(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$8(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
4776
+ debugVerbose && (debug$9(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2)), debug$9(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2)));
5192
4777
  }
5193
4778
  function findBlockFromPath(editor, path) {
5194
4779
  let blockIndex = -1;
@@ -5230,7 +4815,7 @@ function findBlockAndChildFromPath(editor, path) {
5230
4815
  childPath: void 0
5231
4816
  };
5232
4817
  }
5233
- const debug$7 = debugWithName("plugin:withPatches");
4818
+ const debug$8 = debugWithName("plugin:withPatches");
5234
4819
  function createWithPatches({
5235
4820
  editorActor,
5236
4821
  patchFunctions,
@@ -5256,7 +4841,7 @@ function createWithPatches({
5256
4841
  withoutPatching(editor, () => {
5257
4842
  withoutSaving(editor, () => {
5258
4843
  patches2.forEach((patch) => {
5259
- debug$7.enabled && debug$7(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
4844
+ debug$8.enabled && debug$8(`Handling remote patch ${JSON.stringify(patch)}`), changed = applyPatch(editor, patch);
5260
4845
  });
5261
4846
  });
5262
4847
  });
@@ -5269,10 +4854,10 @@ function createWithPatches({
5269
4854
  remotePatches.length !== 0 && (bufferedPatches = bufferedPatches.concat(remotePatches), handleBufferedRemotePatches());
5270
4855
  };
5271
4856
  return subscriptions.push(() => {
5272
- debug$7("Subscribing to remote patches");
4857
+ debug$8("Subscribing to remote patches");
5273
4858
  const sub = editorActor.on("patches", handlePatches);
5274
4859
  return () => {
5275
- debug$7("Unsubscribing to remote patches"), sub.unsubscribe();
4860
+ debug$8("Unsubscribing to remote patches"), sub.unsubscribe();
5276
4861
  };
5277
4862
  }), editor.apply = (operation) => {
5278
4863
  let patches$1 = [];
@@ -5326,7 +4911,7 @@ function createWithPatches({
5326
4911
  }, editor;
5327
4912
  };
5328
4913
  }
5329
- const debug$6 = debugWithName("plugin:withPlaceholderBlock");
4914
+ const debug$7 = debugWithName("plugin:withPlaceholderBlock");
5330
4915
  function createWithPlaceholderBlock(editorActor) {
5331
4916
  return function(editor) {
5332
4917
  const {
@@ -5351,7 +4936,7 @@ function createWithPlaceholderBlock(editorActor) {
5351
4936
  const node = op.node;
5352
4937
  if (op.path[0] === 0 && slate.Editor.isVoid(editor, node)) {
5353
4938
  const nextPath = slate.Path.next(op.path);
5354
- editor.children[nextPath[0]] || (debug$6("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
4939
+ editor.children[nextPath[0]] || (debug$7("Adding placeholder block"), slate.Editor.insertNode(editor, editor.pteCreateTextBlock({
5355
4940
  decorators: []
5356
4941
  })));
5357
4942
  }
@@ -5360,7 +4945,7 @@ function createWithPlaceholderBlock(editorActor) {
5360
4945
  }, editor;
5361
4946
  };
5362
4947
  }
5363
- const debug$5 = debugWithName("plugin:withPortableTextBlockStyle");
4948
+ const debug$6 = debugWithName("plugin:withPortableTextBlockStyle");
5364
4949
  function createWithPortableTextBlockStyle(editorActor, types2) {
5365
4950
  const defaultStyle = types2.styles[0].value;
5366
4951
  return function(editor) {
@@ -5373,7 +4958,7 @@ function createWithPortableTextBlockStyle(editorActor, types2) {
5373
4958
  if (op.type === "split_node" && op.path.length === 1 && editor.isTextBlock(op.properties) && op.properties.style !== defaultStyle && op.path[0] === path[0] && !slate.Path.equals(path, op.path)) {
5374
4959
  const [child] = slate.Editor.node(editor, [op.path[0] + 1, 0]);
5375
4960
  if (slate.Text.isText(child) && child.text === "") {
5376
- debug$5(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
4961
+ debug$6(`Normalizing split node to ${defaultStyle} style`, op), editorActor.send({
5377
4962
  type: "normalizing"
5378
4963
  }), slate.Transforms.setNodes(editor, {
5379
4964
  style: defaultStyle
@@ -5424,7 +5009,7 @@ function createWithPortableTextSelections(editorActor) {
5424
5009
  }, editor;
5425
5010
  };
5426
5011
  }
5427
- const debug$4 = debugWithName("plugin:withSchemaTypes");
5012
+ const debug$5 = debugWithName("plugin:withSchemaTypes");
5428
5013
  function createWithSchemaTypes({
5429
5014
  editorActor,
5430
5015
  schemaTypes
@@ -5437,7 +5022,7 @@ function createWithSchemaTypes({
5437
5022
  return editor.normalizeNode = (entry) => {
5438
5023
  const [node, path] = entry;
5439
5024
  if (node._type === void 0 && path.length === 2) {
5440
- debug$4("Setting span type on text node without a type");
5025
+ debug$5("Setting span type on text node without a type");
5441
5026
  const span = node, key = span._key || editorActor.getSnapshot().context.keyGenerator();
5442
5027
  editorActor.send({
5443
5028
  type: "normalizing"
@@ -5453,7 +5038,7 @@ function createWithSchemaTypes({
5453
5038
  return;
5454
5039
  }
5455
5040
  if (node._key === void 0 && (path.length === 1 || path.length === 2)) {
5456
- debug$4("Setting missing key on child node without a key");
5041
+ debug$5("Setting missing key on child node without a key");
5457
5042
  const key = editorActor.getSnapshot().context.keyGenerator();
5458
5043
  editorActor.send({
5459
5044
  type: "normalizing"
@@ -5519,12 +5104,12 @@ const withPlugins = (editor, options) => {
5519
5104
  schemaTypes
5520
5105
  }), withPortableTextSelections = createWithPortableTextSelections(editorActor);
5521
5106
  return createWithEventListeners(editorActor)(withSchemaTypes(withObjectKeys(withPortableTextMarkModel(withPortableTextBlockStyle(withPlaceholderBlock(withUtils(withMaxBlocks(withUndoRedo(withPatches(withPortableTextSelections(e)))))))))));
5522
- }, debug$3 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
5107
+ }, debug$4 = debugWithName("component:PortableTextEditor:SlateContainer"), slateEditors = /* @__PURE__ */ new WeakMap();
5523
5108
  function createSlateEditor(config) {
5524
5109
  const existingSlateEditor = slateEditors.get(config.editorActor);
5525
5110
  if (existingSlateEditor)
5526
- return debug$3("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
5527
- debug$3("Creating new Slate editor instance", config.editorActor.id);
5111
+ return debug$4("Reusing existing Slate editor instance", config.editorActor.id), existingSlateEditor;
5112
+ debug$4("Creating new Slate editor instance", config.editorActor.id);
5528
5113
  const unsubscriptions = [], subscriptions = [], instance = withPlugins(slateReact.withReact(slate.createEditor()), {
5529
5114
  editorActor: config.editorActor,
5530
5115
  subscriptions
@@ -5538,7 +5123,91 @@ function createSlateEditor(config) {
5538
5123
  instance,
5539
5124
  initialValue
5540
5125
  };
5541
- return slateEditors.set(config.editorActor, slateEditor), slateEditor;
5126
+ return slateEditors.set(config.editorActor, slateEditor), slateEditor;
5127
+ }
5128
+ function defineSchema(definition) {
5129
+ return definition;
5130
+ }
5131
+ const temporaryImageName = `tmp-${defaultKeyGenerator()}-image`, temporaryUrlName = `tmp-${defaultKeyGenerator()}-url`, temporaryObjectNames = {
5132
+ image: temporaryImageName,
5133
+ url: temporaryUrlName
5134
+ }, objectNames = {
5135
+ [temporaryImageName]: "image",
5136
+ [temporaryUrlName]: "url"
5137
+ }, defaultObjectTitles = {
5138
+ image: "Image",
5139
+ url: "URL"
5140
+ };
5141
+ function compileSchemaDefinition(definition) {
5142
+ const blockObjects = definition?.blockObjects?.map((blockObject) => types.defineType({
5143
+ type: "object",
5144
+ // Very naive way to work around `SanitySchema.compile` adding default
5145
+ // fields to objects with certain names.
5146
+ name: temporaryObjectNames[blockObject.name] ?? blockObject.name,
5147
+ title: blockObject.title === void 0 ? (
5148
+ // This avoids the default title which is a title case of the object name
5149
+ defaultObjectTitles[blockObject.name]
5150
+ ) : blockObject.title,
5151
+ fields: []
5152
+ })) ?? [], inlineObjects = definition?.inlineObjects?.map((inlineObject) => types.defineType({
5153
+ type: "object",
5154
+ // Very naive way to work around `SanitySchema.compile` adding default
5155
+ // fields to objects with certain names.
5156
+ name: temporaryObjectNames[inlineObject.name] ?? inlineObject.name,
5157
+ title: inlineObject.title === void 0 ? (
5158
+ // This avoids the default title which is a title case of the object name
5159
+ defaultObjectTitles[inlineObject.name]
5160
+ ) : inlineObject.title,
5161
+ fields: []
5162
+ })) ?? [], portableTextSchema = types.defineField({
5163
+ type: "array",
5164
+ name: "portable-text",
5165
+ of: [...blockObjects.map((blockObject) => ({
5166
+ type: blockObject.name
5167
+ })), {
5168
+ type: "block",
5169
+ name: "block",
5170
+ of: inlineObjects.map((inlineObject) => ({
5171
+ type: inlineObject.name
5172
+ })),
5173
+ marks: {
5174
+ decorators: definition?.decorators?.map((decorator) => ({
5175
+ title: decorator.title ?? startCase__default.default(decorator.name),
5176
+ value: decorator.name
5177
+ })) ?? [],
5178
+ annotations: definition?.annotations?.map((annotation) => ({
5179
+ name: annotation.name,
5180
+ type: "object",
5181
+ title: annotation.title
5182
+ })) ?? []
5183
+ },
5184
+ lists: definition?.lists?.map((list) => ({
5185
+ value: list.name,
5186
+ title: list.title ?? startCase__default.default(list.name)
5187
+ })) ?? [],
5188
+ styles: definition?.styles?.map((style) => ({
5189
+ value: style.name,
5190
+ title: style.title ?? startCase__default.default(style.name)
5191
+ })) ?? []
5192
+ }]
5193
+ }), schema$1 = schema.Schema.compile({
5194
+ types: [portableTextSchema, ...blockObjects, ...inlineObjects]
5195
+ }).get("portable-text"), pteSchema = createEditorSchema(schema$1);
5196
+ return {
5197
+ ...pteSchema,
5198
+ blockObjects: pteSchema.blockObjects.map((blockObject) => objectNames[blockObject.name] !== void 0 ? {
5199
+ ...blockObject,
5200
+ name: objectNames[blockObject.name],
5201
+ type: {
5202
+ ...blockObject.type,
5203
+ name: objectNames[blockObject.name]
5204
+ }
5205
+ } : blockObject),
5206
+ inlineObjects: pteSchema.inlineObjects.map((inlineObject) => objectNames[inlineObject.name] !== void 0 ? {
5207
+ ...inlineObject,
5208
+ name: objectNames[inlineObject.name]
5209
+ } : inlineObject)
5210
+ };
5542
5211
  }
5543
5212
  const abstractAnnotationBehaviors = [behavior_core.defineBehavior({
5544
5213
  on: "annotation.toggle",
@@ -5987,22 +5656,228 @@ const abstractAnnotationBehaviors = [behavior_core.defineBehavior({
5987
5656
  })]]
5988
5657
  }),
5989
5658
  behavior_core.defineBehavior({
5990
- on: "clipboard.cut",
5991
- guard: ({
5992
- snapshot
5993
- }) => {
5994
- const focusSpan = selector_isOverlappingSelection.getFocusSpan(snapshot), selectionCollapsed = selector_isOverlappingSelection.isSelectionCollapsed(snapshot);
5995
- return focusSpan && selectionCollapsed;
5996
- },
5997
- actions: [() => [{
5998
- type: "noop"
5659
+ on: "clipboard.cut",
5660
+ guard: ({
5661
+ snapshot
5662
+ }) => {
5663
+ const focusSpan = selector_isOverlappingSelection.getFocusSpan(snapshot), selectionCollapsed = selector_isOverlappingSelection.isSelectionCollapsed(snapshot);
5664
+ return focusSpan && selectionCollapsed;
5665
+ },
5666
+ actions: [() => [{
5667
+ type: "noop"
5668
+ }]]
5669
+ }),
5670
+ behavior_core.defineBehavior({
5671
+ on: "clipboard.cut",
5672
+ guard: ({
5673
+ snapshot
5674
+ }) => snapshot.context.selection ? {
5675
+ selection: snapshot.context.selection
5676
+ } : !1,
5677
+ actions: [({
5678
+ event
5679
+ }, {
5680
+ selection
5681
+ }) => [behavior_core.raise({
5682
+ type: "serialize",
5683
+ originEvent: event
5684
+ }), behavior_core.raise({
5685
+ type: "delete",
5686
+ selection
5687
+ })]]
5688
+ }),
5689
+ behavior_core.defineBehavior({
5690
+ on: "drag.dragstart",
5691
+ actions: [({
5692
+ event
5693
+ }) => [behavior_core.raise({
5694
+ type: "serialize",
5695
+ originEvent: event
5696
+ })]]
5697
+ }),
5698
+ behavior_core.defineBehavior({
5699
+ on: "serialization.success",
5700
+ actions: [({
5701
+ event
5702
+ }) => [{
5703
+ type: "effect",
5704
+ effect: () => {
5705
+ event.originEvent.originEvent.dataTransfer.setData(event.mimeType, event.data);
5706
+ }
5707
+ }]]
5708
+ }),
5709
+ behavior_core.defineBehavior({
5710
+ on: "serialization.failure",
5711
+ actions: [({
5712
+ event
5713
+ }) => [{
5714
+ type: "effect",
5715
+ effect: () => {
5716
+ console.warn(`Serialization of ${event.mimeType} failed with reason "${event.reason}"`);
5717
+ }
5718
+ }]]
5719
+ }),
5720
+ behavior_core.defineBehavior({
5721
+ on: "drag.drop",
5722
+ guard: ({
5723
+ snapshot,
5724
+ event
5725
+ }) => {
5726
+ const dragOrigin = snapshot.beta.internalDrag?.origin, dropPosition = event.position.selection;
5727
+ return dragOrigin ? selector_isOverlappingSelection.isOverlappingSelection(dropPosition)({
5728
+ ...snapshot,
5729
+ context: {
5730
+ ...snapshot.context,
5731
+ selection: dragOrigin.selection
5732
+ }
5733
+ }) : !1;
5734
+ },
5735
+ actions: [() => [{
5736
+ type: "noop"
5737
+ }]]
5738
+ }),
5739
+ behavior_core.defineBehavior({
5740
+ on: "drag.drop",
5741
+ actions: [({
5742
+ event
5743
+ }) => [behavior_core.raise({
5744
+ type: "select",
5745
+ selection: event.position.selection
5746
+ }), behavior_core.raise({
5747
+ type: "deserialize",
5748
+ originEvent: event
5749
+ })]]
5750
+ }),
5751
+ behavior_core.defineBehavior({
5752
+ on: "deserialization.success",
5753
+ guard: ({
5754
+ snapshot,
5755
+ event
5756
+ }) => {
5757
+ if (event.originEvent.type !== "drag.drop" || snapshot.beta.internalDrag === void 0)
5758
+ return !1;
5759
+ const dragOrigin = snapshot.beta.internalDrag.origin, dropPosition = event.originEvent.position.selection, droppingOnDragOrigin = dragOrigin ? selector_isOverlappingSelection.isOverlappingSelection(dropPosition)({
5760
+ ...snapshot,
5761
+ context: {
5762
+ ...snapshot.context,
5763
+ selection: dragOrigin.selection
5764
+ }
5765
+ }) : !1, draggingEntireBlocks = selector_isSelectingEntireBlocks.isSelectingEntireBlocks({
5766
+ context: {
5767
+ ...snapshot.context,
5768
+ selection: dragOrigin.selection
5769
+ }
5770
+ }), draggedBlocks = selector_isOverlappingSelection.getSelectedBlocks({
5771
+ context: {
5772
+ ...snapshot.context,
5773
+ selection: dragOrigin.selection
5774
+ }
5775
+ });
5776
+ return droppingOnDragOrigin ? !1 : {
5777
+ draggingEntireBlocks,
5778
+ draggedBlocks,
5779
+ dragOrigin,
5780
+ originEvent: event.originEvent
5781
+ };
5782
+ },
5783
+ actions: [({
5784
+ event
5785
+ }, {
5786
+ draggingEntireBlocks,
5787
+ draggedBlocks,
5788
+ dragOrigin,
5789
+ originEvent
5790
+ }) => [...draggingEntireBlocks ? draggedBlocks.map((block) => behavior_core.raise({
5791
+ type: "delete.block",
5792
+ at: block.path
5793
+ })) : [behavior_core.raise({
5794
+ type: "delete",
5795
+ selection: dragOrigin.selection
5796
+ })], behavior_core.raise({
5797
+ type: "insert.blocks",
5798
+ blocks: event.data,
5799
+ placement: draggingEntireBlocks ? originEvent.position.block === "start" ? "before" : originEvent.position.block === "end" ? "after" : "auto" : "auto"
5800
+ })]]
5801
+ }),
5802
+ /**
5803
+ * If we are pasting text/plain into a text block then we can probably
5804
+ * assume that the intended behavior is that the pasted text inherits
5805
+ * formatting from the text it's pasted into.
5806
+ */
5807
+ behavior_core.defineBehavior({
5808
+ on: "deserialization.success",
5809
+ guard: ({
5810
+ snapshot,
5811
+ event
5812
+ }) => {
5813
+ if (selector_isOverlappingSelection.getFocusTextBlock(snapshot) && event.mimeType === "text/plain" && event.originEvent.type === "clipboard.paste") {
5814
+ const activeDecorators = snapshot.context.activeDecorators;
5815
+ return {
5816
+ activeAnnotations: selector_isSelectingEntireBlocks.getActiveAnnotations(snapshot),
5817
+ activeDecorators,
5818
+ textRuns: event.data.flatMap((block) => parseBlocks.isTextBlock(snapshot.context.schema, block) ? [util_sliceBlocks.getTextBlockText(block)] : [])
5819
+ };
5820
+ }
5821
+ return !1;
5822
+ },
5823
+ actions: [(_, {
5824
+ activeAnnotations,
5825
+ activeDecorators,
5826
+ textRuns
5827
+ }) => textRuns.flatMap((textRun, index) => index !== textRuns.length - 1 ? [behavior_core.raise({
5828
+ type: "insert.span",
5829
+ text: textRun,
5830
+ decorators: activeDecorators,
5831
+ annotations: activeAnnotations.map(({
5832
+ _key,
5833
+ _type,
5834
+ ...value
5835
+ }) => ({
5836
+ name: _type,
5837
+ value
5838
+ }))
5839
+ }), behavior_core.raise({
5840
+ type: "insert.break"
5841
+ })] : [behavior_core.raise({
5842
+ type: "insert.span",
5843
+ text: textRun,
5844
+ decorators: activeDecorators,
5845
+ annotations: activeAnnotations.map(({
5846
+ _key,
5847
+ _type,
5848
+ ...value
5849
+ }) => ({
5850
+ name: _type,
5851
+ value
5852
+ }))
5853
+ })])]
5854
+ }),
5855
+ behavior_core.defineBehavior({
5856
+ on: "deserialization.success",
5857
+ actions: [({
5858
+ event
5859
+ }) => [behavior_core.raise({
5860
+ type: "insert.blocks",
5861
+ blocks: event.data,
5862
+ placement: "auto"
5863
+ })]]
5864
+ }),
5865
+ behavior_core.defineBehavior({
5866
+ on: "deserialization.failure",
5867
+ actions: [({
5868
+ event
5869
+ }) => [{
5870
+ type: "effect",
5871
+ effect: () => {
5872
+ console.warn(`Deserialization of ${event.mimeType} failed with reason "${event.reason}"`);
5873
+ }
5999
5874
  }]]
6000
5875
  }),
6001
5876
  behavior_core.defineBehavior({
6002
- on: "clipboard.cut",
5877
+ on: "clipboard.paste",
6003
5878
  guard: ({
6004
5879
  snapshot
6005
- }) => snapshot.context.selection ? {
5880
+ }) => snapshot.context.selection && selector_isOverlappingSelection.isSelectionExpanded(snapshot) ? {
6006
5881
  selection: snapshot.context.selection
6007
5882
  } : !1,
6008
5883
  actions: [({
@@ -6010,887 +5885,1049 @@ const abstractAnnotationBehaviors = [behavior_core.defineBehavior({
6010
5885
  }, {
6011
5886
  selection
6012
5887
  }) => [behavior_core.raise({
6013
- type: "serialize",
6014
- originEvent: event
6015
- }), behavior_core.raise({
6016
5888
  type: "delete",
6017
5889
  selection
5890
+ }), behavior_core.raise({
5891
+ type: "deserialize",
5892
+ originEvent: event
6018
5893
  })]]
6019
5894
  }),
6020
5895
  behavior_core.defineBehavior({
6021
- on: "drag.dragstart",
5896
+ on: "clipboard.paste",
6022
5897
  actions: [({
6023
5898
  event
6024
5899
  }) => [behavior_core.raise({
6025
- type: "serialize",
5900
+ type: "deserialize",
6026
5901
  originEvent: event
6027
5902
  })]]
6028
5903
  }),
6029
5904
  behavior_core.defineBehavior({
6030
- on: "serialization.success",
5905
+ on: "input.*",
6031
5906
  actions: [({
6032
5907
  event
6033
- }) => [{
6034
- type: "effect",
6035
- effect: () => {
6036
- event.originEvent.originEvent.dataTransfer.setData(event.mimeType, event.data);
6037
- }
6038
- }]]
5908
+ }) => [behavior_core.raise({
5909
+ type: "deserialize",
5910
+ originEvent: event
5911
+ })]]
6039
5912
  }),
6040
- behavior_core.defineBehavior({
6041
- on: "serialization.failure",
6042
- actions: [({
6043
- event
6044
- }) => [{
6045
- type: "effect",
6046
- effect: () => {
6047
- console.warn(`Serialization of ${event.mimeType} failed with reason "${event.reason}"`);
5913
+ ...abstractAnnotationBehaviors,
5914
+ ...abstractDecoratorBehaviors,
5915
+ ...abstractInsertBehaviors,
5916
+ ...abstractListItemBehaviors,
5917
+ ...abstractMoveBehaviors,
5918
+ ...abstractStyleBehaviors,
5919
+ ...abstractSelectBehaviors,
5920
+ raiseDeserializationSuccessOrFailure,
5921
+ raiseSerializationSuccessOrFailure,
5922
+ raiseInsertSoftBreak
5923
+ ], abstractBehaviorEventTypes = ["annotation.toggle", "decorator.toggle", "deserialize", "deserialization.success", "deserialization.failure", "insert.blocks", "list item.add", "list item.remove", "list item.toggle", "move.block down", "move.block up", "select.previous block", "select.next block", "serialize", "serialization.success", "serialization.failure", "style.add", "style.remove", "style.toggle"];
5924
+ function isAbstractBehaviorEvent(event) {
5925
+ return abstractBehaviorEventTypes.includes(event.type);
5926
+ }
5927
+ const nativeBehaviorEventTypes = ["clipboard.copy", "clipboard.cut", "clipboard.paste", "drag.dragstart", "drag.drag", "drag.dragend", "drag.dragenter", "drag.dragover", "drag.dragleave", "drag.drop", "input.*", "keyboard.keydown", "keyboard.keyup", "mouse.click"];
5928
+ function isNativeBehaviorEvent(event) {
5929
+ return nativeBehaviorEventTypes.includes(event.type);
5930
+ }
5931
+ function isCustomBehaviorEvent(event) {
5932
+ return event.type.startsWith("custom.");
5933
+ }
5934
+ const debug$3 = debugWithName("behaviors:event");
5935
+ function eventCategory(event) {
5936
+ return isNativeBehaviorEvent(event) ? "native" : isAbstractBehaviorEvent(event) ? "abstract" : isCustomBehaviorEvent(event) ? "custom" : "synthetic";
5937
+ }
5938
+ function performEvent({
5939
+ behaviors,
5940
+ event,
5941
+ editor,
5942
+ keyGenerator,
5943
+ schema: schema2,
5944
+ getSnapshot,
5945
+ nativeEvent,
5946
+ defaultActionCallback
5947
+ }) {
5948
+ debug$3(`(${eventCategory(event)})`, JSON.stringify(event, null, 2));
5949
+ const defaultAction = isCustomBehaviorEvent(event) || isNativeBehaviorEvent(event) || isAbstractBehaviorEvent(event) ? void 0 : {
5950
+ ...event,
5951
+ editor
5952
+ }, eventBehaviors = behaviors.filter((behavior) => {
5953
+ if (behavior.on === "*")
5954
+ return !0;
5955
+ const [listenedNamespace] = behavior.on.includes("*") && behavior.on.includes(".") ? behavior.on.split(".") : [void 0], [eventNamespace] = event.type.includes(".") ? event.type.split(".") : [void 0];
5956
+ return listenedNamespace !== void 0 && eventNamespace !== void 0 && listenedNamespace === eventNamespace || listenedNamespace !== void 0 && eventNamespace === void 0 && listenedNamespace === event.type ? !0 : behavior.on === event.type;
5957
+ });
5958
+ if (eventBehaviors.length === 0) {
5959
+ if (defaultActionCallback) {
5960
+ withApplyingBehaviorActions(editor, () => {
5961
+ try {
5962
+ defaultActionCallback();
5963
+ } catch (error) {
5964
+ console.error(new Error(`Performing action "${event.type}" failed due to: ${error.message}`));
5965
+ }
5966
+ });
5967
+ return;
5968
+ }
5969
+ if (!defaultAction)
5970
+ return;
5971
+ withApplyingBehaviorActions(editor, () => {
5972
+ try {
5973
+ performAction({
5974
+ context: {
5975
+ keyGenerator,
5976
+ schema: schema2
5977
+ },
5978
+ action: defaultAction
5979
+ });
5980
+ } catch (error) {
5981
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6048
5982
  }
6049
- }]]
6050
- }),
6051
- behavior_core.defineBehavior({
6052
- on: "drag.drop",
6053
- guard: ({
6054
- snapshot,
5983
+ }), editor.onChange();
5984
+ return;
5985
+ }
5986
+ const editorSnapshot = getSnapshot();
5987
+ let behaviorOverwritten = !1;
5988
+ for (const eventBehavior of eventBehaviors) {
5989
+ const shouldRun = eventBehavior.guard === void 0 || eventBehavior.guard({
5990
+ context: editorSnapshot.context,
5991
+ snapshot: editorSnapshot,
6055
5992
  event
6056
- }) => {
6057
- const dragOrigin = snapshot.beta.internalDrag?.origin, dropPosition = event.position.selection;
6058
- return dragOrigin ? selector_isOverlappingSelection.isOverlappingSelection(dropPosition)({
6059
- ...snapshot,
6060
- context: {
6061
- ...snapshot.context,
6062
- selection: dragOrigin.selection
5993
+ });
5994
+ if (!shouldRun)
5995
+ continue;
5996
+ const actionSets = eventBehavior.actions.map((actionSet) => actionSet({
5997
+ context: editorSnapshot.context,
5998
+ snapshot: editorSnapshot,
5999
+ event
6000
+ }, shouldRun));
6001
+ for (const actionSet of actionSets)
6002
+ actionSet.length !== 0 && (behaviorOverwritten = behaviorOverwritten || actionSet.some((action) => action.type !== "effect"), withApplyingBehaviorActionSet(editor, () => {
6003
+ for (const action of actionSet) {
6004
+ if (action.type === "raise") {
6005
+ performEvent({
6006
+ behaviors,
6007
+ event: action.event,
6008
+ editor,
6009
+ keyGenerator,
6010
+ schema: schema2,
6011
+ getSnapshot,
6012
+ defaultActionCallback: void 0,
6013
+ nativeEvent: void 0
6014
+ });
6015
+ continue;
6016
+ }
6017
+ const internalAction = {
6018
+ ...action,
6019
+ editor
6020
+ };
6021
+ try {
6022
+ performAction({
6023
+ context: {
6024
+ keyGenerator,
6025
+ schema: schema2
6026
+ },
6027
+ action: internalAction
6028
+ });
6029
+ } catch (error) {
6030
+ console.error(new Error(`Performing action "${internalAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6031
+ break;
6032
+ }
6063
6033
  }
6064
- }) : !1;
6034
+ }), editor.onChange());
6035
+ if (behaviorOverwritten) {
6036
+ nativeEvent?.preventDefault();
6037
+ break;
6038
+ }
6039
+ }
6040
+ if (!behaviorOverwritten) {
6041
+ if (defaultActionCallback) {
6042
+ withApplyingBehaviorActions(editor, () => {
6043
+ try {
6044
+ defaultActionCallback();
6045
+ } catch (error) {
6046
+ console.error(new Error(`Performing "${event.type}" failed due to: ${error.message}`));
6047
+ }
6048
+ });
6049
+ return;
6050
+ }
6051
+ if (!defaultAction)
6052
+ return;
6053
+ withApplyingBehaviorActions(editor, () => {
6054
+ try {
6055
+ performAction({
6056
+ context: {
6057
+ keyGenerator,
6058
+ schema: schema2
6059
+ },
6060
+ action: defaultAction
6061
+ });
6062
+ } catch (error) {
6063
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6064
+ }
6065
+ }), editor.onChange();
6066
+ }
6067
+ }
6068
+ function slateChildrenToBlocks(schema2, value) {
6069
+ const blocks = new Array(value.length);
6070
+ for (let blockIndex = 0; blockIndex < value.length; blockIndex++) {
6071
+ const descendant = value[blockIndex];
6072
+ if (descendant._type !== schema2.block.name) {
6073
+ blocks[blockIndex] = {
6074
+ _key: descendant._key,
6075
+ _type: descendant._type,
6076
+ ..."value" in descendant && typeof descendant.value == "object" ? descendant.value : {}
6077
+ };
6078
+ continue;
6079
+ }
6080
+ const children = "children" in descendant ? descendant.children : [], processedChildren = new Array(children.length);
6081
+ for (let childIndex = 0; childIndex < children.length; childIndex++) {
6082
+ const child = children[childIndex];
6083
+ processedChildren[childIndex] = child._type === schema2.span.name ? child : {
6084
+ _key: child._key,
6085
+ _type: child._type,
6086
+ ..."value" in child && typeof child.value == "object" ? child.value : {}
6087
+ };
6088
+ }
6089
+ blocks[blockIndex] = {
6090
+ ...descendant,
6091
+ children: processedChildren
6092
+ };
6093
+ }
6094
+ return blocks;
6095
+ }
6096
+ function getActiveDecorators({
6097
+ schema: schema2,
6098
+ slateEditorInstance
6099
+ }) {
6100
+ const decorators = schema2.decorators.map((decorator) => decorator.value);
6101
+ return ({
6102
+ ...slate.Editor.marks(slateEditorInstance) ?? {}
6103
+ }.marks ?? []).filter((mark) => decorators.includes(mark));
6104
+ }
6105
+ function createEditorSnapshot({
6106
+ converters,
6107
+ editor,
6108
+ keyGenerator,
6109
+ readOnly,
6110
+ schema: schema2,
6111
+ hasTag,
6112
+ internalDrag
6113
+ }) {
6114
+ const value = slateChildrenToBlocks(schema2, editor.children), selection = editor.selection ? slateRangeToSelection({
6115
+ schema: schema2,
6116
+ editor,
6117
+ range: editor.selection
6118
+ }) : null;
6119
+ return {
6120
+ context: {
6121
+ activeDecorators: getActiveDecorators({
6122
+ schema: schema2,
6123
+ slateEditorInstance: editor
6124
+ }),
6125
+ converters,
6126
+ keyGenerator,
6127
+ readOnly,
6128
+ schema: schema2,
6129
+ selection,
6130
+ value
6065
6131
  },
6066
- actions: [() => [{
6067
- type: "noop"
6068
- }]]
6069
- }),
6070
- behavior_core.defineBehavior({
6071
- on: "drag.drop",
6072
- actions: [({
6073
- event
6074
- }) => [behavior_core.raise({
6075
- type: "select",
6076
- selection: event.position.selection
6077
- }), behavior_core.raise({
6078
- type: "deserialize",
6079
- originEvent: event
6080
- })]]
6081
- }),
6082
- behavior_core.defineBehavior({
6083
- on: "deserialization.success",
6084
- guard: ({
6085
- snapshot,
6086
- event
6132
+ beta: {
6133
+ hasTag,
6134
+ internalDrag
6135
+ }
6136
+ };
6137
+ }
6138
+ const editorMachine = xstate.setup({
6139
+ types: {
6140
+ context: {},
6141
+ events: {},
6142
+ emitted: {},
6143
+ input: {},
6144
+ tags: {}
6145
+ },
6146
+ actions: {
6147
+ "add behavior to context": xstate.assign({
6148
+ behaviors: ({
6149
+ context,
6150
+ event
6151
+ }) => (xstate.assertEvent(event, "add behavior"), /* @__PURE__ */ new Set([...context.behaviors, event.behavior]))
6152
+ }),
6153
+ "remove behavior from context": xstate.assign({
6154
+ behaviors: ({
6155
+ context,
6156
+ event
6157
+ }) => (xstate.assertEvent(event, "remove behavior"), context.behaviors.delete(event.behavior), /* @__PURE__ */ new Set([...context.behaviors]))
6158
+ }),
6159
+ "assign behaviors": xstate.assign({
6160
+ behaviors: ({
6161
+ event
6162
+ }) => (xstate.assertEvent(event, "update behaviors"), /* @__PURE__ */ new Set([...event.behaviors]))
6163
+ }),
6164
+ "assign schema": xstate.assign({
6165
+ schema: ({
6166
+ event
6167
+ }) => (xstate.assertEvent(event, "update schema"), event.schema)
6168
+ }),
6169
+ "emit patch event": xstate.enqueueActions(({
6170
+ event,
6171
+ enqueue
6087
6172
  }) => {
6088
- if (event.originEvent.type !== "drag.drop" || snapshot.beta.internalDrag === void 0)
6089
- return !1;
6090
- const dragOrigin = snapshot.beta.internalDrag.origin, dropPosition = event.originEvent.position.selection, droppingOnDragOrigin = dragOrigin ? selector_isOverlappingSelection.isOverlappingSelection(dropPosition)({
6091
- ...snapshot,
6092
- context: {
6093
- ...snapshot.context,
6094
- selection: dragOrigin.selection
6095
- }
6096
- }) : !1, draggingEntireBlocks = selector_isSelectingEntireBlocks.isSelectingEntireBlocks({
6097
- context: {
6098
- ...snapshot.context,
6099
- selection: dragOrigin.selection
6100
- }
6101
- }), draggedBlocks = selector_isOverlappingSelection.getSelectedBlocks({
6102
- context: {
6103
- ...snapshot.context,
6104
- selection: dragOrigin.selection
6105
- }
6173
+ xstate.assertEvent(event, "internal.patch"), enqueue.emit(event), enqueue.emit({
6174
+ type: "patch",
6175
+ patch: event.patch
6106
6176
  });
6107
- return droppingOnDragOrigin ? !1 : {
6108
- draggingEntireBlocks,
6109
- draggedBlocks,
6110
- dragOrigin,
6111
- originEvent: event.originEvent
6112
- };
6113
- },
6114
- actions: [({
6115
- event
6116
- }, {
6117
- draggingEntireBlocks,
6118
- draggedBlocks,
6119
- dragOrigin,
6120
- originEvent
6121
- }) => [...draggingEntireBlocks ? draggedBlocks.map((block) => behavior_core.raise({
6122
- type: "delete.block",
6123
- at: block.path
6124
- })) : [behavior_core.raise({
6125
- type: "delete",
6126
- selection: dragOrigin.selection
6127
- })], behavior_core.raise({
6128
- type: "insert.blocks",
6129
- blocks: event.data,
6130
- placement: draggingEntireBlocks ? originEvent.position.block === "start" ? "before" : originEvent.position.block === "end" ? "after" : "auto" : "auto"
6131
- })]]
6132
- }),
6133
- /**
6134
- * If we are pasting text/plain into a text block then we can probably
6135
- * assume that the intended behavior is that the pasted text inherits
6136
- * formatting from the text it's pasted into.
6137
- */
6138
- behavior_core.defineBehavior({
6139
- on: "deserialization.success",
6140
- guard: ({
6141
- snapshot,
6177
+ }),
6178
+ "emit mutation event": xstate.emit(({
6142
6179
  event
6180
+ }) => (xstate.assertEvent(event, "mutation"), event)),
6181
+ "emit read only": xstate.emit({
6182
+ type: "read only"
6183
+ }),
6184
+ "emit editable": xstate.emit({
6185
+ type: "editable"
6186
+ }),
6187
+ "defer event": xstate.assign({
6188
+ pendingEvents: ({
6189
+ context,
6190
+ event
6191
+ }) => (xstate.assertEvent(event, ["internal.patch", "mutation"]), [...context.pendingEvents, event])
6192
+ }),
6193
+ "emit pending events": xstate.enqueueActions(({
6194
+ context,
6195
+ enqueue
6143
6196
  }) => {
6144
- if (selector_isOverlappingSelection.getFocusTextBlock(snapshot) && event.mimeType === "text/plain" && event.originEvent.type === "clipboard.paste") {
6145
- const activeDecorators = snapshot.context.activeDecorators;
6146
- return {
6147
- activeAnnotations: selector_isSelectingEntireBlocks.getActiveAnnotations(snapshot),
6148
- activeDecorators,
6149
- textRuns: event.data.flatMap((block) => parseBlocks.isTextBlock(snapshot.context.schema, block) ? [util_sliceBlocks.getTextBlockText(block)] : [])
6150
- };
6151
- }
6152
- return !1;
6197
+ for (const event of context.pendingEvents)
6198
+ event.type === "internal.patch" ? (enqueue.emit(event), enqueue.emit({
6199
+ type: "patch",
6200
+ patch: event.patch
6201
+ })) : enqueue.emit(event);
6202
+ }),
6203
+ "emit ready": xstate.emit({
6204
+ type: "ready"
6205
+ }),
6206
+ "clear pending events": xstate.assign({
6207
+ pendingEvents: []
6208
+ }),
6209
+ "handle behavior event": ({
6210
+ context,
6211
+ event,
6212
+ self
6213
+ }) => {
6214
+ xstate.assertEvent(event, ["behavior event"]), performEvent({
6215
+ behaviors: [...context.behaviors.values(), ...defaultBehaviors],
6216
+ event: event.behaviorEvent,
6217
+ editor: event.editor,
6218
+ keyGenerator: context.keyGenerator,
6219
+ schema: context.schema,
6220
+ getSnapshot: () => createEditorSnapshot({
6221
+ converters: [...context.converters],
6222
+ editor: event.editor,
6223
+ keyGenerator: context.keyGenerator,
6224
+ readOnly: self.getSnapshot().matches({
6225
+ "edit mode": "read only"
6226
+ }),
6227
+ schema: context.schema,
6228
+ hasTag: (tag) => self.getSnapshot().hasTag(tag),
6229
+ internalDrag: context.internalDrag
6230
+ }),
6231
+ nativeEvent: event.nativeEvent,
6232
+ defaultActionCallback: event.type === "behavior event" ? event.defaultActionCallback : void 0
6233
+ });
6234
+ }
6235
+ }
6236
+ }).createMachine({
6237
+ id: "editor",
6238
+ context: ({
6239
+ input
6240
+ }) => ({
6241
+ behaviors: /* @__PURE__ */ new Set([...input.behaviors ?? behavior_core.coreBehaviors]),
6242
+ converters: new Set(input.converters ?? []),
6243
+ keyGenerator: input.keyGenerator,
6244
+ pendingEvents: [],
6245
+ schema: input.schema,
6246
+ selection: null,
6247
+ initialReadOnly: input.readOnly ?? !1,
6248
+ maxBlocks: input.maxBlocks,
6249
+ value: input.value
6250
+ }),
6251
+ on: {
6252
+ "notify.blurred": {
6253
+ actions: xstate.emit(({
6254
+ event
6255
+ }) => ({
6256
+ ...event,
6257
+ type: "blurred"
6258
+ }))
6259
+ },
6260
+ "notify.done loading": {
6261
+ actions: xstate.emit({
6262
+ type: "done loading"
6263
+ })
6264
+ },
6265
+ "notify.error": {
6266
+ actions: xstate.emit(({
6267
+ event
6268
+ }) => ({
6269
+ ...event,
6270
+ type: "error"
6271
+ }))
6272
+ },
6273
+ "notify.invalid value": {
6274
+ actions: xstate.emit(({
6275
+ event
6276
+ }) => ({
6277
+ ...event,
6278
+ type: "invalid value"
6279
+ }))
6280
+ },
6281
+ "notify.focused": {
6282
+ actions: xstate.emit(({
6283
+ event
6284
+ }) => ({
6285
+ ...event,
6286
+ type: "focused"
6287
+ }))
6153
6288
  },
6154
- actions: [(_, {
6155
- activeAnnotations,
6156
- activeDecorators,
6157
- textRuns
6158
- }) => textRuns.flatMap((textRun, index) => index !== textRuns.length - 1 ? [behavior_core.raise({
6159
- type: "insert.span",
6160
- text: textRun,
6161
- decorators: activeDecorators,
6162
- annotations: activeAnnotations.map(({
6163
- _key,
6164
- _type,
6165
- ...value
6289
+ "notify.selection": {
6290
+ actions: [xstate.assign({
6291
+ selection: ({
6292
+ event
6293
+ }) => event.selection
6294
+ }), xstate.emit(({
6295
+ event
6166
6296
  }) => ({
6167
- name: _type,
6168
- value
6297
+ ...event,
6298
+ type: "selection"
6299
+ }))]
6300
+ },
6301
+ "notify.unset": {
6302
+ actions: xstate.emit(({
6303
+ event
6304
+ }) => ({
6305
+ ...event,
6306
+ type: "unset"
6169
6307
  }))
6170
- }), behavior_core.raise({
6171
- type: "insert.break"
6172
- })] : [behavior_core.raise({
6173
- type: "insert.span",
6174
- text: textRun,
6175
- decorators: activeDecorators,
6176
- annotations: activeAnnotations.map(({
6177
- _key,
6178
- _type,
6179
- ...value
6308
+ },
6309
+ "notify.loading": {
6310
+ actions: xstate.emit({
6311
+ type: "loading"
6312
+ })
6313
+ },
6314
+ "notify.value changed": {
6315
+ actions: xstate.emit(({
6316
+ event
6180
6317
  }) => ({
6181
- name: _type,
6182
- value
6318
+ ...event,
6319
+ type: "value changed"
6183
6320
  }))
6184
- })])]
6185
- }),
6186
- behavior_core.defineBehavior({
6187
- on: "deserialization.success",
6188
- actions: [({
6189
- event
6190
- }) => [behavior_core.raise({
6191
- type: "insert.blocks",
6192
- blocks: event.data,
6193
- placement: "auto"
6194
- })]]
6195
- }),
6196
- behavior_core.defineBehavior({
6197
- on: "deserialization.failure",
6198
- actions: [({
6199
- event
6200
- }) => [{
6201
- type: "effect",
6202
- effect: () => {
6203
- console.warn(`Deserialization of ${event.mimeType} failed with reason "${event.reason}"`);
6204
- }
6205
- }]]
6206
- }),
6207
- behavior_core.defineBehavior({
6208
- on: "clipboard.paste",
6209
- guard: ({
6210
- snapshot
6211
- }) => snapshot.context.selection && selector_isOverlappingSelection.isSelectionExpanded(snapshot) ? {
6212
- selection: snapshot.context.selection
6213
- } : !1,
6214
- actions: [({
6215
- event
6216
- }, {
6217
- selection
6218
- }) => [behavior_core.raise({
6219
- type: "delete",
6220
- selection
6221
- }), behavior_core.raise({
6222
- type: "deserialize",
6223
- originEvent: event
6224
- })]]
6225
- }),
6226
- behavior_core.defineBehavior({
6227
- on: "clipboard.paste",
6228
- actions: [({
6229
- event
6230
- }) => [behavior_core.raise({
6231
- type: "deserialize",
6232
- originEvent: event
6233
- })]]
6234
- }),
6235
- behavior_core.defineBehavior({
6236
- on: "input.*",
6237
- actions: [({
6238
- event
6239
- }) => [behavior_core.raise({
6240
- type: "deserialize",
6241
- originEvent: event
6242
- })]]
6243
- }),
6244
- ...abstractAnnotationBehaviors,
6245
- ...abstractDecoratorBehaviors,
6246
- ...abstractInsertBehaviors,
6247
- ...abstractListItemBehaviors,
6248
- ...abstractMoveBehaviors,
6249
- ...abstractStyleBehaviors,
6250
- ...abstractSelectBehaviors,
6251
- raiseDeserializationSuccessOrFailure,
6252
- raiseSerializationSuccessOrFailure,
6253
- raiseInsertSoftBreak
6254
- ], abstractBehaviorEventTypes = ["annotation.toggle", "decorator.toggle", "deserialize", "deserialization.success", "deserialization.failure", "insert.blocks", "list item.add", "list item.remove", "list item.toggle", "move.block down", "move.block up", "select.previous block", "select.next block", "serialize", "serialization.success", "serialization.failure", "style.add", "style.remove", "style.toggle"];
6255
- function isAbstractBehaviorEvent(event) {
6256
- return abstractBehaviorEventTypes.includes(event.type);
6257
- }
6258
- const nativeBehaviorEventTypes = ["clipboard.copy", "clipboard.cut", "clipboard.paste", "drag.dragstart", "drag.drag", "drag.dragend", "drag.dragenter", "drag.dragover", "drag.dragleave", "drag.drop", "input.*", "keyboard.keydown", "keyboard.keyup", "mouse.click"];
6259
- function isNativeBehaviorEvent(event) {
6260
- return nativeBehaviorEventTypes.includes(event.type);
6261
- }
6262
- function isCustomBehaviorEvent(event) {
6263
- return event.type.startsWith("custom.");
6264
- }
6265
- const debug$2 = debugWithName("behaviors:event");
6266
- function eventCategory(event) {
6267
- return isNativeBehaviorEvent(event) ? "native" : isAbstractBehaviorEvent(event) ? "abstract" : isCustomBehaviorEvent(event) ? "custom" : "synthetic";
6268
- }
6269
- function performEvent({
6270
- behaviors,
6271
- event,
6272
- editor,
6273
- keyGenerator,
6274
- schema: schema2,
6275
- getSnapshot,
6276
- nativeEvent,
6277
- defaultActionCallback
6278
- }) {
6279
- debug$2(`(${eventCategory(event)})`, JSON.stringify(event, null, 2));
6280
- const defaultAction = isCustomBehaviorEvent(event) || isNativeBehaviorEvent(event) || isAbstractBehaviorEvent(event) ? void 0 : {
6281
- ...event,
6282
- editor
6283
- }, eventBehaviors = behaviors.filter((behavior) => {
6284
- if (behavior.on === "*")
6285
- return !0;
6286
- const [listenedNamespace] = behavior.on.includes("*") && behavior.on.includes(".") ? behavior.on.split(".") : [void 0], [eventNamespace] = event.type.includes(".") ? event.type.split(".") : [void 0];
6287
- return listenedNamespace !== void 0 && eventNamespace !== void 0 && listenedNamespace === eventNamespace || listenedNamespace !== void 0 && eventNamespace === void 0 && listenedNamespace === event.type ? !0 : behavior.on === event.type;
6288
- });
6289
- if (eventBehaviors.length === 0) {
6290
- if (defaultActionCallback) {
6291
- withApplyingBehaviorActions(editor, () => {
6292
- try {
6293
- defaultActionCallback();
6294
- } catch (error) {
6295
- console.error(new Error(`Performing action "${event.type}" failed due to: ${error.message}`));
6296
- }
6297
- });
6298
- return;
6321
+ },
6322
+ "add behavior": {
6323
+ actions: "add behavior to context"
6324
+ },
6325
+ "remove behavior": {
6326
+ actions: "remove behavior from context"
6327
+ },
6328
+ patches: {
6329
+ actions: xstate.emit(({
6330
+ event
6331
+ }) => event)
6332
+ },
6333
+ "update behaviors": {
6334
+ actions: "assign behaviors"
6335
+ },
6336
+ "update key generator": {
6337
+ actions: xstate.assign({
6338
+ keyGenerator: ({
6339
+ event
6340
+ }) => event.keyGenerator
6341
+ })
6342
+ },
6343
+ "update schema": {
6344
+ actions: "assign schema"
6345
+ },
6346
+ "update value": {
6347
+ actions: xstate.assign({
6348
+ value: ({
6349
+ event
6350
+ }) => event.value
6351
+ })
6352
+ },
6353
+ "update maxBlocks": {
6354
+ actions: xstate.assign({
6355
+ maxBlocks: ({
6356
+ event
6357
+ }) => event.maxBlocks
6358
+ })
6299
6359
  }
6300
- if (!defaultAction)
6301
- return;
6302
- withApplyingBehaviorActions(editor, () => {
6303
- try {
6304
- performAction({
6305
- context: {
6306
- keyGenerator,
6307
- schema: schema2
6360
+ },
6361
+ type: "parallel",
6362
+ states: {
6363
+ "edit mode": {
6364
+ initial: "read only",
6365
+ states: {
6366
+ "read only": {
6367
+ initial: "determine initial edit mode",
6368
+ on: {
6369
+ "behavior event": {
6370
+ actions: "handle behavior event",
6371
+ guard: ({
6372
+ event
6373
+ }) => event.behaviorEvent.type === "clipboard.copy" || event.behaviorEvent.type === "mouse.click" || event.behaviorEvent.type === "serialize" || event.behaviorEvent.type === "serialization.failure" || event.behaviorEvent.type === "serialization.success" || event.behaviorEvent.type === "select"
6374
+ }
6375
+ },
6376
+ states: {
6377
+ "determine initial edit mode": {
6378
+ on: {
6379
+ "done syncing initial value": [{
6380
+ target: "#editor.edit mode.read only.read only",
6381
+ guard: ({
6382
+ context
6383
+ }) => context.initialReadOnly
6384
+ }, {
6385
+ target: "#editor.edit mode.editable"
6386
+ }]
6387
+ }
6388
+ },
6389
+ "read only": {
6390
+ on: {
6391
+ "update readOnly": {
6392
+ guard: ({
6393
+ event
6394
+ }) => !event.readOnly,
6395
+ target: "#editor.edit mode.editable",
6396
+ actions: ["emit editable"]
6397
+ }
6398
+ }
6399
+ }
6400
+ }
6401
+ },
6402
+ editable: {
6403
+ on: {
6404
+ "update readOnly": {
6405
+ guard: ({
6406
+ event
6407
+ }) => event.readOnly,
6408
+ target: "#editor.edit mode.read only.read only",
6409
+ actions: ["emit read only"]
6410
+ },
6411
+ "behavior event": {
6412
+ actions: "handle behavior event"
6413
+ }
6308
6414
  },
6309
- action: defaultAction
6310
- });
6311
- } catch (error) {
6312
- console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6415
+ initial: "idle",
6416
+ states: {
6417
+ idle: {
6418
+ on: {
6419
+ dragstart: {
6420
+ actions: [xstate.assign({
6421
+ internalDrag: ({
6422
+ event
6423
+ }) => ({
6424
+ ghost: event.ghost,
6425
+ origin: event.origin
6426
+ })
6427
+ })],
6428
+ target: "dragging internally"
6429
+ }
6430
+ }
6431
+ },
6432
+ "dragging internally": {
6433
+ exit: [({
6434
+ context
6435
+ }) => {
6436
+ if (context.internalDrag?.ghost)
6437
+ try {
6438
+ context.internalDrag.ghost.parentNode?.removeChild(context.internalDrag.ghost);
6439
+ } catch (error) {
6440
+ console.error(new Error(`Removing the internal drag ghost failed due to: ${error.message}`));
6441
+ }
6442
+ }, xstate.assign({
6443
+ internalDrag: void 0
6444
+ })],
6445
+ tags: ["dragging internally"],
6446
+ on: {
6447
+ dragend: {
6448
+ target: "idle"
6449
+ },
6450
+ drop: {
6451
+ target: "idle"
6452
+ }
6453
+ }
6454
+ }
6455
+ }
6456
+ }
6313
6457
  }
6314
- }), editor.onChange();
6315
- return;
6316
- }
6317
- const editorSnapshot = getSnapshot();
6318
- let behaviorOverwritten = !1;
6319
- for (const eventBehavior of eventBehaviors) {
6320
- const shouldRun = eventBehavior.guard === void 0 || eventBehavior.guard({
6321
- context: editorSnapshot.context,
6322
- snapshot: editorSnapshot,
6323
- event
6324
- });
6325
- if (!shouldRun)
6326
- continue;
6327
- const actionSets = eventBehavior.actions.map((actionSet) => actionSet({
6328
- context: editorSnapshot.context,
6329
- snapshot: editorSnapshot,
6330
- event
6331
- }, shouldRun));
6332
- for (const actionSet of actionSets)
6333
- actionSet.length !== 0 && (behaviorOverwritten = behaviorOverwritten || actionSet.some((action) => action.type !== "effect"), withApplyingBehaviorActionSet(editor, () => {
6334
- for (const action of actionSet) {
6335
- if (action.type === "raise") {
6336
- performEvent({
6337
- behaviors,
6338
- event: action.event,
6339
- editor,
6340
- keyGenerator,
6341
- schema: schema2,
6342
- getSnapshot,
6343
- defaultActionCallback: void 0,
6344
- nativeEvent: void 0
6345
- });
6346
- continue;
6458
+ },
6459
+ setup: {
6460
+ initial: "setting up",
6461
+ states: {
6462
+ "setting up": {
6463
+ exit: ["emit ready"],
6464
+ on: {
6465
+ "internal.patch": {
6466
+ actions: "defer event"
6467
+ },
6468
+ mutation: {
6469
+ actions: "defer event"
6470
+ },
6471
+ "done syncing initial value": {
6472
+ target: "pristine"
6473
+ }
6347
6474
  }
6348
- const internalAction = {
6349
- ...action,
6350
- editor
6351
- };
6352
- try {
6353
- performAction({
6354
- context: {
6355
- keyGenerator,
6356
- schema: schema2
6357
- },
6358
- action: internalAction
6359
- });
6360
- } catch (error) {
6361
- console.error(new Error(`Performing action "${internalAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6362
- break;
6475
+ },
6476
+ pristine: {
6477
+ initial: "idle",
6478
+ states: {
6479
+ idle: {
6480
+ on: {
6481
+ normalizing: {
6482
+ target: "normalizing"
6483
+ },
6484
+ "internal.patch": {
6485
+ actions: "defer event",
6486
+ target: "#editor.setup.dirty"
6487
+ },
6488
+ mutation: {
6489
+ actions: "defer event",
6490
+ target: "#editor.setup.dirty"
6491
+ }
6492
+ }
6493
+ },
6494
+ normalizing: {
6495
+ on: {
6496
+ "done normalizing": {
6497
+ target: "idle"
6498
+ },
6499
+ "internal.patch": {
6500
+ actions: "defer event"
6501
+ },
6502
+ mutation: {
6503
+ actions: "defer event"
6504
+ }
6505
+ }
6506
+ }
6507
+ }
6508
+ },
6509
+ dirty: {
6510
+ entry: ["emit pending events", "clear pending events"],
6511
+ on: {
6512
+ "internal.patch": {
6513
+ actions: "emit patch event"
6514
+ },
6515
+ mutation: {
6516
+ actions: "emit mutation event"
6517
+ }
6363
6518
  }
6364
6519
  }
6365
- }), editor.onChange());
6366
- if (behaviorOverwritten) {
6367
- nativeEvent?.preventDefault();
6368
- break;
6369
- }
6370
- }
6371
- if (!behaviorOverwritten) {
6372
- if (defaultActionCallback) {
6373
- withApplyingBehaviorActions(editor, () => {
6374
- try {
6375
- defaultActionCallback();
6376
- } catch (error) {
6377
- console.error(new Error(`Performing "${event.type}" failed due to: ${error.message}`));
6378
- }
6379
- });
6380
- return;
6381
- }
6382
- if (!defaultAction)
6383
- return;
6384
- withApplyingBehaviorActions(editor, () => {
6385
- try {
6386
- performAction({
6387
- context: {
6388
- keyGenerator,
6389
- schema: schema2
6390
- },
6391
- action: defaultAction
6392
- });
6393
- } catch (error) {
6394
- console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6395
6520
  }
6396
- }), editor.onChange();
6397
- }
6398
- }
6399
- function slateChildrenToBlocks(schema2, value) {
6400
- const blocks = new Array(value.length);
6401
- for (let blockIndex = 0; blockIndex < value.length; blockIndex++) {
6402
- const descendant = value[blockIndex];
6403
- if (descendant._type !== schema2.block.name) {
6404
- blocks[blockIndex] = {
6405
- _key: descendant._key,
6406
- _type: descendant._type,
6407
- ..."value" in descendant && typeof descendant.value == "object" ? descendant.value : {}
6408
- };
6409
- continue;
6410
- }
6411
- const children = "children" in descendant ? descendant.children : [], processedChildren = new Array(children.length);
6412
- for (let childIndex = 0; childIndex < children.length; childIndex++) {
6413
- const child = children[childIndex];
6414
- processedChildren[childIndex] = child._type === schema2.span.name ? child : {
6415
- _key: child._key,
6416
- _type: child._type,
6417
- ..."value" in child && typeof child.value == "object" ? child.value : {}
6418
- };
6419
6521
  }
6420
- blocks[blockIndex] = {
6421
- ...descendant,
6422
- children: processedChildren
6423
- };
6424
6522
  }
6425
- return blocks;
6426
- }
6427
- function getActiveDecorators({
6428
- schema: schema2,
6429
- slateEditorInstance
6430
- }) {
6431
- const decorators = schema2.decorators.map((decorator) => decorator.value);
6432
- return ({
6433
- ...slate.Editor.marks(slateEditorInstance) ?? {}
6434
- }.marks ?? []).filter((mark) => decorators.includes(mark));
6523
+ });
6524
+ function defaultCompare(a, b) {
6525
+ return a === b;
6435
6526
  }
6436
- function createEditorSnapshot({
6437
- converters,
6438
- editor,
6439
- keyGenerator,
6440
- readOnly,
6441
- schema: schema2,
6442
- hasTag,
6443
- internalDrag
6527
+ function useEditorSelector(editor, selector, t0) {
6528
+ const $ = reactCompilerRuntime.c(3), compare = t0 === void 0 ? defaultCompare : t0;
6529
+ let t1;
6530
+ return $[0] !== editor || $[1] !== selector ? (t1 = (editorActorSnapshot) => {
6531
+ const snapshot = getEditorSnapshot({
6532
+ editorActorSnapshot,
6533
+ slateEditorInstance: editor._internal.slateEditor.instance
6534
+ });
6535
+ return selector(snapshot);
6536
+ }, $[0] = editor, $[1] = selector, $[2] = t1) : t1 = $[2], react.useSelector(editor._internal.editorActor, t1, compare);
6537
+ }
6538
+ function getEditorSnapshot({
6539
+ editorActorSnapshot,
6540
+ slateEditorInstance
6444
6541
  }) {
6445
- const value = slateChildrenToBlocks(schema2, editor.children), selection = editor.selection ? slateRangeToSelection({
6446
- schema: schema2,
6447
- editor,
6448
- range: editor.selection
6449
- }) : null;
6450
6542
  return {
6451
6543
  context: {
6544
+ converters: [...editorActorSnapshot.context.converters],
6452
6545
  activeDecorators: getActiveDecorators({
6453
- schema: schema2,
6454
- slateEditorInstance: editor
6546
+ schema: editorActorSnapshot.context.schema,
6547
+ slateEditorInstance
6455
6548
  }),
6456
- converters,
6457
- keyGenerator,
6458
- readOnly,
6459
- schema: schema2,
6460
- selection,
6461
- value
6549
+ keyGenerator: editorActorSnapshot.context.keyGenerator,
6550
+ readOnly: editorActorSnapshot.matches({
6551
+ "edit mode": "read only"
6552
+ }),
6553
+ schema: editorActorSnapshot.context.schema,
6554
+ selection: editorActorSnapshot.context.selection,
6555
+ value: slateChildrenToBlocks(editorActorSnapshot.context.schema, slateEditorInstance.children)
6462
6556
  },
6463
6557
  beta: {
6464
- hasTag,
6465
- internalDrag
6558
+ hasTag: (tag) => editorActorSnapshot.hasTag(tag),
6559
+ internalDrag: editorActorSnapshot.context.internalDrag
6466
6560
  }
6467
6561
  };
6468
6562
  }
6469
- const editorMachine = xstate.setup({
6470
- types: {
6471
- context: {},
6472
- events: {},
6473
- emitted: {},
6474
- input: {},
6475
- tags: {}
6476
- },
6477
- actions: {
6478
- "add behavior to context": xstate.assign({
6479
- behaviors: ({
6480
- context,
6481
- event
6482
- }) => (xstate.assertEvent(event, "add behavior"), /* @__PURE__ */ new Set([...context.behaviors, event.behavior]))
6483
- }),
6484
- "remove behavior from context": xstate.assign({
6485
- behaviors: ({
6486
- context,
6487
- event
6488
- }) => (xstate.assertEvent(event, "remove behavior"), context.behaviors.delete(event.behavior), /* @__PURE__ */ new Set([...context.behaviors]))
6489
- }),
6490
- "assign behaviors": xstate.assign({
6491
- behaviors: ({
6492
- event
6493
- }) => (xstate.assertEvent(event, "update behaviors"), /* @__PURE__ */ new Set([...event.behaviors]))
6494
- }),
6495
- "assign schema": xstate.assign({
6496
- schema: ({
6497
- event
6498
- }) => (xstate.assertEvent(event, "update schema"), event.schema)
6499
- }),
6500
- "emit patch event": xstate.enqueueActions(({
6501
- event,
6502
- enqueue
6503
- }) => {
6504
- xstate.assertEvent(event, "internal.patch"), enqueue.emit(event), enqueue.emit({
6505
- type: "patch",
6506
- patch: event.patch
6507
- });
6508
- }),
6509
- "emit mutation event": xstate.emit(({
6510
- event
6511
- }) => (xstate.assertEvent(event, "mutation"), event)),
6512
- "emit read only": xstate.emit({
6513
- type: "read only"
6514
- }),
6515
- "emit editable": xstate.emit({
6516
- type: "editable"
6517
- }),
6518
- "defer event": xstate.assign({
6519
- pendingEvents: ({
6520
- context,
6521
- event
6522
- }) => (xstate.assertEvent(event, ["internal.patch", "mutation"]), [...context.pendingEvents, event])
6523
- }),
6524
- "emit pending events": xstate.enqueueActions(({
6525
- context,
6526
- enqueue
6527
- }) => {
6528
- for (const event of context.pendingEvents)
6529
- event.type === "internal.patch" ? (enqueue.emit(event), enqueue.emit({
6530
- type: "patch",
6531
- patch: event.patch
6532
- })) : enqueue.emit(event);
6533
- }),
6534
- "emit ready": xstate.emit({
6535
- type: "ready"
6536
- }),
6537
- "clear pending events": xstate.assign({
6538
- pendingEvents: []
6539
- }),
6540
- "handle behavior event": ({
6541
- context,
6542
- event,
6543
- self
6544
- }) => {
6545
- xstate.assertEvent(event, ["behavior event"]), performEvent({
6546
- behaviors: [...context.behaviors.values(), ...defaultBehaviors],
6547
- event: event.behaviorEvent,
6548
- editor: event.editor,
6549
- keyGenerator: context.keyGenerator,
6550
- schema: context.schema,
6551
- getSnapshot: () => createEditorSnapshot({
6552
- converters: [...context.converters],
6553
- editor: event.editor,
6554
- keyGenerator: context.keyGenerator,
6555
- readOnly: self.getSnapshot().matches({
6556
- "edit mode": "read only"
6557
- }),
6558
- schema: context.schema,
6559
- hasTag: (tag) => self.getSnapshot().hasTag(tag),
6560
- internalDrag: context.internalDrag
6561
- }),
6562
- nativeEvent: event.nativeEvent,
6563
- defaultActionCallback: event.type === "behavior event" ? event.defaultActionCallback : void 0
6563
+ const debug$2 = debugWithName("API:editable");
6564
+ function createEditableAPI(editor, editorActor) {
6565
+ const types2 = editorActor.getSnapshot().context.schema;
6566
+ return {
6567
+ focus: () => {
6568
+ editorActor.send({
6569
+ type: "behavior event",
6570
+ behaviorEvent: {
6571
+ type: "focus"
6572
+ },
6573
+ editor
6564
6574
  });
6565
- }
6566
- }
6567
- }).createMachine({
6568
- id: "editor",
6569
- context: ({
6570
- input
6571
- }) => ({
6572
- behaviors: /* @__PURE__ */ new Set([...input.behaviors ?? behavior_core.coreBehaviors]),
6573
- converters: new Set(input.converters ?? []),
6574
- keyGenerator: input.keyGenerator,
6575
- pendingEvents: [],
6576
- schema: input.schema,
6577
- selection: null,
6578
- initialReadOnly: input.readOnly ?? !1,
6579
- maxBlocks: input.maxBlocks,
6580
- value: input.value
6581
- }),
6582
- on: {
6583
- "notify.blurred": {
6584
- actions: xstate.emit(({
6585
- event
6586
- }) => ({
6587
- ...event,
6588
- type: "blurred"
6589
- }))
6590
- },
6591
- "notify.done loading": {
6592
- actions: xstate.emit({
6593
- type: "done loading"
6594
- })
6595
- },
6596
- "notify.error": {
6597
- actions: xstate.emit(({
6598
- event
6599
- }) => ({
6600
- ...event,
6601
- type: "error"
6602
- }))
6603
- },
6604
- "notify.invalid value": {
6605
- actions: xstate.emit(({
6606
- event
6607
- }) => ({
6608
- ...event,
6609
- type: "invalid value"
6610
- }))
6611
- },
6612
- "notify.focused": {
6613
- actions: xstate.emit(({
6614
- event
6615
- }) => ({
6616
- ...event,
6617
- type: "focused"
6618
- }))
6619
- },
6620
- "notify.selection": {
6621
- actions: [xstate.assign({
6622
- selection: ({
6623
- event
6624
- }) => event.selection
6625
- }), xstate.emit(({
6626
- event
6627
- }) => ({
6628
- ...event,
6629
- type: "selection"
6630
- }))]
6631
6575
  },
6632
- "notify.unset": {
6633
- actions: xstate.emit(({
6634
- event
6635
- }) => ({
6636
- ...event,
6637
- type: "unset"
6638
- }))
6576
+ blur: () => {
6577
+ editorActor.send({
6578
+ type: "behavior event",
6579
+ behaviorEvent: {
6580
+ type: "blur"
6581
+ },
6582
+ editor
6583
+ });
6639
6584
  },
6640
- "notify.loading": {
6641
- actions: xstate.emit({
6642
- type: "loading"
6643
- })
6585
+ toggleMark: (mark) => {
6586
+ editorActor.send({
6587
+ type: "behavior event",
6588
+ behaviorEvent: {
6589
+ type: "decorator.toggle",
6590
+ decorator: mark
6591
+ },
6592
+ editor
6593
+ });
6644
6594
  },
6645
- "notify.value changed": {
6646
- actions: xstate.emit(({
6647
- event
6648
- }) => ({
6649
- ...event,
6650
- type: "value changed"
6651
- }))
6595
+ toggleList: (listItem) => {
6596
+ editorActor.send({
6597
+ type: "behavior event",
6598
+ behaviorEvent: {
6599
+ type: "list item.toggle",
6600
+ listItem
6601
+ },
6602
+ editor
6603
+ });
6652
6604
  },
6653
- "add behavior": {
6654
- actions: "add behavior to context"
6605
+ toggleBlockStyle: (style) => {
6606
+ editorActor.send({
6607
+ type: "behavior event",
6608
+ behaviorEvent: {
6609
+ type: "style.toggle",
6610
+ style
6611
+ },
6612
+ editor
6613
+ });
6655
6614
  },
6656
- "remove behavior": {
6657
- actions: "remove behavior from context"
6615
+ isMarkActive: (mark) => {
6616
+ try {
6617
+ return isDecoratorActive({
6618
+ editor,
6619
+ decorator: mark
6620
+ });
6621
+ } catch (err) {
6622
+ return console.warn(err), !1;
6623
+ }
6658
6624
  },
6659
- patches: {
6660
- actions: xstate.emit(({
6661
- event
6662
- }) => event)
6625
+ marks: () => ({
6626
+ ...slate.Editor.marks(editor) || {}
6627
+ }).marks || [],
6628
+ undo: () => {
6629
+ editorActor.send({
6630
+ type: "behavior event",
6631
+ behaviorEvent: {
6632
+ type: "history.undo"
6633
+ },
6634
+ editor
6635
+ });
6663
6636
  },
6664
- "update behaviors": {
6665
- actions: "assign behaviors"
6637
+ redo: () => {
6638
+ editorActor.send({
6639
+ type: "behavior event",
6640
+ behaviorEvent: {
6641
+ type: "history.redo"
6642
+ },
6643
+ editor
6644
+ });
6666
6645
  },
6667
- "update key generator": {
6668
- actions: xstate.assign({
6669
- keyGenerator: ({
6670
- event
6671
- }) => event.keyGenerator
6672
- })
6646
+ select: (selection) => {
6647
+ const slateSelection = toSlateRange(selection, editor);
6648
+ slateSelection ? slate.Transforms.select(editor, slateSelection) : slate.Transforms.deselect(editor), editor.onChange();
6673
6649
  },
6674
- "update schema": {
6675
- actions: "assign schema"
6650
+ focusBlock: () => {
6651
+ if (editor.selection) {
6652
+ const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
6653
+ if (block)
6654
+ return fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
6655
+ }
6676
6656
  },
6677
- "update value": {
6678
- actions: xstate.assign({
6679
- value: ({
6680
- event
6681
- }) => event.value
6682
- })
6657
+ focusChild: () => {
6658
+ if (editor.selection) {
6659
+ const block = slate.Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
6660
+ if (block && editor.isTextBlock(block))
6661
+ return fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0].children[editor.selection.focus.path[1]];
6662
+ }
6683
6663
  },
6684
- "update maxBlocks": {
6685
- actions: xstate.assign({
6686
- maxBlocks: ({
6687
- event
6688
- }) => event.maxBlocks
6689
- })
6690
- }
6691
- },
6692
- type: "parallel",
6693
- states: {
6694
- "edit mode": {
6695
- initial: "read only",
6696
- states: {
6697
- "read only": {
6698
- initial: "determine initial edit mode",
6699
- on: {
6700
- "behavior event": {
6701
- actions: "handle behavior event",
6702
- guard: ({
6703
- event
6704
- }) => event.behaviorEvent.type === "clipboard.copy" || event.behaviorEvent.type === "mouse.click" || event.behaviorEvent.type === "serialize" || event.behaviorEvent.type === "serialization.failure" || event.behaviorEvent.type === "serialization.success" || event.behaviorEvent.type === "select"
6664
+ insertChild: (type, value) => {
6665
+ if (type.name !== types2.span.name)
6666
+ return editorActor.send({
6667
+ type: "behavior event",
6668
+ behaviorEvent: {
6669
+ type: "insert.inline object",
6670
+ inlineObject: {
6671
+ name: type.name,
6672
+ value
6705
6673
  }
6706
6674
  },
6707
- states: {
6708
- "determine initial edit mode": {
6709
- on: {
6710
- "done syncing initial value": [{
6711
- target: "#editor.edit mode.read only.read only",
6712
- guard: ({
6713
- context
6714
- }) => context.initialReadOnly
6715
- }, {
6716
- target: "#editor.edit mode.editable"
6717
- }]
6718
- }
6719
- },
6720
- "read only": {
6721
- on: {
6722
- "update readOnly": {
6723
- guard: ({
6724
- event
6725
- }) => !event.readOnly,
6726
- target: "#editor.edit mode.editable",
6727
- actions: ["emit editable"]
6728
- }
6729
- }
6730
- }
6731
- }
6675
+ editor
6676
+ }), editor.selection ? slateRangeToSelection({
6677
+ schema: editorActor.getSnapshot().context.schema,
6678
+ editor,
6679
+ range: editor.selection
6680
+ })?.focus.path ?? [] : [];
6681
+ if (!editor.selection)
6682
+ throw new Error("The editor has no selection");
6683
+ const [focusBlock] = Array.from(slate.Editor.nodes(editor, {
6684
+ at: editor.selection.focus.path.slice(0, 1),
6685
+ match: (n) => n._type === types2.block.name
6686
+ }))[0] || [void 0];
6687
+ if (!focusBlock)
6688
+ throw new Error("No focused text block");
6689
+ if (type.name !== types2.span.name && !types2.inlineObjects.some((t) => t.name === type.name))
6690
+ throw new Error("This type cannot be inserted as a child to a text block");
6691
+ const child = toSlateValue([{
6692
+ _key: editorActor.getSnapshot().context.keyGenerator(),
6693
+ _type: types2.block.name,
6694
+ children: [{
6695
+ _key: editorActor.getSnapshot().context.keyGenerator(),
6696
+ _type: type.name,
6697
+ ...value || {}
6698
+ }]
6699
+ }], {
6700
+ schemaTypes: editorActor.getSnapshot().context.schema
6701
+ })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types2.span.name, focusNode = slate.Node.get(editor, focusChildPath);
6702
+ return isSpanNode && focusNode._type !== types2.span.name && (debug$2("Inserting span child next to inline object child, moving selection + 1"), editor.move({
6703
+ distance: 1,
6704
+ unit: "character"
6705
+ })), slate.Transforms.insertNodes(editor, child, {
6706
+ select: !0,
6707
+ at: editor.selection
6708
+ }), editor.onChange(), editor.selection ? slateRangeToSelection({
6709
+ schema: editorActor.getSnapshot().context.schema,
6710
+ editor,
6711
+ range: editor.selection
6712
+ })?.focus.path ?? [] : [];
6713
+ },
6714
+ insertBlock: (type, value) => (editorActor.send({
6715
+ type: "behavior event",
6716
+ behaviorEvent: {
6717
+ type: "insert.block",
6718
+ block: {
6719
+ _type: type.name,
6720
+ ...value || {}
6732
6721
  },
6733
- editable: {
6734
- on: {
6735
- "update readOnly": {
6736
- guard: ({
6737
- event
6738
- }) => event.readOnly,
6739
- target: "#editor.edit mode.read only.read only",
6740
- actions: ["emit read only"]
6741
- },
6742
- "behavior event": {
6743
- actions: "handle behavior event"
6744
- }
6745
- },
6746
- initial: "idle",
6747
- states: {
6748
- idle: {
6749
- on: {
6750
- dragstart: {
6751
- actions: [xstate.assign({
6752
- internalDrag: ({
6753
- event
6754
- }) => ({
6755
- ghost: event.ghost,
6756
- origin: event.origin
6757
- })
6758
- })],
6759
- target: "dragging internally"
6760
- }
6761
- }
6762
- },
6763
- "dragging internally": {
6764
- exit: [({
6765
- context
6766
- }) => {
6767
- if (context.internalDrag?.ghost)
6768
- try {
6769
- context.internalDrag.ghost.parentNode?.removeChild(context.internalDrag.ghost);
6770
- } catch (error) {
6771
- console.error(new Error(`Removing the internal drag ghost failed due to: ${error.message}`));
6772
- }
6773
- }, xstate.assign({
6774
- internalDrag: void 0
6775
- })],
6776
- tags: ["dragging internally"],
6777
- on: {
6778
- dragend: {
6779
- target: "idle"
6780
- },
6781
- drop: {
6782
- target: "idle"
6783
- }
6784
- }
6785
- }
6722
+ placement: "auto"
6723
+ },
6724
+ editor
6725
+ }), editor.selection ? slateRangeToSelection({
6726
+ schema: editorActor.getSnapshot().context.schema,
6727
+ editor,
6728
+ range: editor.selection
6729
+ })?.focus.path ?? [] : []),
6730
+ hasBlockStyle: (style) => {
6731
+ try {
6732
+ return isStyleActive({
6733
+ editor,
6734
+ style
6735
+ });
6736
+ } catch {
6737
+ return !1;
6738
+ }
6739
+ },
6740
+ hasListStyle: (listItem) => {
6741
+ try {
6742
+ return isListItemActive({
6743
+ editor,
6744
+ listItem
6745
+ });
6746
+ } catch {
6747
+ return !1;
6748
+ }
6749
+ },
6750
+ isVoid: (element) => ![types2.block.name, types2.span.name].includes(element._type),
6751
+ findByPath: (path) => {
6752
+ const slatePath = toSlateRange({
6753
+ focus: {
6754
+ path,
6755
+ offset: 0
6756
+ },
6757
+ anchor: {
6758
+ path,
6759
+ offset: 0
6760
+ }
6761
+ }, editor);
6762
+ if (slatePath) {
6763
+ const [block, blockPath] = slate.Editor.node(editor, slatePath.focus.path.slice(0, 1));
6764
+ if (block && blockPath && typeof block._key == "string") {
6765
+ if (path.length === 1 && slatePath.focus.path.length === 1)
6766
+ return [fromSlateValue([block], types2.block.name)[0], [{
6767
+ _key: block._key
6768
+ }]];
6769
+ const ptBlock = fromSlateValue([block], types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
6770
+ if (editor.isTextBlock(ptBlock)) {
6771
+ const ptChild = ptBlock.children[slatePath.focus.path[1]];
6772
+ if (ptChild)
6773
+ return [ptChild, [{
6774
+ _key: block._key
6775
+ }, "children", {
6776
+ _key: ptChild._key
6777
+ }]];
6786
6778
  }
6787
6779
  }
6788
6780
  }
6781
+ return [void 0, void 0];
6789
6782
  },
6790
- setup: {
6791
- initial: "setting up",
6792
- states: {
6793
- "setting up": {
6794
- exit: ["emit ready"],
6795
- on: {
6796
- "internal.patch": {
6797
- actions: "defer event"
6798
- },
6799
- mutation: {
6800
- actions: "defer event"
6801
- },
6802
- "done syncing initial value": {
6803
- target: "pristine"
6804
- }
6805
- }
6806
- },
6807
- pristine: {
6808
- initial: "idle",
6809
- states: {
6810
- idle: {
6811
- on: {
6812
- normalizing: {
6813
- target: "normalizing"
6814
- },
6815
- "internal.patch": {
6816
- actions: "defer event",
6817
- target: "#editor.setup.dirty"
6818
- },
6819
- mutation: {
6820
- actions: "defer event",
6821
- target: "#editor.setup.dirty"
6822
- }
6823
- }
6783
+ findDOMNode: (element) => {
6784
+ let node;
6785
+ try {
6786
+ const [item] = Array.from(slate.Editor.nodes(editor, {
6787
+ at: [],
6788
+ match: (n) => n._key === element._key
6789
+ }) || [])[0] || [void 0];
6790
+ node = slateReact.ReactEditor.toDOMNode(editor, item);
6791
+ } catch {
6792
+ }
6793
+ return node;
6794
+ },
6795
+ activeAnnotations: () => {
6796
+ if (!editor.selection || editor.selection.focus.path.length < 2)
6797
+ return [];
6798
+ try {
6799
+ const activeAnnotations = [], spans = slate.Editor.nodes(editor, {
6800
+ at: editor.selection,
6801
+ match: (node) => slate.Text.isText(node) && node.marks !== void 0 && Array.isArray(node.marks) && node.marks.length > 0
6802
+ });
6803
+ for (const [span, path] of spans) {
6804
+ const [block] = slate.Editor.node(editor, path, {
6805
+ depth: 1
6806
+ });
6807
+ editor.isTextBlock(block) && block.markDefs?.forEach((def) => {
6808
+ slate.Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
6809
+ });
6810
+ }
6811
+ return activeAnnotations;
6812
+ } catch {
6813
+ return [];
6814
+ }
6815
+ },
6816
+ isAnnotationActive: (annotationType) => isAnnotationActive({
6817
+ editor,
6818
+ annotation: {
6819
+ name: annotationType
6820
+ }
6821
+ }),
6822
+ addAnnotation: (type, value) => {
6823
+ let paths;
6824
+ return slate.Editor.withoutNormalizing(editor, () => {
6825
+ paths = addAnnotationActionImplementation({
6826
+ context: {
6827
+ keyGenerator: editorActor.getSnapshot().context.keyGenerator,
6828
+ schema: types2
6829
+ },
6830
+ action: {
6831
+ annotation: {
6832
+ name: type.name,
6833
+ value: value ?? {}
6824
6834
  },
6825
- normalizing: {
6826
- on: {
6827
- "done normalizing": {
6828
- target: "idle"
6829
- },
6830
- "internal.patch": {
6831
- actions: "defer event"
6832
- },
6833
- mutation: {
6834
- actions: "defer event"
6835
- }
6836
- }
6837
- }
6835
+ editor
6838
6836
  }
6839
- },
6840
- dirty: {
6841
- entry: ["emit pending events", "clear pending events"],
6842
- on: {
6843
- "internal.patch": {
6844
- actions: "emit patch event"
6845
- },
6846
- mutation: {
6847
- actions: "emit mutation event"
6848
- }
6837
+ });
6838
+ }), editor.onChange(), paths;
6839
+ },
6840
+ delete: (selection, options) => {
6841
+ if (selection) {
6842
+ const range = toSlateRange(selection, editor);
6843
+ if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
6844
+ throw new Error("Invalid range");
6845
+ if (range) {
6846
+ if (!options?.mode || options?.mode === "selected") {
6847
+ debug$2("Deleting content in selection"), slate.Transforms.delete(editor, {
6848
+ at: range,
6849
+ hanging: !0,
6850
+ voids: !0
6851
+ }), editor.onChange();
6852
+ return;
6849
6853
  }
6854
+ options?.mode === "blocks" && (debug$2("Deleting blocks touched by selection"), slate.Transforms.removeNodes(editor, {
6855
+ at: range,
6856
+ voids: !0,
6857
+ match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && slate.Element.isElement(node)
6858
+ })), options?.mode === "children" && (debug$2("Deleting children touched by selection"), slate.Transforms.removeNodes(editor, {
6859
+ at: range,
6860
+ voids: !0,
6861
+ match: (node) => node._type === types2.span.name || // Text children
6862
+ !editor.isTextBlock(node) && slate.Element.isElement(node)
6863
+ })), editor.children.length === 0 && (editor.children = [editor.pteCreateTextBlock({
6864
+ decorators: []
6865
+ })]), editor.onChange();
6850
6866
  }
6851
6867
  }
6852
- }
6853
- }
6854
- });
6855
- function defaultCompare(a, b) {
6856
- return a === b;
6857
- }
6858
- function useEditorSelector(editor, selector, t0) {
6859
- const $ = reactCompilerRuntime.c(3), compare = t0 === void 0 ? defaultCompare : t0;
6860
- let t1;
6861
- return $[0] !== editor || $[1] !== selector ? (t1 = (editorActorSnapshot) => {
6862
- const snapshot = getEditorSnapshot({
6863
- editorActorSnapshot,
6864
- slateEditorInstance: editor._internal.slateEditor.instance
6865
- });
6866
- return selector(snapshot);
6867
- }, $[0] = editor, $[1] = selector, $[2] = t1) : t1 = $[2], react.useSelector(editor._internal.editorActor, t1, compare);
6868
- }
6869
- function getEditorSnapshot({
6870
- editorActorSnapshot,
6871
- slateEditorInstance
6872
- }) {
6873
- return {
6874
- context: {
6875
- converters: [...editorActorSnapshot.context.converters],
6876
- activeDecorators: getActiveDecorators({
6877
- schema: editorActorSnapshot.context.schema,
6878
- slateEditorInstance
6879
- }),
6880
- keyGenerator: editorActorSnapshot.context.keyGenerator,
6881
- readOnly: editorActorSnapshot.matches({
6882
- "edit mode": "read only"
6883
- }),
6884
- schema: editorActorSnapshot.context.schema,
6885
- selection: editorActorSnapshot.context.selection,
6886
- value: slateChildrenToBlocks(editorActorSnapshot.context.schema, slateEditorInstance.children)
6887
6868
  },
6888
- beta: {
6889
- hasTag: (tag) => editorActorSnapshot.hasTag(tag),
6890
- internalDrag: editorActorSnapshot.context.internalDrag
6869
+ removeAnnotation: (type) => {
6870
+ editorActor.send({
6871
+ type: "behavior event",
6872
+ behaviorEvent: {
6873
+ type: "annotation.remove",
6874
+ annotation: {
6875
+ name: type.name
6876
+ }
6877
+ },
6878
+ editor
6879
+ });
6880
+ },
6881
+ getSelection: () => {
6882
+ let ptRange = null;
6883
+ if (editor.selection) {
6884
+ const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
6885
+ if (existing)
6886
+ return existing;
6887
+ ptRange = slateRangeToSelection({
6888
+ schema: editorActor.getSnapshot().context.schema,
6889
+ editor,
6890
+ range: editor.selection
6891
+ }), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
6892
+ }
6893
+ return ptRange;
6894
+ },
6895
+ getValue: () => fromSlateValue(editor.children, types2.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
6896
+ isCollapsedSelection: () => !!editor.selection && slate.Range.isCollapsed(editor.selection),
6897
+ isExpandedSelection: () => !!editor.selection && slate.Range.isExpanded(editor.selection),
6898
+ insertBreak: () => {
6899
+ editor.insertBreak(), editor.onChange();
6900
+ },
6901
+ getFragment: () => fromSlateValue(editor.getFragment(), types2.block.name),
6902
+ isSelectionsOverlapping: (selectionA, selectionB) => {
6903
+ const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
6904
+ return slate.Range.isRange(rangeA) && slate.Range.isRange(rangeB) && slate.Range.includes(rangeA, rangeB);
6891
6905
  }
6892
6906
  };
6893
6907
  }
6908
+ function isAnnotationActive({
6909
+ editor,
6910
+ annotation
6911
+ }) {
6912
+ if (!editor.selection || editor.selection.focus.path.length < 2)
6913
+ return !1;
6914
+ try {
6915
+ const spans = [...slate.Editor.nodes(editor, {
6916
+ at: editor.selection,
6917
+ match: (node) => slate.Text.isText(node)
6918
+ })];
6919
+ if (spans.length === 0 || spans.some(([span]) => !types.isPortableTextSpan(span) || !span.marks || span.marks?.length === 0)) return !1;
6920
+ const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
6921
+ const [block] = slate.Editor.node(editor, path, {
6922
+ depth: 1
6923
+ });
6924
+ return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
6925
+ }, []);
6926
+ return spans.every(([span]) => types.isPortableTextSpan(span) ? span.marks?.map((markKey) => selectionMarkDefs.find((def) => def?._key === markKey)?._type)?.includes(annotation.name) : !1);
6927
+ } catch {
6928
+ return !1;
6929
+ }
6930
+ }
6894
6931
  function createInternalEditor(config) {
6895
6932
  const editorActor = xstate.createActor(editorMachine, {
6896
6933
  input: editorConfigToMachineInput(config)
@@ -6999,7 +7036,12 @@ function createInternalEditorFromActor(editorActor) {
6999
7036
  }
7000
7037
  };
7001
7038
  }
7002
- const PortableTextEditorSelectionContext = React.createContext(null), usePortableTextEditorSelection = () => {
7039
+ const EditorActorContext = React.createContext({}), PortableTextEditorContext = React.createContext(null), usePortableTextEditor = () => {
7040
+ const editor = React.useContext(PortableTextEditorContext);
7041
+ if (!editor)
7042
+ throw new Error("The `usePortableTextEditor` hook must be used inside the <PortableTextEditor> component's context.");
7043
+ return editor;
7044
+ }, PortableTextEditorSelectionContext = React.createContext(null), usePortableTextEditorSelection = () => {
7003
7045
  const selection = React.useContext(PortableTextEditorSelectionContext);
7004
7046
  if (selection === void 0)
7005
7047
  throw new Error("The `usePortableTextEditorSelection` hook must be used inside the <PortableTextEditor> component's context.");