@portabletext/editor 1.47.6 → 1.47.8

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.
@@ -1,8 +1,8 @@
1
1
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import { c } from "react-compiler-runtime";
3
- import React, { useEffect, useMemo, createContext, useContext, useState, startTransition, Component } from "react";
4
- import { withReact, ReactEditor, Slate } from "slate-react";
5
2
  import { useSelector, useActorRef } from "@xstate/react";
3
+ import React, { useEffect, createContext, useContext, useState, startTransition, Component, useMemo } from "react";
4
+ import { withReact, ReactEditor, Slate } from "slate-react";
5
+ import { c } from "react-compiler-runtime";
6
6
  import debug$g from "debug";
7
7
  import isEqual from "lodash/isEqual.js";
8
8
  import { Element, Text, Editor, Path, Operation, Transforms, Node, Range, Point, createEditor } from "slate";
@@ -14,7 +14,7 @@ import isPlainObject from "lodash/isPlainObject.js";
14
14
  import uniq from "lodash/uniq.js";
15
15
  import getRandomValues from "get-random-values-esm";
16
16
  import { parseBlock, parseAnnotation, isTextBlock, parseInlineObject } from "./parse-blocks.js";
17
- import { sliceBlocks, blockOffsetToSpanSelectionPoint, getBlockEndPoint, getBlockStartPoint, getTextBlockText } from "./util.slice-blocks.js";
17
+ import { sliceBlocks, blockOffsetToSpanSelectionPoint, isEmptyTextBlock, getBlockEndPoint, getBlockStartPoint, getTextBlockText } from "./util.slice-blocks.js";
18
18
  import { htmlToBlocks } from "@portabletext/block-tools";
19
19
  import { toHTML } from "@portabletext/to-html";
20
20
  import { Schema } from "@sanity/schema";
@@ -25,9 +25,9 @@ import omit from "lodash/omit.js";
25
25
  import { selectionPointToBlockOffset, blockOffsetsToSelection } from "./util.selection-point-to-block-offset.js";
26
26
  import { getTrimmedSelection, isActiveAnnotation, isActiveDecorator, getSelectedTextBlocks, isActiveListItem, isActiveStyle, isSelectingEntireBlocks, getActiveAnnotations } from "./selector.is-selecting-entire-blocks.js";
27
27
  import { DOMEditor } from "slate-dom";
28
+ import startCase from "lodash.startcase";
28
29
  import { defineBehavior, raise, coreBehaviors } from "./behavior.core.js";
29
30
  import { getFocusTextBlock, getPreviousBlock, getNextBlock, getFocusSpan, isSelectionCollapsed, isOverlappingSelection, getSelectedBlocks, isSelectionExpanded } from "./selector.is-overlapping-selection.js";
30
- import startCase from "lodash.startcase";
31
31
  import { Subject } from "rxjs";
32
32
  import { useEffectEvent } from "use-effect-event";
33
33
  const rootName = "sanity-pte:";
@@ -5070,2173 +5070,2178 @@ function createSlateEditor(config) {
5070
5070
  };
5071
5071
  return slateEditors.set(config.editorActor, slateEditor), slateEditor;
5072
5072
  }
5073
- const abstractAnnotationBehaviors = [defineBehavior({
5074
- on: "annotation.toggle",
5075
- guard: ({
5076
- snapshot,
5077
- event
5078
- }) => isActiveAnnotation(event.annotation.name)(snapshot),
5079
- actions: [({
5080
- event
5081
- }) => [raise({
5082
- type: "annotation.remove",
5083
- annotation: event.annotation
5084
- })]]
5085
- }), defineBehavior({
5086
- on: "annotation.toggle",
5087
- guard: ({
5088
- snapshot,
5089
- event
5090
- }) => !isActiveAnnotation(event.annotation.name)(snapshot),
5091
- actions: [({
5092
- event
5093
- }) => [raise({
5094
- type: "annotation.add",
5095
- annotation: event.annotation
5096
- })]]
5097
- })], abstractDecoratorBehaviors = [defineBehavior({
5098
- on: "decorator.toggle",
5099
- guard: ({
5100
- snapshot,
5101
- event
5102
- }) => isActiveDecorator(event.decorator)(snapshot),
5103
- actions: [({
5104
- event
5105
- }) => [raise({
5106
- type: "decorator.remove",
5107
- decorator: event.decorator
5108
- })]]
5109
- }), defineBehavior({
5110
- on: "decorator.toggle",
5111
- guard: ({
5112
- snapshot,
5113
- event
5114
- }) => {
5115
- const manualSelection = event.at ? blockOffsetsToSelection({
5116
- value: snapshot.context.value,
5117
- offsets: event.at
5118
- }) : null;
5119
- return manualSelection ? !isActiveDecorator(event.decorator)({
5120
- ...snapshot,
5121
- context: {
5122
- ...snapshot.context,
5123
- selection: manualSelection
5073
+ function createLegacySchema(portableTextType) {
5074
+ if (!portableTextType)
5075
+ throw new Error("Parameter 'portabletextType' missing (required)");
5076
+ const blockType = portableTextType.of?.find(findBlockType);
5077
+ if (!blockType)
5078
+ throw new Error("Block type is not defined in this schema (required)");
5079
+ const childrenField = blockType.fields?.find((field) => field.name === "children");
5080
+ if (!childrenField)
5081
+ throw new Error("Children field for block type found in schema (required)");
5082
+ const ofType = childrenField.type.of;
5083
+ if (!ofType)
5084
+ throw new Error("Valid types for block children not found in schema (required)");
5085
+ const spanType = ofType.find((memberType) => memberType.name === "span");
5086
+ if (!spanType)
5087
+ throw new Error("Span type not found in schema (required)");
5088
+ const inlineObjectTypes = ofType.filter((memberType) => memberType.name !== "span") || [], blockObjectTypes = portableTextType.of?.filter((field) => field.name !== blockType.name) || [];
5089
+ return {
5090
+ styles: resolveEnabledStyles(blockType),
5091
+ decorators: resolveEnabledDecorators(spanType),
5092
+ lists: resolveEnabledListItems(blockType),
5093
+ block: blockType,
5094
+ span: spanType,
5095
+ portableText: portableTextType,
5096
+ inlineObjects: inlineObjectTypes,
5097
+ blockObjects: blockObjectTypes,
5098
+ annotations: spanType.annotations
5099
+ };
5100
+ }
5101
+ function resolveEnabledStyles(blockType) {
5102
+ const styleField = blockType.fields?.find((btField) => btField.name === "style");
5103
+ if (!styleField)
5104
+ throw new Error("A field with name 'style' is not defined in the block type (required).");
5105
+ const textStyles = styleField.type.options?.list && styleField.type.options.list?.filter((style) => style.value);
5106
+ if (!textStyles || textStyles.length === 0)
5107
+ throw new Error("The style fields need at least one style defined. I.e: {title: 'Normal', value: 'normal'}.");
5108
+ return textStyles;
5109
+ }
5110
+ function resolveEnabledDecorators(spanType) {
5111
+ return spanType.decorators;
5112
+ }
5113
+ function resolveEnabledListItems(blockType) {
5114
+ const listField = blockType.fields?.find((btField) => btField.name === "listItem");
5115
+ if (!listField)
5116
+ throw new Error("A field with name 'listItem' is not defined in the block type (required).");
5117
+ const listItems = listField.type.options?.list && listField.type.options.list.filter((list) => list.value);
5118
+ if (!listItems)
5119
+ throw new Error("The list field need at least to be an empty array");
5120
+ return listItems;
5121
+ }
5122
+ function findBlockType(type) {
5123
+ return type.type ? findBlockType(type.type) : type.name === "block" ? type : null;
5124
+ }
5125
+ function defineSchema(definition) {
5126
+ return definition;
5127
+ }
5128
+ const temporaryImageName = `tmp-${defaultKeyGenerator()}-image`, temporaryUrlName = `tmp-${defaultKeyGenerator()}-url`, temporaryObjectNames = {
5129
+ image: temporaryImageName,
5130
+ url: temporaryUrlName
5131
+ }, objectNames = {
5132
+ [temporaryImageName]: "image",
5133
+ [temporaryUrlName]: "url"
5134
+ }, defaultObjectTitles = {
5135
+ image: "Image",
5136
+ url: "URL"
5137
+ };
5138
+ function legacySchemaToEditorSchema(schema) {
5139
+ return {
5140
+ annotations: schema.annotations.map((annotation) => ({
5141
+ name: annotation.name,
5142
+ fields: annotation.fields.map((field) => ({
5143
+ name: field.name,
5144
+ type: field.type.jsonType
5145
+ })),
5146
+ title: annotation.title
5147
+ })),
5148
+ block: {
5149
+ name: schema.block.name
5150
+ },
5151
+ blockObjects: schema.blockObjects.map((blockObject) => ({
5152
+ name: blockObject.name,
5153
+ fields: blockObject.fields.map((field) => ({
5154
+ name: field.name,
5155
+ type: field.type.jsonType
5156
+ })),
5157
+ title: blockObject.title
5158
+ })),
5159
+ decorators: schema.decorators.map((decorator) => ({
5160
+ name: decorator.value,
5161
+ title: decorator.title,
5162
+ value: decorator.value
5163
+ })),
5164
+ inlineObjects: schema.inlineObjects.map((inlineObject) => ({
5165
+ name: inlineObject.name,
5166
+ fields: inlineObject.fields.map((field) => ({
5167
+ name: field.name,
5168
+ type: field.type.jsonType
5169
+ })),
5170
+ title: inlineObject.title
5171
+ })),
5172
+ span: {
5173
+ name: schema.span.name
5174
+ },
5175
+ styles: schema.styles.map((style) => ({
5176
+ name: style.value,
5177
+ title: style.title,
5178
+ value: style.value
5179
+ })),
5180
+ lists: schema.lists.map((list) => ({
5181
+ name: list.value,
5182
+ title: list.title,
5183
+ value: list.value
5184
+ }))
5185
+ };
5186
+ }
5187
+ function compileSchemaDefinitionToLegacySchema(definition) {
5188
+ const blockObjects = definition?.blockObjects?.map((blockObject) => defineType({
5189
+ type: "object",
5190
+ // Very naive way to work around `SanitySchema.compile` adding default
5191
+ // fields to objects with certain names.
5192
+ name: temporaryObjectNames[blockObject.name] ?? blockObject.name,
5193
+ title: blockObject.title === void 0 ? (
5194
+ // This avoids the default title which is a title case of the object name
5195
+ defaultObjectTitles[blockObject.name]
5196
+ ) : blockObject.title,
5197
+ fields: blockObject.fields?.map((field) => ({
5198
+ name: field.name,
5199
+ type: field.type
5200
+ })) ?? []
5201
+ })) ?? [], inlineObjects = definition?.inlineObjects?.map((inlineObject) => defineType({
5202
+ type: "object",
5203
+ // Very naive way to work around `SanitySchema.compile` adding default
5204
+ // fields to objects with certain names.
5205
+ name: temporaryObjectNames[inlineObject.name] ?? inlineObject.name,
5206
+ title: inlineObject.title === void 0 ? (
5207
+ // This avoids the default title which is a title case of the object name
5208
+ defaultObjectTitles[inlineObject.name]
5209
+ ) : inlineObject.title,
5210
+ fields: inlineObject.fields?.map((field) => ({
5211
+ name: field.name,
5212
+ type: field.type
5213
+ })) ?? []
5214
+ })) ?? [], portableTextSchema = defineField({
5215
+ type: "array",
5216
+ name: "portable-text",
5217
+ of: [...blockObjects.map((blockObject) => ({
5218
+ type: blockObject.name
5219
+ })), {
5220
+ type: "block",
5221
+ name: "block",
5222
+ of: inlineObjects.map((inlineObject) => ({
5223
+ type: inlineObject.name
5224
+ })),
5225
+ marks: {
5226
+ decorators: definition?.decorators?.map((decorator) => ({
5227
+ title: decorator.title ?? startCase(decorator.name),
5228
+ value: decorator.name
5229
+ })) ?? [],
5230
+ annotations: definition?.annotations?.map((annotation) => ({
5231
+ name: annotation.name,
5232
+ type: "object",
5233
+ title: annotation.title,
5234
+ fields: annotation.fields?.map((field) => ({
5235
+ name: field.name,
5236
+ type: field.type
5237
+ })) ?? []
5238
+ })) ?? []
5239
+ },
5240
+ lists: definition?.lists?.map((list) => ({
5241
+ value: list.name,
5242
+ title: list.title ?? startCase(list.name)
5243
+ })) ?? [],
5244
+ styles: definition?.styles?.map((style) => ({
5245
+ value: style.name,
5246
+ title: style.title ?? startCase(style.name)
5247
+ })) ?? []
5248
+ }]
5249
+ }), schema = Schema.compile({
5250
+ types: [portableTextSchema, ...blockObjects, ...inlineObjects]
5251
+ }).get("portable-text"), pteSchema = createLegacySchema(schema);
5252
+ return {
5253
+ ...pteSchema,
5254
+ blockObjects: pteSchema.blockObjects.map((blockObject) => objectNames[blockObject.name] !== void 0 ? {
5255
+ ...blockObject,
5256
+ name: objectNames[blockObject.name],
5257
+ type: {
5258
+ ...blockObject.type,
5259
+ name: objectNames[blockObject.name]
5124
5260
  }
5125
- }) : !isActiveDecorator(event.decorator)(snapshot);
5126
- },
5127
- actions: [({
5128
- event
5129
- }) => [raise({
5130
- ...event,
5131
- type: "decorator.add"
5132
- })]]
5133
- })], abstractDeleteBehaviors = [defineBehavior({
5134
- on: "delete.text",
5135
- guard: ({
5136
- snapshot,
5137
- event
5138
- }) => {
5139
- const selection = blockOffsetsToSelection({
5140
- value: snapshot.context.value,
5141
- offsets: event.at
5142
- });
5143
- if (!selection)
5144
- return !1;
5145
- const trimmedSelection = getTrimmedSelection({
5146
- context: {
5147
- converters: [],
5148
- schema: snapshot.context.schema,
5149
- keyGenerator: snapshot.context.keyGenerator,
5150
- activeDecorators: [],
5151
- readOnly: !1,
5152
- value: snapshot.context.value,
5153
- selection
5154
- }
5155
- });
5156
- return trimmedSelection ? {
5157
- selection: trimmedSelection
5158
- } : !1;
5159
- },
5160
- actions: [(_, {
5161
- selection
5162
- }) => [raise({
5163
- type: "delete",
5164
- at: selection
5165
- })]]
5166
- })], abstractInsertBehaviors = [defineBehavior({
5167
- on: "insert.blocks",
5168
- guard: ({
5169
- event
5170
- }) => event.placement === "before",
5171
- actions: [({
5172
- event
5173
- }) => event.blocks.map((block, index) => raise({
5174
- type: "insert.block",
5175
- block,
5176
- placement: index === 0 ? "before" : "after",
5177
- select: "end"
5178
- }))]
5179
- }), defineBehavior({
5180
- on: "insert.blocks",
5181
- guard: ({
5182
- event
5183
- }) => event.placement === "after",
5184
- actions: [({
5185
- event
5186
- }) => event.blocks.map((block) => raise({
5187
- type: "insert.block",
5188
- block,
5189
- placement: "after",
5190
- select: "end"
5191
- }))]
5192
- }), defineBehavior({
5193
- on: "insert.blocks",
5194
- guard: ({
5195
- snapshot,
5196
- event
5197
- }) => !(event.placement !== "auto" || !getFocusTextBlock(snapshot)),
5198
- actions: [({
5199
- event
5200
- }) => event.blocks.length === 1 ? [raise({
5201
- type: "insert.block",
5202
- block: event.blocks[0],
5203
- placement: "auto",
5204
- select: "end"
5205
- })] : event.blocks.flatMap((block, index) => index === 0 ? [raise({
5206
- type: "split.block"
5207
- }), raise({
5208
- type: "select.previous block",
5209
- select: "end"
5210
- }), raise({
5211
- type: "insert.block",
5212
- block,
5213
- placement: "auto",
5214
- select: "end"
5215
- })] : index === event.blocks.length - 1 ? [raise({
5216
- type: "select.next block",
5217
- select: "start"
5218
- }), raise({
5219
- type: "insert.block",
5220
- block,
5221
- placement: "auto",
5222
- select: "end"
5223
- })] : [raise({
5224
- type: "insert.block",
5225
- block,
5226
- placement: "after",
5227
- select: "end"
5228
- })])]
5229
- }), defineBehavior({
5230
- on: "insert.blocks",
5231
- guard: ({
5232
- event
5233
- }) => event.placement === "auto",
5234
- actions: [({
5235
- event
5236
- }) => event.blocks.map((block, index) => raise({
5237
- type: "insert.block",
5238
- block,
5239
- placement: index === 0 ? "auto" : "after",
5240
- select: "end"
5241
- }))]
5242
- }), defineBehavior({
5243
- on: "insert.break",
5244
- actions: [() => [raise({
5245
- type: "split.block"
5246
- })]]
5247
- }), defineBehavior({
5248
- on: "insert.soft break",
5249
- actions: [() => [raise({
5250
- type: "insert.text",
5251
- text: `
5252
- `
5253
- })]]
5254
- })], abstractListItemBehaviors = [defineBehavior({
5255
- on: "list item.add",
5256
- guard: ({
5257
- snapshot
5258
- }) => ({
5259
- selectedTextBlocks: getSelectedTextBlocks(snapshot)
5260
- }),
5261
- actions: [({
5262
- event
5263
- }, {
5264
- selectedTextBlocks
5265
- }) => selectedTextBlocks.map((block) => raise({
5266
- type: "block.set",
5267
- at: block.path,
5268
- props: {
5269
- level: 1,
5270
- listItem: event.listItem
5271
- }
5272
- }))]
5273
- }), defineBehavior({
5274
- on: "list item.remove",
5275
- guard: ({
5276
- snapshot
5277
- }) => ({
5278
- selectedTextBlocks: getSelectedTextBlocks(snapshot)
5279
- }),
5280
- actions: [(_, {
5281
- selectedTextBlocks
5282
- }) => selectedTextBlocks.map((block) => raise({
5283
- type: "block.unset",
5284
- at: block.path,
5285
- props: ["level", "listItem"]
5286
- }))]
5287
- }), defineBehavior({
5288
- on: "list item.toggle",
5289
- guard: ({
5290
- snapshot,
5291
- event
5292
- }) => isActiveListItem(event.listItem)(snapshot),
5293
- actions: [({
5294
- event
5295
- }) => [raise({
5296
- type: "list item.remove",
5297
- listItem: event.listItem
5298
- })]]
5299
- }), defineBehavior({
5300
- on: "list item.toggle",
5301
- guard: ({
5302
- snapshot,
5303
- event
5304
- }) => !isActiveListItem(event.listItem)(snapshot),
5305
- actions: [({
5306
- event
5307
- }) => [raise({
5308
- type: "list item.add",
5309
- listItem: event.listItem
5310
- })]]
5311
- })], abstractMoveBehaviors = [defineBehavior({
5312
- on: "move.block up",
5313
- guard: ({
5314
- snapshot,
5315
- event
5316
- }) => {
5317
- const previousBlock = getPreviousBlock({
5318
- context: {
5319
- ...snapshot.context,
5320
- selection: {
5321
- anchor: {
5322
- path: event.at,
5323
- offset: 0
5324
- },
5325
- focus: {
5326
- path: event.at,
5327
- offset: 0
5328
- }
5329
- }
5330
- }
5331
- });
5332
- return previousBlock ? {
5333
- previousBlock
5334
- } : !1;
5335
- },
5336
- actions: [({
5337
- event
5338
- }, {
5339
- previousBlock
5340
- }) => [raise({
5341
- type: "move.block",
5342
- at: event.at,
5343
- to: previousBlock.path
5344
- })]]
5345
- }), defineBehavior({
5346
- on: "move.block down",
5347
- guard: ({
5348
- snapshot,
5349
- event
5350
- }) => {
5351
- const nextBlock = getNextBlock({
5352
- context: {
5353
- ...snapshot.context,
5354
- selection: {
5355
- anchor: {
5356
- path: event.at,
5357
- offset: 0
5358
- },
5359
- focus: {
5360
- path: event.at,
5361
- offset: 0
5362
- }
5363
- }
5364
- }
5365
- });
5366
- return nextBlock ? {
5367
- nextBlock
5368
- } : !1;
5369
- },
5370
- actions: [({
5371
- event
5372
- }, {
5373
- nextBlock
5374
- }) => [raise({
5375
- type: "move.block",
5376
- at: event.at,
5377
- to: nextBlock.path
5378
- })]]
5379
- })], abstractSelectBehaviors = [defineBehavior({
5380
- on: "select.previous block",
5381
- guard: ({
5382
- snapshot,
5383
- event
5384
- }) => {
5385
- const previousBlock = getPreviousBlock(snapshot);
5386
- if (!previousBlock)
5387
- return !1;
5388
- const point = event.select === "end" ? getBlockEndPoint(previousBlock) : getBlockStartPoint(previousBlock);
5389
- return {
5390
- selection: {
5391
- anchor: point,
5392
- focus: point
5393
- }
5394
- };
5395
- },
5396
- actions: [(_, {
5397
- selection
5398
- }) => [raise({
5399
- type: "select",
5400
- at: selection
5401
- })]]
5402
- }), defineBehavior({
5403
- on: "select.next block",
5404
- guard: ({
5405
- snapshot,
5406
- event
5407
- }) => {
5408
- const nextBlock = getNextBlock(snapshot);
5409
- if (!nextBlock)
5410
- return !1;
5411
- const point = event.select === "end" ? getBlockEndPoint(nextBlock) : getBlockStartPoint(nextBlock);
5412
- return {
5413
- selection: {
5414
- anchor: point,
5415
- focus: point
5416
- }
5417
- };
5418
- },
5419
- actions: [(_, {
5420
- selection
5421
- }) => [raise({
5422
- type: "select",
5423
- at: selection
5424
- })]]
5425
- })], abstractStyleBehaviors = [defineBehavior({
5426
- on: "style.add",
5427
- guard: ({
5428
- snapshot
5429
- }) => ({
5430
- selectedTextBlocks: getSelectedTextBlocks(snapshot)
5431
- }),
5432
- actions: [({
5433
- event
5434
- }, {
5435
- selectedTextBlocks
5436
- }) => selectedTextBlocks.map((block) => raise({
5437
- type: "block.set",
5438
- at: block.path,
5439
- props: {
5440
- style: event.style
5261
+ } : blockObject),
5262
+ inlineObjects: pteSchema.inlineObjects.map((inlineObject) => objectNames[inlineObject.name] !== void 0 ? {
5263
+ ...inlineObject,
5264
+ name: objectNames[inlineObject.name]
5265
+ } : inlineObject)
5266
+ };
5267
+ }
5268
+ function slateChildrenToBlocks(schema, value) {
5269
+ const blocks = new Array(value.length);
5270
+ for (let blockIndex = 0; blockIndex < value.length; blockIndex++) {
5271
+ const descendant = value[blockIndex];
5272
+ if (descendant._type !== schema.block.name) {
5273
+ blocks[blockIndex] = {
5274
+ _key: descendant._key,
5275
+ _type: descendant._type,
5276
+ ..."value" in descendant && typeof descendant.value == "object" ? descendant.value : {}
5277
+ };
5278
+ continue;
5441
5279
  }
5442
- }))]
5443
- }), defineBehavior({
5444
- on: "style.remove",
5445
- guard: ({
5446
- snapshot
5447
- }) => ({
5448
- selectedTextBlocks: getSelectedTextBlocks(snapshot)
5449
- }),
5450
- actions: [(_, {
5451
- selectedTextBlocks
5452
- }) => selectedTextBlocks.map((block) => raise({
5453
- type: "block.unset",
5454
- at: block.path,
5455
- props: ["style"]
5456
- }))]
5457
- }), defineBehavior({
5458
- on: "style.toggle",
5459
- guard: ({
5460
- snapshot,
5461
- event
5462
- }) => isActiveStyle(event.style)(snapshot),
5463
- actions: [({
5464
- event
5465
- }) => [raise({
5466
- type: "style.remove",
5467
- style: event.style
5468
- })]]
5469
- }), defineBehavior({
5470
- on: "style.toggle",
5471
- guard: ({
5472
- snapshot,
5473
- event
5474
- }) => !isActiveStyle(event.style)(snapshot),
5475
- actions: [({
5476
- event
5477
- }) => [raise({
5478
- type: "style.add",
5479
- style: event.style
5480
- })]]
5481
- })], keyIs = {
5482
- lineBreak: (event) => event.key === "Enter" && event.shiftKey
5483
- }, raiseInsertSoftBreak = defineBehavior({
5484
- on: "keyboard.keydown",
5485
- guard: ({
5486
- event
5487
- }) => keyIs.lineBreak(event.originEvent),
5488
- actions: [() => [raise({
5489
- type: "insert.soft break"
5490
- })]]
5491
- }), raiseDeserializationSuccessOrFailure = defineBehavior({
5492
- on: "deserialize",
5493
- guard: ({
5494
- snapshot,
5495
- event
5496
- }) => {
5497
- let success;
5498
- const failures = [];
5499
- for (const converter of snapshot.context.converters) {
5500
- const data = event.originEvent.originEvent.dataTransfer.getData(converter.mimeType);
5501
- if (!data)
5502
- continue;
5503
- const deserializeEvent = converter.deserialize({
5504
- snapshot,
5505
- event: {
5506
- type: "deserialize",
5507
- data
5508
- }
5509
- });
5510
- if (deserializeEvent.type === "deserialization.success") {
5511
- success = deserializeEvent;
5512
- break;
5513
- } else
5514
- failures.push(deserializeEvent);
5280
+ const children = "children" in descendant ? descendant.children : [], processedChildren = new Array(children.length);
5281
+ for (let childIndex = 0; childIndex < children.length; childIndex++) {
5282
+ const child = children[childIndex];
5283
+ processedChildren[childIndex] = child._type === schema.span.name ? child : {
5284
+ _key: child._key,
5285
+ _type: child._type,
5286
+ ..."value" in child && typeof child.value == "object" ? child.value : {}
5287
+ };
5515
5288
  }
5516
- return success || {
5517
- type: "deserialization.failure",
5518
- mimeType: "*/*",
5519
- reason: failures.map((failure) => failure.reason).join(", ")
5289
+ blocks[blockIndex] = {
5290
+ ...descendant,
5291
+ children: processedChildren
5520
5292
  };
5521
- },
5522
- actions: [({
5523
- event
5524
- }, deserializeEvent) => [raise({
5525
- ...deserializeEvent,
5526
- originEvent: event.originEvent
5527
- })]]
5528
- }), raiseSerializationSuccessOrFailure = defineBehavior({
5529
- on: "serialize",
5530
- guard: ({
5531
- snapshot,
5532
- event
5533
- }) => {
5534
- if (snapshot.context.converters.length === 0)
5535
- return !1;
5536
- const serializeEvents = snapshot.context.converters.map((converter) => converter.serialize({
5537
- snapshot,
5538
- event: {
5539
- ...event,
5540
- originEvent: event.originEvent.type
5541
- }
5542
- }));
5543
- return serializeEvents.length === 0 ? !1 : serializeEvents;
5544
- },
5545
- actions: [({
5546
- event
5547
- }, serializeEvents) => serializeEvents.map((serializeEvent) => raise({
5548
- ...serializeEvent,
5549
- originEvent: event.originEvent
5550
- }))]
5551
- }), defaultBehaviors = [
5552
- defineBehavior({
5553
- on: "clipboard.copy",
5554
- guard: ({
5555
- snapshot
5556
- }) => {
5557
- const focusSpan = getFocusSpan(snapshot), selectionCollapsed = isSelectionCollapsed(snapshot);
5558
- return focusSpan && selectionCollapsed;
5293
+ }
5294
+ return blocks;
5295
+ }
5296
+ function getActiveDecorators({
5297
+ schema,
5298
+ slateEditorInstance
5299
+ }) {
5300
+ const decorators = schema.decorators.map((decorator) => decorator.name);
5301
+ return ({
5302
+ ...Editor.marks(slateEditorInstance) ?? {}
5303
+ }.marks ?? []).filter((mark) => decorators.includes(mark));
5304
+ }
5305
+ function defaultCompare(a, b) {
5306
+ return a === b;
5307
+ }
5308
+ function useEditorSelector(editor, selector, t0) {
5309
+ const $ = c(3), compare = t0 === void 0 ? defaultCompare : t0;
5310
+ let t1;
5311
+ return $[0] !== editor || $[1] !== selector ? (t1 = (editorActorSnapshot) => {
5312
+ const snapshot = getEditorSnapshot({
5313
+ editorActorSnapshot,
5314
+ slateEditorInstance: editor._internal.slateEditor.instance
5315
+ });
5316
+ return selector(snapshot);
5317
+ }, $[0] = editor, $[1] = selector, $[2] = t1) : t1 = $[2], useSelector(editor._internal.editorActor, t1, compare);
5318
+ }
5319
+ function getEditorSnapshot({
5320
+ editorActorSnapshot,
5321
+ slateEditorInstance
5322
+ }) {
5323
+ return {
5324
+ context: {
5325
+ converters: [...editorActorSnapshot.context.converters],
5326
+ activeDecorators: getActiveDecorators({
5327
+ schema: editorActorSnapshot.context.schema,
5328
+ slateEditorInstance
5329
+ }),
5330
+ keyGenerator: editorActorSnapshot.context.keyGenerator,
5331
+ readOnly: editorActorSnapshot.matches({
5332
+ "edit mode": "read only"
5333
+ }),
5334
+ schema: editorActorSnapshot.context.schema,
5335
+ selection: editorActorSnapshot.context.selection,
5336
+ value: slateChildrenToBlocks(editorActorSnapshot.context.schema, slateEditorInstance.children)
5337
+ },
5338
+ beta: {
5339
+ hasTag: (tag) => editorActorSnapshot.hasTag(tag),
5340
+ internalDrag: editorActorSnapshot.context.internalDrag
5341
+ }
5342
+ };
5343
+ }
5344
+ const debug$3 = debugWithName("API:editable");
5345
+ function createEditableAPI(editor, editorActor) {
5346
+ const types = editorActor.getSnapshot().context.schema;
5347
+ return {
5348
+ focus: () => {
5349
+ editorActor.send({
5350
+ type: "focus",
5351
+ editor
5352
+ });
5353
+ },
5354
+ blur: () => {
5355
+ editorActor.send({
5356
+ type: "blur",
5357
+ editor
5358
+ });
5359
+ },
5360
+ toggleMark: (mark) => {
5361
+ editorActor.send({
5362
+ type: "behavior event",
5363
+ behaviorEvent: {
5364
+ type: "decorator.toggle",
5365
+ decorator: mark
5366
+ },
5367
+ editor
5368
+ });
5369
+ },
5370
+ toggleList: (listItem) => {
5371
+ editorActor.send({
5372
+ type: "behavior event",
5373
+ behaviorEvent: {
5374
+ type: "list item.toggle",
5375
+ listItem
5376
+ },
5377
+ editor
5378
+ });
5379
+ },
5380
+ toggleBlockStyle: (style) => {
5381
+ editorActor.send({
5382
+ type: "behavior event",
5383
+ behaviorEvent: {
5384
+ type: "style.toggle",
5385
+ style
5386
+ },
5387
+ editor
5388
+ });
5389
+ },
5390
+ isMarkActive: (mark) => {
5391
+ try {
5392
+ return isDecoratorActive({
5393
+ editor,
5394
+ decorator: mark
5395
+ });
5396
+ } catch (err) {
5397
+ return console.warn(err), !1;
5398
+ }
5559
5399
  },
5560
- actions: [() => [{
5561
- type: "noop"
5562
- }]]
5563
- }),
5564
- defineBehavior({
5565
- on: "clipboard.copy",
5566
- actions: [({
5567
- event
5568
- }) => [raise({
5569
- type: "serialize",
5570
- originEvent: event
5571
- })]]
5572
- }),
5573
- defineBehavior({
5574
- on: "clipboard.cut",
5575
- guard: ({
5576
- snapshot
5577
- }) => {
5578
- const focusSpan = getFocusSpan(snapshot), selectionCollapsed = isSelectionCollapsed(snapshot);
5579
- return focusSpan && selectionCollapsed;
5400
+ marks: () => ({
5401
+ ...Editor.marks(editor) || {}
5402
+ }).marks || [],
5403
+ undo: () => {
5404
+ editorActor.send({
5405
+ type: "behavior event",
5406
+ behaviorEvent: {
5407
+ type: "history.undo"
5408
+ },
5409
+ editor
5410
+ });
5580
5411
  },
5581
- actions: [() => [{
5582
- type: "noop"
5583
- }]]
5584
- }),
5585
- defineBehavior({
5586
- on: "clipboard.cut",
5587
- guard: ({
5588
- snapshot
5589
- }) => snapshot.context.selection ? {
5590
- selection: snapshot.context.selection
5591
- } : !1,
5592
- actions: [({
5593
- event
5594
- }, {
5595
- selection
5596
- }) => [raise({
5597
- type: "serialize",
5598
- originEvent: event
5599
- }), raise({
5600
- type: "delete",
5601
- at: selection
5602
- })]]
5603
- }),
5604
- defineBehavior({
5605
- on: "drag.dragstart",
5606
- actions: [({
5607
- event
5608
- }) => [raise({
5609
- type: "serialize",
5610
- originEvent: event
5611
- })]]
5612
- }),
5613
- defineBehavior({
5614
- on: "serialization.success",
5615
- actions: [({
5616
- event
5617
- }) => [{
5618
- type: "effect",
5619
- effect: () => {
5620
- event.originEvent.originEvent.dataTransfer.setData(event.mimeType, event.data);
5412
+ redo: () => {
5413
+ editorActor.send({
5414
+ type: "behavior event",
5415
+ behaviorEvent: {
5416
+ type: "history.redo"
5417
+ },
5418
+ editor
5419
+ });
5420
+ },
5421
+ select: (selection) => {
5422
+ const slateSelection = toSlateRange(selection, editor);
5423
+ slateSelection ? Transforms.select(editor, slateSelection) : Transforms.deselect(editor), editor.onChange();
5424
+ },
5425
+ focusBlock: () => {
5426
+ if (editor.selection) {
5427
+ const block = Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
5428
+ if (block)
5429
+ return fromSlateValue([block], types.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
5621
5430
  }
5622
- }]]
5623
- }),
5624
- defineBehavior({
5625
- on: "serialization.failure",
5626
- actions: [({
5627
- event
5628
- }) => [{
5629
- type: "effect",
5630
- effect: () => {
5631
- console.warn(`Serialization of ${event.mimeType} failed with reason "${event.reason}"`);
5431
+ },
5432
+ focusChild: () => {
5433
+ if (editor.selection) {
5434
+ const block = Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
5435
+ if (block && editor.isTextBlock(block))
5436
+ return fromSlateValue([block], types.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0].children[editor.selection.focus.path[1]];
5632
5437
  }
5633
- }]]
5634
- }),
5635
- defineBehavior({
5636
- on: "drag.drop",
5637
- guard: ({
5638
- snapshot,
5639
- event
5640
- }) => {
5641
- const dragOrigin = snapshot.beta.internalDrag?.origin, dropPosition = event.position.selection;
5642
- return dragOrigin ? isOverlappingSelection(dropPosition)({
5643
- ...snapshot,
5644
- context: {
5645
- ...snapshot.context,
5646
- selection: dragOrigin.selection
5647
- }
5648
- }) : !1;
5649
5438
  },
5650
- actions: [() => [{
5651
- type: "noop"
5652
- }]]
5653
- }),
5654
- defineBehavior({
5655
- on: "drag.drop",
5656
- actions: [({
5657
- event
5658
- }) => [raise({
5659
- type: "select",
5660
- at: event.position.selection
5661
- }), raise({
5662
- type: "deserialize",
5663
- originEvent: event
5664
- })]]
5665
- }),
5666
- defineBehavior({
5667
- on: "deserialization.success",
5668
- guard: ({
5669
- snapshot,
5670
- event
5671
- }) => {
5672
- if (event.originEvent.type !== "drag.drop" || snapshot.beta.internalDrag === void 0)
5439
+ insertChild: (type, value) => {
5440
+ if (type.name !== types.span.name)
5441
+ return editorActor.send({
5442
+ type: "behavior event",
5443
+ behaviorEvent: {
5444
+ type: "insert.inline object",
5445
+ inlineObject: {
5446
+ name: type.name,
5447
+ value
5448
+ }
5449
+ },
5450
+ editor
5451
+ }), editor.selection ? slateRangeToSelection({
5452
+ schema: editorActor.getSnapshot().context.schema,
5453
+ editor,
5454
+ range: editor.selection
5455
+ })?.focus.path ?? [] : [];
5456
+ if (!editor.selection)
5457
+ throw new Error("The editor has no selection");
5458
+ const [focusBlock] = Array.from(Editor.nodes(editor, {
5459
+ at: editor.selection.focus.path.slice(0, 1),
5460
+ match: (n) => n._type === types.block.name
5461
+ }))[0] || [void 0];
5462
+ if (!focusBlock)
5463
+ throw new Error("No focused text block");
5464
+ if (type.name !== types.span.name && !types.inlineObjects.some((t) => t.name === type.name))
5465
+ throw new Error("This type cannot be inserted as a child to a text block");
5466
+ const child = toSlateValue([{
5467
+ _key: editorActor.getSnapshot().context.keyGenerator(),
5468
+ _type: types.block.name,
5469
+ children: [{
5470
+ _key: editorActor.getSnapshot().context.keyGenerator(),
5471
+ _type: type.name,
5472
+ ...value || {}
5473
+ }]
5474
+ }], {
5475
+ schemaTypes: editorActor.getSnapshot().context.schema
5476
+ })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types.span.name, focusNode = Node.get(editor, focusChildPath);
5477
+ return isSpanNode && focusNode._type !== types.span.name && (debug$3("Inserting span child next to inline object child, moving selection + 1"), editor.move({
5478
+ distance: 1,
5479
+ unit: "character"
5480
+ })), Transforms.insertNodes(editor, child, {
5481
+ select: !0,
5482
+ at: editor.selection
5483
+ }), editor.onChange(), editor.selection ? slateRangeToSelection({
5484
+ schema: editorActor.getSnapshot().context.schema,
5485
+ editor,
5486
+ range: editor.selection
5487
+ })?.focus.path ?? [] : [];
5488
+ },
5489
+ insertBlock: (type, value) => (editorActor.send({
5490
+ type: "behavior event",
5491
+ behaviorEvent: {
5492
+ type: "insert.block",
5493
+ block: {
5494
+ _type: type.name,
5495
+ ...value || {}
5496
+ },
5497
+ placement: "auto"
5498
+ },
5499
+ editor
5500
+ }), editor.selection ? slateRangeToSelection({
5501
+ schema: editorActor.getSnapshot().context.schema,
5502
+ editor,
5503
+ range: editor.selection
5504
+ })?.focus.path ?? [] : []),
5505
+ hasBlockStyle: (style) => {
5506
+ try {
5507
+ return isStyleActive({
5508
+ editor,
5509
+ style
5510
+ });
5511
+ } catch {
5673
5512
  return !1;
5674
- const dragOrigin = snapshot.beta.internalDrag.origin, dropPosition = event.originEvent.position.selection, droppingOnDragOrigin = dragOrigin ? isOverlappingSelection(dropPosition)({
5675
- ...snapshot,
5676
- context: {
5677
- ...snapshot.context,
5678
- selection: dragOrigin.selection
5513
+ }
5514
+ },
5515
+ hasListStyle: (listItem) => {
5516
+ try {
5517
+ return isListItemActive({
5518
+ editor,
5519
+ listItem
5520
+ });
5521
+ } catch {
5522
+ return !1;
5523
+ }
5524
+ },
5525
+ isVoid: (element) => ![types.block.name, types.span.name].includes(element._type),
5526
+ findByPath: (path) => {
5527
+ const slatePath = toSlateRange({
5528
+ focus: {
5529
+ path,
5530
+ offset: 0
5531
+ },
5532
+ anchor: {
5533
+ path,
5534
+ offset: 0
5679
5535
  }
5680
- }) : !1, draggingEntireBlocks = isSelectingEntireBlocks({
5681
- context: {
5682
- ...snapshot.context,
5683
- selection: dragOrigin.selection
5536
+ }, editor);
5537
+ if (slatePath) {
5538
+ const [block, blockPath] = Editor.node(editor, slatePath.focus.path.slice(0, 1));
5539
+ if (block && blockPath && typeof block._key == "string") {
5540
+ if (path.length === 1 && slatePath.focus.path.length === 1)
5541
+ return [fromSlateValue([block], types.block.name)[0], [{
5542
+ _key: block._key
5543
+ }]];
5544
+ const ptBlock = fromSlateValue([block], types.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
5545
+ if (editor.isTextBlock(ptBlock)) {
5546
+ const ptChild = ptBlock.children[slatePath.focus.path[1]];
5547
+ if (ptChild)
5548
+ return [ptChild, [{
5549
+ _key: block._key
5550
+ }, "children", {
5551
+ _key: ptChild._key
5552
+ }]];
5553
+ }
5684
5554
  }
5685
- }), draggedBlocks = getSelectedBlocks({
5686
- context: {
5687
- ...snapshot.context,
5688
- selection: dragOrigin.selection
5555
+ }
5556
+ return [void 0, void 0];
5557
+ },
5558
+ findDOMNode: (element) => {
5559
+ let node;
5560
+ try {
5561
+ const [item] = Array.from(Editor.nodes(editor, {
5562
+ at: [],
5563
+ match: (n) => n._key === element._key
5564
+ }) || [])[0] || [void 0];
5565
+ node = ReactEditor.toDOMNode(editor, item);
5566
+ } catch {
5567
+ }
5568
+ return node;
5569
+ },
5570
+ activeAnnotations: () => {
5571
+ if (!editor.selection || editor.selection.focus.path.length < 2)
5572
+ return [];
5573
+ try {
5574
+ const activeAnnotations = [], spans = Editor.nodes(editor, {
5575
+ at: editor.selection,
5576
+ match: (node) => Text.isText(node) && node.marks !== void 0 && Array.isArray(node.marks) && node.marks.length > 0
5577
+ });
5578
+ for (const [span, path] of spans) {
5579
+ const [block] = Editor.node(editor, path, {
5580
+ depth: 1
5581
+ });
5582
+ editor.isTextBlock(block) && block.markDefs?.forEach((def) => {
5583
+ Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
5584
+ });
5689
5585
  }
5690
- });
5691
- return droppingOnDragOrigin ? !1 : {
5692
- draggingEntireBlocks,
5693
- draggedBlocks,
5694
- dragOrigin,
5695
- originEvent: event.originEvent
5696
- };
5586
+ return activeAnnotations;
5587
+ } catch {
5588
+ return [];
5589
+ }
5697
5590
  },
5698
- actions: [({
5699
- event
5700
- }, {
5701
- draggingEntireBlocks,
5702
- draggedBlocks,
5703
- dragOrigin,
5704
- originEvent
5705
- }) => [...draggingEntireBlocks ? draggedBlocks.map((block) => raise({
5706
- type: "delete.block",
5707
- at: block.path
5708
- })) : [raise({
5709
- type: "delete",
5710
- at: dragOrigin.selection
5711
- })], raise({
5712
- type: "insert.blocks",
5713
- blocks: event.data,
5714
- placement: draggingEntireBlocks ? originEvent.position.block === "start" ? "before" : originEvent.position.block === "end" ? "after" : "auto" : "auto"
5715
- })]]
5716
- }),
5717
- /**
5718
- * If we are pasting text/plain into a text block then we can probably
5719
- * assume that the intended behavior is that the pasted text inherits
5720
- * formatting from the text it's pasted into.
5721
- */
5722
- defineBehavior({
5723
- on: "deserialization.success",
5724
- guard: ({
5725
- snapshot,
5726
- event
5727
- }) => {
5728
- if (getFocusTextBlock(snapshot) && event.mimeType === "text/plain" && event.originEvent.type === "clipboard.paste") {
5729
- const activeDecorators = snapshot.context.activeDecorators;
5730
- return {
5731
- activeAnnotations: getActiveAnnotations(snapshot),
5732
- activeDecorators,
5733
- textRuns: event.data.flatMap((block) => isTextBlock(snapshot.context.schema, block) ? [getTextBlockText(block)] : [])
5734
- };
5591
+ isAnnotationActive: (annotationType) => isAnnotationActive({
5592
+ editor,
5593
+ annotation: {
5594
+ name: annotationType
5735
5595
  }
5736
- return !1;
5596
+ }),
5597
+ addAnnotation: (type, value) => {
5598
+ let paths;
5599
+ return Editor.withoutNormalizing(editor, () => {
5600
+ paths = addAnnotationActionImplementation({
5601
+ context: {
5602
+ keyGenerator: editorActor.getSnapshot().context.keyGenerator,
5603
+ schema: types
5604
+ },
5605
+ action: {
5606
+ annotation: {
5607
+ name: type.name,
5608
+ value: value ?? {}
5609
+ },
5610
+ editor
5611
+ }
5612
+ });
5613
+ }), editor.onChange(), paths;
5737
5614
  },
5738
- actions: [(_, {
5739
- activeAnnotations,
5740
- activeDecorators,
5741
- textRuns
5742
- }) => textRuns.flatMap((textRun, index) => index !== textRuns.length - 1 ? [raise({
5743
- type: "insert.span",
5744
- text: textRun,
5745
- decorators: activeDecorators,
5746
- annotations: activeAnnotations.map(({
5747
- _key,
5748
- _type,
5749
- ...value
5750
- }) => ({
5751
- name: _type,
5752
- value
5753
- }))
5754
- }), raise({
5755
- type: "insert.break"
5756
- })] : [raise({
5757
- type: "insert.span",
5758
- text: textRun,
5759
- decorators: activeDecorators,
5760
- annotations: activeAnnotations.map(({
5761
- _key,
5762
- _type,
5763
- ...value
5764
- }) => ({
5765
- name: _type,
5766
- value
5767
- }))
5768
- })])]
5769
- }),
5770
- defineBehavior({
5771
- on: "deserialization.success",
5772
- actions: [({
5773
- event
5774
- }) => [raise({
5775
- type: "insert.blocks",
5776
- blocks: event.data,
5777
- placement: "auto"
5778
- })]]
5779
- }),
5780
- defineBehavior({
5781
- on: "deserialization.failure",
5782
- actions: [({
5783
- event
5784
- }) => [{
5785
- type: "effect",
5786
- effect: () => {
5787
- console.warn(`Deserialization of ${event.mimeType} failed with reason "${event.reason}"`);
5615
+ delete: (selection, options) => {
5616
+ if (selection) {
5617
+ const range = toSlateRange(selection, editor);
5618
+ if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
5619
+ throw new Error("Invalid range");
5620
+ if (range) {
5621
+ if (!options?.mode || options?.mode === "selected") {
5622
+ debug$3("Deleting content in selection"), Transforms.delete(editor, {
5623
+ at: range,
5624
+ hanging: !0,
5625
+ voids: !0
5626
+ }), editor.onChange();
5627
+ return;
5628
+ }
5629
+ options?.mode === "blocks" && (debug$3("Deleting blocks touched by selection"), Transforms.removeNodes(editor, {
5630
+ at: range,
5631
+ voids: !0,
5632
+ match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && Element.isElement(node)
5633
+ })), options?.mode === "children" && (debug$3("Deleting children touched by selection"), Transforms.removeNodes(editor, {
5634
+ at: range,
5635
+ voids: !0,
5636
+ match: (node) => node._type === types.span.name || // Text children
5637
+ !editor.isTextBlock(node) && Element.isElement(node)
5638
+ })), editor.children.length === 0 && (editor.children = [editor.pteCreateTextBlock({
5639
+ decorators: []
5640
+ })]), editor.onChange();
5641
+ }
5788
5642
  }
5789
- }]]
5790
- }),
5791
- defineBehavior({
5792
- on: "clipboard.paste",
5793
- guard: ({
5794
- snapshot
5795
- }) => snapshot.context.selection && isSelectionExpanded(snapshot) ? {
5796
- selection: snapshot.context.selection
5797
- } : !1,
5798
- actions: [({
5799
- event
5800
- }, {
5801
- selection
5802
- }) => [raise({
5803
- type: "delete",
5804
- at: selection
5805
- }), raise({
5806
- type: "deserialize",
5807
- originEvent: event
5808
- })]]
5809
- }),
5810
- defineBehavior({
5811
- on: "clipboard.paste",
5812
- actions: [({
5813
- event
5814
- }) => [raise({
5815
- type: "deserialize",
5816
- originEvent: event
5817
- })]]
5818
- }),
5819
- defineBehavior({
5820
- on: "input.*",
5821
- actions: [({
5822
- event
5823
- }) => [raise({
5824
- type: "deserialize",
5825
- originEvent: event
5826
- })]]
5827
- }),
5828
- ...abstractAnnotationBehaviors,
5829
- ...abstractDecoratorBehaviors,
5830
- ...abstractDeleteBehaviors,
5831
- ...abstractInsertBehaviors,
5832
- ...abstractListItemBehaviors,
5833
- ...abstractMoveBehaviors,
5834
- ...abstractStyleBehaviors,
5835
- ...abstractSelectBehaviors,
5836
- raiseDeserializationSuccessOrFailure,
5837
- raiseSerializationSuccessOrFailure,
5838
- raiseInsertSoftBreak
5839
- ], abstractBehaviorEventTypes = ["annotation.toggle", "decorator.toggle", "delete.text", "deserialize", "deserialization.success", "deserialization.failure", "insert.blocks", "insert.break", "insert.soft break", "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"];
5840
- function isAbstractBehaviorEvent(event) {
5841
- return abstractBehaviorEventTypes.includes(event.type);
5643
+ },
5644
+ removeAnnotation: (type) => {
5645
+ editorActor.send({
5646
+ type: "behavior event",
5647
+ behaviorEvent: {
5648
+ type: "annotation.remove",
5649
+ annotation: {
5650
+ name: type.name
5651
+ }
5652
+ },
5653
+ editor
5654
+ });
5655
+ },
5656
+ getSelection: () => {
5657
+ let ptRange = null;
5658
+ if (editor.selection) {
5659
+ const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
5660
+ if (existing)
5661
+ return existing;
5662
+ ptRange = slateRangeToSelection({
5663
+ schema: editorActor.getSnapshot().context.schema,
5664
+ editor,
5665
+ range: editor.selection
5666
+ }), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
5667
+ }
5668
+ return ptRange;
5669
+ },
5670
+ getValue: () => fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
5671
+ isCollapsedSelection: () => !!editor.selection && Range.isCollapsed(editor.selection),
5672
+ isExpandedSelection: () => !!editor.selection && Range.isExpanded(editor.selection),
5673
+ insertBreak: () => {
5674
+ editor.insertBreak(), editor.onChange();
5675
+ },
5676
+ getFragment: () => fromSlateValue(editor.getFragment(), types.block.name),
5677
+ isSelectionsOverlapping: (selectionA, selectionB) => {
5678
+ const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
5679
+ return Range.isRange(rangeA) && Range.isRange(rangeB) && Range.includes(rangeA, rangeB);
5680
+ }
5681
+ };
5842
5682
  }
5843
- 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"];
5844
- function isNativeBehaviorEvent(event) {
5845
- return nativeBehaviorEventTypes.includes(event.type);
5683
+ function isAnnotationActive({
5684
+ editor,
5685
+ annotation
5686
+ }) {
5687
+ if (!editor.selection || editor.selection.focus.path.length < 2)
5688
+ return !1;
5689
+ try {
5690
+ const spans = [...Editor.nodes(editor, {
5691
+ at: editor.selection,
5692
+ match: (node) => Text.isText(node)
5693
+ })];
5694
+ if (spans.length === 0 || spans.some(([span]) => !isPortableTextSpan$1(span) || !span.marks || span.marks?.length === 0)) return !1;
5695
+ const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
5696
+ const [block] = Editor.node(editor, path, {
5697
+ depth: 1
5698
+ });
5699
+ return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
5700
+ }, []);
5701
+ return spans.every(([span]) => isPortableTextSpan$1(span) ? span.marks?.map((markKey) => selectionMarkDefs.find((def) => def?._key === markKey)?._type)?.includes(annotation.name) : !1);
5702
+ } catch {
5703
+ return !1;
5704
+ }
5846
5705
  }
5847
- function isCustomBehaviorEvent(event) {
5848
- return event.type.startsWith("custom.");
5706
+ function compileSchemasFromEditorConfig(config) {
5707
+ const legacySchema = config.schemaDefinition ? compileSchemaDefinitionToLegacySchema(config.schemaDefinition) : createLegacySchema(config.schema.hasOwnProperty("jsonType") ? config.schema : compileType(config.schema)), schema = legacySchemaToEditorSchema(legacySchema);
5708
+ return {
5709
+ legacySchema,
5710
+ schema
5711
+ };
5849
5712
  }
5850
- const debug$3 = debugWithName("behaviors:event");
5851
- function eventCategory(event) {
5852
- return isNativeBehaviorEvent(event) ? "native" : isAbstractBehaviorEvent(event) ? "abstract" : isCustomBehaviorEvent(event) ? "custom" : "synthetic";
5713
+ function editorConfigToMachineInput(config) {
5714
+ const {
5715
+ legacySchema,
5716
+ schema
5717
+ } = compileSchemasFromEditorConfig(config);
5718
+ return {
5719
+ behaviors: config.behaviors,
5720
+ converters: createCoreConverters(legacySchema),
5721
+ getLegacySchema: () => legacySchema,
5722
+ keyGenerator: config.keyGenerator ?? defaultKeyGenerator,
5723
+ maxBlocks: config.maxBlocks,
5724
+ readOnly: config.readOnly,
5725
+ schema,
5726
+ initialValue: config.initialValue
5727
+ };
5853
5728
  }
5854
- function performEvent({
5855
- mode,
5856
- behaviors,
5857
- event,
5858
- editor,
5859
- keyGenerator,
5860
- schema,
5861
- getSnapshot,
5862
- nativeEvent
5863
- }) {
5864
- debug$3(`(${eventCategory(event)})`, JSON.stringify(event, null, 2));
5865
- const defaultAction = isCustomBehaviorEvent(event) || isNativeBehaviorEvent(event) || isAbstractBehaviorEvent(event) ? void 0 : {
5729
+ function createInternalEditor(editorActor) {
5730
+ const slateEditor = createSlateEditor({
5731
+ editorActor
5732
+ }), editable = createEditableAPI(slateEditor.instance, editorActor);
5733
+ return {
5734
+ getSnapshot: () => getEditorSnapshot({
5735
+ editorActorSnapshot: editorActor.getSnapshot(),
5736
+ slateEditorInstance: slateEditor.instance
5737
+ }),
5738
+ registerBehavior: (config) => (editorActor.send({
5739
+ type: "add behavior",
5740
+ behavior: config.behavior
5741
+ }), () => {
5742
+ editorActor.send({
5743
+ type: "remove behavior",
5744
+ behavior: config.behavior
5745
+ });
5746
+ }),
5747
+ send: (event) => {
5748
+ switch (event.type) {
5749
+ case "add behavior":
5750
+ case "remove behavior":
5751
+ case "update behaviors":
5752
+ case "update key generator":
5753
+ case "update readOnly":
5754
+ case "patches":
5755
+ case "update value":
5756
+ case "update schema":
5757
+ case "update maxBlocks":
5758
+ editorActor.send(event);
5759
+ break;
5760
+ case "blur":
5761
+ editorActor.send({
5762
+ type: "blur",
5763
+ editor: slateEditor.instance
5764
+ });
5765
+ break;
5766
+ case "focus":
5767
+ editorActor.send({
5768
+ type: "focus",
5769
+ editor: slateEditor.instance
5770
+ });
5771
+ break;
5772
+ case "insert.block object":
5773
+ editorActor.send({
5774
+ type: "behavior event",
5775
+ behaviorEvent: {
5776
+ type: "insert.block",
5777
+ block: {
5778
+ _type: event.blockObject.name,
5779
+ ...event.blockObject.value ?? {}
5780
+ },
5781
+ placement: event.placement
5782
+ },
5783
+ editor: slateEditor.instance
5784
+ });
5785
+ break;
5786
+ default:
5787
+ editorActor.send({
5788
+ type: "behavior event",
5789
+ behaviorEvent: event,
5790
+ editor: slateEditor.instance
5791
+ });
5792
+ }
5793
+ },
5794
+ on: (event, listener) => editorActor.on(event, (event2) => {
5795
+ switch (event2.type) {
5796
+ case "blurred":
5797
+ case "done loading":
5798
+ case "editable":
5799
+ case "error":
5800
+ case "focused":
5801
+ case "invalid value":
5802
+ case "loading":
5803
+ case "mutation":
5804
+ case "patch":
5805
+ case "read only":
5806
+ case "ready":
5807
+ case "selection":
5808
+ case "value changed":
5809
+ listener(event2);
5810
+ break;
5811
+ }
5812
+ }),
5813
+ _internal: {
5814
+ editable,
5815
+ editorActor,
5816
+ slateEditor
5817
+ }
5818
+ };
5819
+ }
5820
+ const EditorActorContext = createContext({}), abstractAnnotationBehaviors = [defineBehavior({
5821
+ on: "annotation.toggle",
5822
+ guard: ({
5823
+ snapshot,
5824
+ event
5825
+ }) => isActiveAnnotation(event.annotation.name)(snapshot),
5826
+ actions: [({
5827
+ event
5828
+ }) => [raise({
5829
+ type: "annotation.remove",
5830
+ annotation: event.annotation
5831
+ })]]
5832
+ }), defineBehavior({
5833
+ on: "annotation.toggle",
5834
+ guard: ({
5835
+ snapshot,
5836
+ event
5837
+ }) => !isActiveAnnotation(event.annotation.name)(snapshot),
5838
+ actions: [({
5839
+ event
5840
+ }) => [raise({
5841
+ type: "annotation.add",
5842
+ annotation: event.annotation
5843
+ })]]
5844
+ })], abstractDecoratorBehaviors = [defineBehavior({
5845
+ on: "decorator.toggle",
5846
+ guard: ({
5847
+ snapshot,
5848
+ event
5849
+ }) => isActiveDecorator(event.decorator)(snapshot),
5850
+ actions: [({
5851
+ event
5852
+ }) => [raise({
5853
+ type: "decorator.remove",
5854
+ decorator: event.decorator
5855
+ })]]
5856
+ }), defineBehavior({
5857
+ on: "decorator.toggle",
5858
+ guard: ({
5859
+ snapshot,
5860
+ event
5861
+ }) => {
5862
+ const manualSelection = event.at ? blockOffsetsToSelection({
5863
+ value: snapshot.context.value,
5864
+ offsets: event.at
5865
+ }) : null;
5866
+ return manualSelection ? !isActiveDecorator(event.decorator)({
5867
+ ...snapshot,
5868
+ context: {
5869
+ ...snapshot.context,
5870
+ selection: manualSelection
5871
+ }
5872
+ }) : !isActiveDecorator(event.decorator)(snapshot);
5873
+ },
5874
+ actions: [({
5875
+ event
5876
+ }) => [raise({
5866
5877
  ...event,
5867
- editor
5868
- }, eventBehaviors = (mode === "raise" ? [...behaviors, ...defaultBehaviors] : behaviors).filter((behavior) => {
5869
- if (behavior.on === "*")
5870
- return !0;
5871
- const [listenedNamespace] = behavior.on.includes("*") && behavior.on.includes(".") ? behavior.on.split(".") : [void 0], [eventNamespace] = event.type.includes(".") ? event.type.split(".") : [void 0];
5872
- return listenedNamespace !== void 0 && eventNamespace !== void 0 && listenedNamespace === eventNamespace || listenedNamespace !== void 0 && eventNamespace === void 0 && listenedNamespace === event.type ? !0 : behavior.on === event.type;
5873
- });
5874
- if (eventBehaviors.length === 0) {
5875
- if (!defaultAction)
5876
- return;
5877
- withApplyingBehaviorActions(editor, () => {
5878
- try {
5879
- performAction({
5880
- context: {
5881
- keyGenerator,
5882
- schema
5883
- },
5884
- action: defaultAction
5885
- });
5886
- } catch (error) {
5887
- console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
5878
+ type: "decorator.add"
5879
+ })]]
5880
+ })], abstractDeleteBehaviors = [defineBehavior({
5881
+ on: "delete.text",
5882
+ guard: ({
5883
+ snapshot,
5884
+ event
5885
+ }) => {
5886
+ const selection = blockOffsetsToSelection({
5887
+ value: snapshot.context.value,
5888
+ offsets: event.at
5889
+ });
5890
+ if (!selection)
5891
+ return !1;
5892
+ const trimmedSelection = getTrimmedSelection({
5893
+ context: {
5894
+ converters: [],
5895
+ schema: snapshot.context.schema,
5896
+ keyGenerator: snapshot.context.keyGenerator,
5897
+ activeDecorators: [],
5898
+ readOnly: !1,
5899
+ value: snapshot.context.value,
5900
+ selection
5888
5901
  }
5889
- }), editor.onChange();
5890
- return;
5891
- }
5892
- const guardSnapshot = getSnapshot();
5893
- let behaviorOverwritten = !1;
5894
- for (const eventBehavior of eventBehaviors) {
5895
- const shouldRun = eventBehavior.guard === void 0 || eventBehavior.guard({
5896
- snapshot: guardSnapshot,
5897
- event
5898
5902
  });
5899
- if (shouldRun) {
5900
- for (const actionSet of eventBehavior.actions) {
5901
- const actionsSnapshot = getSnapshot(), actions = actionSet({
5902
- snapshot: actionsSnapshot,
5903
- event
5904
- }, shouldRun);
5905
- actions.length !== 0 && (behaviorOverwritten = behaviorOverwritten || actions.some((action) => action.type !== "effect"), withApplyingBehaviorActionSet(editor, () => {
5906
- for (const action of actions) {
5907
- if (action.type === "raise") {
5908
- performEvent({
5909
- mode,
5910
- behaviors: mode === "execute" ? isCustomBehaviorEvent(action.event) ? [...behaviors, ...defaultBehaviors] : defaultBehaviors : [...behaviors, ...defaultBehaviors],
5911
- event: action.event,
5912
- editor,
5913
- keyGenerator,
5914
- schema,
5915
- getSnapshot,
5916
- nativeEvent: void 0
5917
- });
5918
- continue;
5919
- }
5920
- if (action.type === "execute") {
5921
- if (isAbstractBehaviorEvent(action.event) || isCustomBehaviorEvent(action.event))
5922
- performEvent({
5923
- mode: "execute",
5924
- behaviors: isCustomBehaviorEvent(action.event) ? [...behaviors, ...defaultBehaviors] : defaultBehaviors,
5925
- event: action.event,
5926
- editor,
5927
- keyGenerator,
5928
- schema,
5929
- getSnapshot,
5930
- nativeEvent: void 0
5931
- });
5932
- else {
5933
- const internalAction2 = {
5934
- ...action.event,
5935
- editor
5936
- };
5937
- let actionFailed2 = !1;
5938
- if (withApplyingBehaviorActions(editor, () => {
5939
- try {
5940
- performAction({
5941
- context: {
5942
- keyGenerator,
5943
- schema
5944
- },
5945
- action: internalAction2
5946
- });
5947
- } catch (error) {
5948
- console.error(new Error(`Performing action "${action.event.type}" as a result of "${event.type}" failed due to: ${error.message}`)), actionFailed2 = !0;
5949
- }
5950
- }), actionFailed2)
5951
- break;
5952
- editor.onChange();
5953
- }
5954
- continue;
5955
- }
5956
- const internalAction = {
5957
- ...action,
5958
- editor
5959
- };
5960
- let actionFailed = !1;
5961
- if (withApplyingBehaviorActions(editor, () => {
5962
- try {
5963
- performAction({
5964
- context: {
5965
- keyGenerator,
5966
- schema
5967
- },
5968
- action: internalAction
5969
- });
5970
- } catch (error) {
5971
- console.error(new Error(`Performing action "${internalAction.type}" as a result of "${event.type}" failed due to: ${error.message}`)), actionFailed = !0;
5972
- }
5973
- }), actionFailed)
5974
- break;
5975
- editor.onChange();
5903
+ return trimmedSelection ? {
5904
+ selection: trimmedSelection
5905
+ } : !1;
5906
+ },
5907
+ actions: [(_, {
5908
+ selection
5909
+ }) => [raise({
5910
+ type: "delete",
5911
+ at: selection
5912
+ })]]
5913
+ })], abstractInsertBehaviors = [defineBehavior({
5914
+ on: "insert.blocks",
5915
+ guard: ({
5916
+ event
5917
+ }) => event.placement === "before",
5918
+ actions: [({
5919
+ event
5920
+ }) => event.blocks.map((block, index) => raise({
5921
+ type: "insert.block",
5922
+ block,
5923
+ placement: index === 0 ? "before" : "after",
5924
+ select: "end"
5925
+ }))]
5926
+ }), defineBehavior({
5927
+ on: "insert.blocks",
5928
+ guard: ({
5929
+ event
5930
+ }) => event.placement === "after",
5931
+ actions: [({
5932
+ event
5933
+ }) => event.blocks.map((block) => raise({
5934
+ type: "insert.block",
5935
+ block,
5936
+ placement: "after",
5937
+ select: "end"
5938
+ }))]
5939
+ }), defineBehavior({
5940
+ on: "insert.blocks",
5941
+ guard: ({
5942
+ snapshot,
5943
+ event
5944
+ }) => {
5945
+ if (event.placement !== "auto")
5946
+ return !1;
5947
+ const focusTextBlock = getFocusTextBlock(snapshot);
5948
+ return focusTextBlock ? {
5949
+ focusTextBlock
5950
+ } : !1;
5951
+ },
5952
+ actions: [({
5953
+ event
5954
+ }, {
5955
+ focusTextBlock
5956
+ }) => event.blocks.length === 1 ? [raise({
5957
+ type: "insert.block",
5958
+ block: event.blocks[0],
5959
+ placement: "auto",
5960
+ select: "end"
5961
+ })] : isEmptyTextBlock(focusTextBlock.node) ? event.blocks.map((block, index) => raise({
5962
+ type: "insert.block",
5963
+ block,
5964
+ placement: index === 0 ? "auto" : "after",
5965
+ select: "end"
5966
+ })) : event.blocks.flatMap((block, index) => index === 0 ? [raise({
5967
+ type: "split.block"
5968
+ }), raise({
5969
+ type: "select.previous block",
5970
+ select: "end"
5971
+ }), raise({
5972
+ type: "insert.block",
5973
+ block,
5974
+ placement: "auto",
5975
+ select: "end"
5976
+ })] : index === event.blocks.length - 1 ? [raise({
5977
+ type: "select.next block",
5978
+ select: "start"
5979
+ }), raise({
5980
+ type: "insert.block",
5981
+ block,
5982
+ placement: "auto",
5983
+ select: "end"
5984
+ })] : [raise({
5985
+ type: "insert.block",
5986
+ block,
5987
+ placement: "after",
5988
+ select: "end"
5989
+ })])]
5990
+ }), defineBehavior({
5991
+ on: "insert.blocks",
5992
+ guard: ({
5993
+ event
5994
+ }) => event.placement === "auto",
5995
+ actions: [({
5996
+ event
5997
+ }) => event.blocks.map((block, index) => raise({
5998
+ type: "insert.block",
5999
+ block,
6000
+ placement: index === 0 ? "auto" : "after",
6001
+ select: "end"
6002
+ }))]
6003
+ }), defineBehavior({
6004
+ on: "insert.break",
6005
+ actions: [() => [raise({
6006
+ type: "split.block"
6007
+ })]]
6008
+ }), defineBehavior({
6009
+ on: "insert.soft break",
6010
+ actions: [() => [raise({
6011
+ type: "insert.text",
6012
+ text: `
6013
+ `
6014
+ })]]
6015
+ })], abstractListItemBehaviors = [defineBehavior({
6016
+ on: "list item.add",
6017
+ guard: ({
6018
+ snapshot
6019
+ }) => ({
6020
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6021
+ }),
6022
+ actions: [({
6023
+ event
6024
+ }, {
6025
+ selectedTextBlocks
6026
+ }) => selectedTextBlocks.map((block) => raise({
6027
+ type: "block.set",
6028
+ at: block.path,
6029
+ props: {
6030
+ level: 1,
6031
+ listItem: event.listItem
6032
+ }
6033
+ }))]
6034
+ }), defineBehavior({
6035
+ on: "list item.remove",
6036
+ guard: ({
6037
+ snapshot
6038
+ }) => ({
6039
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6040
+ }),
6041
+ actions: [(_, {
6042
+ selectedTextBlocks
6043
+ }) => selectedTextBlocks.map((block) => raise({
6044
+ type: "block.unset",
6045
+ at: block.path,
6046
+ props: ["level", "listItem"]
6047
+ }))]
6048
+ }), defineBehavior({
6049
+ on: "list item.toggle",
6050
+ guard: ({
6051
+ snapshot,
6052
+ event
6053
+ }) => isActiveListItem(event.listItem)(snapshot),
6054
+ actions: [({
6055
+ event
6056
+ }) => [raise({
6057
+ type: "list item.remove",
6058
+ listItem: event.listItem
6059
+ })]]
6060
+ }), defineBehavior({
6061
+ on: "list item.toggle",
6062
+ guard: ({
6063
+ snapshot,
6064
+ event
6065
+ }) => !isActiveListItem(event.listItem)(snapshot),
6066
+ actions: [({
6067
+ event
6068
+ }) => [raise({
6069
+ type: "list item.add",
6070
+ listItem: event.listItem
6071
+ })]]
6072
+ })], abstractMoveBehaviors = [defineBehavior({
6073
+ on: "move.block up",
6074
+ guard: ({
6075
+ snapshot,
6076
+ event
6077
+ }) => {
6078
+ const previousBlock = getPreviousBlock({
6079
+ context: {
6080
+ ...snapshot.context,
6081
+ selection: {
6082
+ anchor: {
6083
+ path: event.at,
6084
+ offset: 0
6085
+ },
6086
+ focus: {
6087
+ path: event.at,
6088
+ offset: 0
5976
6089
  }
5977
- }));
5978
- }
5979
- if (behaviorOverwritten) {
5980
- nativeEvent?.preventDefault();
5981
- break;
6090
+ }
5982
6091
  }
5983
- }
5984
- }
5985
- if (!behaviorOverwritten) {
5986
- if (!defaultAction)
5987
- return;
5988
- withApplyingBehaviorActions(editor, () => {
5989
- try {
5990
- performAction({
5991
- context: {
5992
- keyGenerator,
5993
- schema
6092
+ });
6093
+ return previousBlock ? {
6094
+ previousBlock
6095
+ } : !1;
6096
+ },
6097
+ actions: [({
6098
+ event
6099
+ }, {
6100
+ previousBlock
6101
+ }) => [raise({
6102
+ type: "move.block",
6103
+ at: event.at,
6104
+ to: previousBlock.path
6105
+ })]]
6106
+ }), defineBehavior({
6107
+ on: "move.block down",
6108
+ guard: ({
6109
+ snapshot,
6110
+ event
6111
+ }) => {
6112
+ const nextBlock = getNextBlock({
6113
+ context: {
6114
+ ...snapshot.context,
6115
+ selection: {
6116
+ anchor: {
6117
+ path: event.at,
6118
+ offset: 0
5994
6119
  },
5995
- action: defaultAction
5996
- });
5997
- } catch (error) {
5998
- console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6120
+ focus: {
6121
+ path: event.at,
6122
+ offset: 0
6123
+ }
6124
+ }
5999
6125
  }
6000
- }), editor.onChange();
6001
- }
6002
- }
6003
- function slateChildrenToBlocks(schema, value) {
6004
- const blocks = new Array(value.length);
6005
- for (let blockIndex = 0; blockIndex < value.length; blockIndex++) {
6006
- const descendant = value[blockIndex];
6007
- if (descendant._type !== schema.block.name) {
6008
- blocks[blockIndex] = {
6009
- _key: descendant._key,
6010
- _type: descendant._type,
6011
- ..."value" in descendant && typeof descendant.value == "object" ? descendant.value : {}
6012
- };
6013
- continue;
6014
- }
6015
- const children = "children" in descendant ? descendant.children : [], processedChildren = new Array(children.length);
6016
- for (let childIndex = 0; childIndex < children.length; childIndex++) {
6017
- const child = children[childIndex];
6018
- processedChildren[childIndex] = child._type === schema.span.name ? child : {
6019
- _key: child._key,
6020
- _type: child._type,
6021
- ..."value" in child && typeof child.value == "object" ? child.value : {}
6022
- };
6023
- }
6024
- blocks[blockIndex] = {
6025
- ...descendant,
6026
- children: processedChildren
6027
- };
6028
- }
6029
- return blocks;
6030
- }
6031
- function getActiveDecorators({
6032
- schema,
6033
- slateEditorInstance
6034
- }) {
6035
- const decorators = schema.decorators.map((decorator) => decorator.name);
6036
- return ({
6037
- ...Editor.marks(slateEditorInstance) ?? {}
6038
- }.marks ?? []).filter((mark) => decorators.includes(mark));
6039
- }
6040
- function createEditorSnapshot({
6041
- converters,
6042
- editor,
6043
- keyGenerator,
6044
- readOnly,
6045
- schema,
6046
- hasTag,
6047
- internalDrag
6048
- }) {
6049
- const value = slateChildrenToBlocks(schema, editor.children), selection = editor.selection ? slateRangeToSelection({
6050
- schema,
6051
- editor,
6052
- range: editor.selection
6053
- }) : null;
6054
- return {
6055
- context: {
6056
- activeDecorators: getActiveDecorators({
6057
- schema,
6058
- slateEditorInstance: editor
6059
- }),
6060
- converters,
6061
- keyGenerator,
6062
- readOnly,
6063
- schema,
6064
- selection,
6065
- value
6066
- },
6067
- beta: {
6068
- hasTag,
6069
- internalDrag
6070
- }
6071
- };
6072
- }
6073
- const editorMachine = setup({
6074
- types: {
6075
- context: {},
6076
- events: {},
6077
- emitted: {},
6078
- input: {},
6079
- tags: {}
6126
+ });
6127
+ return nextBlock ? {
6128
+ nextBlock
6129
+ } : !1;
6080
6130
  },
6081
- actions: {
6082
- "add behavior to context": assign({
6083
- behaviors: ({
6084
- context,
6085
- event
6086
- }) => (assertEvent(event, "add behavior"), /* @__PURE__ */ new Set([...context.behaviors, event.behavior]))
6087
- }),
6088
- "remove behavior from context": assign({
6089
- behaviors: ({
6090
- context,
6091
- event
6092
- }) => (assertEvent(event, "remove behavior"), context.behaviors.delete(event.behavior), /* @__PURE__ */ new Set([...context.behaviors]))
6093
- }),
6094
- "assign behaviors": assign({
6095
- behaviors: ({
6096
- event
6097
- }) => (assertEvent(event, "update behaviors"), /* @__PURE__ */ new Set([...event.behaviors]))
6098
- }),
6099
- "assign schema": assign({
6100
- schema: ({
6101
- event
6102
- }) => (assertEvent(event, "update schema"), event.schema)
6103
- }),
6104
- "emit patch event": enqueueActions(({
6105
- event,
6106
- enqueue
6107
- }) => {
6108
- assertEvent(event, "internal.patch"), enqueue.emit(event), enqueue.emit({
6109
- type: "patch",
6110
- patch: event.patch
6111
- });
6112
- }),
6113
- "emit mutation event": emit(({
6114
- event
6115
- }) => (assertEvent(event, "mutation"), event)),
6116
- "emit read only": emit({
6117
- type: "read only"
6118
- }),
6119
- "emit editable": emit({
6120
- type: "editable"
6121
- }),
6122
- "defer event": assign({
6123
- pendingEvents: ({
6124
- context,
6125
- event
6126
- }) => (assertEvent(event, ["internal.patch", "mutation"]), [...context.pendingEvents, event])
6127
- }),
6128
- "emit pending events": enqueueActions(({
6129
- context,
6130
- enqueue
6131
- }) => {
6132
- for (const event of context.pendingEvents)
6133
- event.type === "internal.patch" ? (enqueue.emit(event), enqueue.emit({
6134
- type: "patch",
6135
- patch: event.patch
6136
- })) : enqueue.emit(event);
6137
- }),
6138
- "emit ready": emit({
6139
- type: "ready"
6140
- }),
6141
- "clear pending events": assign({
6142
- pendingEvents: []
6143
- }),
6144
- "handle blur": ({
6145
- event
6146
- }) => {
6147
- assertEvent(event, "blur");
6148
- try {
6149
- ReactEditor.blur(event.editor);
6150
- } catch (error) {
6151
- console.error(new Error(`Failed to blur editor: ${error.message}`));
6152
- }
6153
- },
6154
- "handle focus": ({
6155
- context
6156
- }) => {
6157
- if (!context.slateEditor) {
6158
- console.error("No Slate editor found to focus");
6159
- return;
6131
+ actions: [({
6132
+ event
6133
+ }, {
6134
+ nextBlock
6135
+ }) => [raise({
6136
+ type: "move.block",
6137
+ at: event.at,
6138
+ to: nextBlock.path
6139
+ })]]
6140
+ })], abstractSelectBehaviors = [defineBehavior({
6141
+ on: "select.previous block",
6142
+ guard: ({
6143
+ snapshot,
6144
+ event
6145
+ }) => {
6146
+ const previousBlock = getPreviousBlock(snapshot);
6147
+ if (!previousBlock)
6148
+ return !1;
6149
+ const point = event.select === "end" ? getBlockEndPoint(previousBlock) : getBlockStartPoint(previousBlock);
6150
+ return {
6151
+ selection: {
6152
+ anchor: point,
6153
+ focus: point
6160
6154
  }
6161
- try {
6162
- const currentSelection = context.slateEditor.selection;
6163
- ReactEditor.focus(context.slateEditor), currentSelection && Transforms.select(context.slateEditor, currentSelection);
6164
- } catch (error) {
6165
- console.error(new Error(`Failed to focus editor: ${error.message}`));
6155
+ };
6156
+ },
6157
+ actions: [(_, {
6158
+ selection
6159
+ }) => [raise({
6160
+ type: "select",
6161
+ at: selection
6162
+ })]]
6163
+ }), defineBehavior({
6164
+ on: "select.next block",
6165
+ guard: ({
6166
+ snapshot,
6167
+ event
6168
+ }) => {
6169
+ const nextBlock = getNextBlock(snapshot);
6170
+ if (!nextBlock)
6171
+ return !1;
6172
+ const point = event.select === "end" ? getBlockEndPoint(nextBlock) : getBlockStartPoint(nextBlock);
6173
+ return {
6174
+ selection: {
6175
+ anchor: point,
6176
+ focus: point
6166
6177
  }
6167
- },
6168
- "handle behavior event": ({
6169
- context,
6170
- event,
6171
- self
6172
- }) => {
6173
- assertEvent(event, ["behavior event"]), performEvent({
6174
- mode: "raise",
6175
- behaviors: [...context.behaviors.values()],
6176
- event: event.behaviorEvent,
6177
- editor: event.editor,
6178
- keyGenerator: context.keyGenerator,
6179
- schema: context.schema,
6180
- getSnapshot: () => createEditorSnapshot({
6181
- converters: [...context.converters],
6182
- editor: event.editor,
6183
- keyGenerator: context.keyGenerator,
6184
- readOnly: self.getSnapshot().matches({
6185
- "edit mode": "read only"
6186
- }),
6187
- schema: context.schema,
6188
- hasTag: (tag) => self.getSnapshot().hasTag(tag),
6189
- internalDrag: context.internalDrag
6190
- }),
6191
- nativeEvent: event.nativeEvent
6192
- });
6193
- }
6178
+ };
6194
6179
  },
6195
- guards: {
6196
- "slate is busy": ({
6197
- context
6198
- }) => context.slateEditor ? context.slateEditor.operations.length > 0 : !1
6199
- }
6200
- }).createMachine({
6201
- id: "editor",
6202
- context: ({
6203
- input
6180
+ actions: [(_, {
6181
+ selection
6182
+ }) => [raise({
6183
+ type: "select",
6184
+ at: selection
6185
+ })]]
6186
+ })], abstractStyleBehaviors = [defineBehavior({
6187
+ on: "style.add",
6188
+ guard: ({
6189
+ snapshot
6204
6190
  }) => ({
6205
- behaviors: /* @__PURE__ */ new Set([...input.behaviors ?? coreBehaviors]),
6206
- converters: new Set(input.converters ?? []),
6207
- keyGenerator: input.keyGenerator,
6208
- pendingEvents: [],
6209
- schema: input.schema,
6210
- selection: null,
6211
- initialReadOnly: input.readOnly ?? !1,
6212
- maxBlocks: input.maxBlocks,
6213
- incomingValue: input.initialValue
6191
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6214
6192
  }),
6215
- on: {
6216
- "notify.blurred": {
6217
- actions: emit(({
6218
- event
6219
- }) => ({
6220
- ...event,
6221
- type: "blurred"
6222
- }))
6223
- },
6224
- "notify.done loading": {
6225
- actions: emit({
6226
- type: "done loading"
6227
- })
6228
- },
6229
- "notify.error": {
6230
- actions: emit(({
6231
- event
6232
- }) => ({
6233
- ...event,
6234
- type: "error"
6235
- }))
6236
- },
6237
- "notify.invalid value": {
6238
- actions: emit(({
6239
- event
6240
- }) => ({
6241
- ...event,
6242
- type: "invalid value"
6243
- }))
6244
- },
6245
- "notify.focused": {
6246
- actions: emit(({
6247
- event
6248
- }) => ({
6249
- ...event,
6250
- type: "focused"
6251
- }))
6252
- },
6253
- "notify.selection": {
6254
- actions: [assign({
6255
- selection: ({
6256
- event
6257
- }) => event.selection
6258
- }), emit(({
6259
- event
6260
- }) => ({
6261
- ...event,
6262
- type: "selection"
6263
- }))]
6264
- },
6265
- "notify.unset": {
6266
- actions: emit(({
6267
- event
6268
- }) => ({
6269
- ...event,
6270
- type: "unset"
6271
- }))
6272
- },
6273
- "notify.loading": {
6274
- actions: emit({
6275
- type: "loading"
6276
- })
6277
- },
6278
- "notify.value changed": {
6279
- actions: emit(({
6280
- event
6281
- }) => ({
6193
+ actions: [({
6194
+ event
6195
+ }, {
6196
+ selectedTextBlocks
6197
+ }) => selectedTextBlocks.map((block) => raise({
6198
+ type: "block.set",
6199
+ at: block.path,
6200
+ props: {
6201
+ style: event.style
6202
+ }
6203
+ }))]
6204
+ }), defineBehavior({
6205
+ on: "style.remove",
6206
+ guard: ({
6207
+ snapshot
6208
+ }) => ({
6209
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6210
+ }),
6211
+ actions: [(_, {
6212
+ selectedTextBlocks
6213
+ }) => selectedTextBlocks.map((block) => raise({
6214
+ type: "block.unset",
6215
+ at: block.path,
6216
+ props: ["style"]
6217
+ }))]
6218
+ }), defineBehavior({
6219
+ on: "style.toggle",
6220
+ guard: ({
6221
+ snapshot,
6222
+ event
6223
+ }) => isActiveStyle(event.style)(snapshot),
6224
+ actions: [({
6225
+ event
6226
+ }) => [raise({
6227
+ type: "style.remove",
6228
+ style: event.style
6229
+ })]]
6230
+ }), defineBehavior({
6231
+ on: "style.toggle",
6232
+ guard: ({
6233
+ snapshot,
6234
+ event
6235
+ }) => !isActiveStyle(event.style)(snapshot),
6236
+ actions: [({
6237
+ event
6238
+ }) => [raise({
6239
+ type: "style.add",
6240
+ style: event.style
6241
+ })]]
6242
+ })], keyIs = {
6243
+ lineBreak: (event) => event.key === "Enter" && event.shiftKey
6244
+ }, raiseInsertSoftBreak = defineBehavior({
6245
+ on: "keyboard.keydown",
6246
+ guard: ({
6247
+ event
6248
+ }) => keyIs.lineBreak(event.originEvent),
6249
+ actions: [() => [raise({
6250
+ type: "insert.soft break"
6251
+ })]]
6252
+ }), raiseDeserializationSuccessOrFailure = defineBehavior({
6253
+ on: "deserialize",
6254
+ guard: ({
6255
+ snapshot,
6256
+ event
6257
+ }) => {
6258
+ let success;
6259
+ const failures = [];
6260
+ for (const converter of snapshot.context.converters) {
6261
+ const data = event.originEvent.originEvent.dataTransfer.getData(converter.mimeType);
6262
+ if (!data)
6263
+ continue;
6264
+ const deserializeEvent = converter.deserialize({
6265
+ snapshot,
6266
+ event: {
6267
+ type: "deserialize",
6268
+ data
6269
+ }
6270
+ });
6271
+ if (deserializeEvent.type === "deserialization.success") {
6272
+ success = deserializeEvent;
6273
+ break;
6274
+ } else
6275
+ failures.push(deserializeEvent);
6276
+ }
6277
+ return success || {
6278
+ type: "deserialization.failure",
6279
+ mimeType: "*/*",
6280
+ reason: failures.map((failure) => failure.reason).join(", ")
6281
+ };
6282
+ },
6283
+ actions: [({
6284
+ event
6285
+ }, deserializeEvent) => [raise({
6286
+ ...deserializeEvent,
6287
+ originEvent: event.originEvent
6288
+ })]]
6289
+ }), raiseSerializationSuccessOrFailure = defineBehavior({
6290
+ on: "serialize",
6291
+ guard: ({
6292
+ snapshot,
6293
+ event
6294
+ }) => {
6295
+ if (snapshot.context.converters.length === 0)
6296
+ return !1;
6297
+ const serializeEvents = snapshot.context.converters.map((converter) => converter.serialize({
6298
+ snapshot,
6299
+ event: {
6282
6300
  ...event,
6283
- type: "value changed"
6284
- }))
6285
- },
6286
- "add behavior": {
6287
- actions: "add behavior to context"
6288
- },
6289
- "remove behavior": {
6290
- actions: "remove behavior from context"
6291
- },
6292
- patches: {
6293
- actions: emit(({
6294
- event
6295
- }) => event)
6296
- },
6297
- "update behaviors": {
6298
- actions: "assign behaviors"
6299
- },
6300
- "update key generator": {
6301
- actions: assign({
6302
- keyGenerator: ({
6303
- event
6304
- }) => event.keyGenerator
6305
- })
6306
- },
6307
- "update schema": {
6308
- actions: "assign schema"
6301
+ originEvent: event.originEvent.type
6302
+ }
6303
+ }));
6304
+ return serializeEvents.length === 0 ? !1 : serializeEvents;
6305
+ },
6306
+ actions: [({
6307
+ event
6308
+ }, serializeEvents) => serializeEvents.map((serializeEvent) => raise({
6309
+ ...serializeEvent,
6310
+ originEvent: event.originEvent
6311
+ }))]
6312
+ }), defaultBehaviors = [
6313
+ defineBehavior({
6314
+ on: "clipboard.copy",
6315
+ guard: ({
6316
+ snapshot
6317
+ }) => {
6318
+ const focusSpan = getFocusSpan(snapshot), selectionCollapsed = isSelectionCollapsed(snapshot);
6319
+ return focusSpan && selectionCollapsed;
6309
6320
  },
6310
- "update value": {
6311
- actions: assign({
6312
- incomingValue: ({
6313
- event
6314
- }) => event.value
6315
- })
6321
+ actions: [() => [{
6322
+ type: "noop"
6323
+ }]]
6324
+ }),
6325
+ defineBehavior({
6326
+ on: "clipboard.copy",
6327
+ actions: [({
6328
+ event
6329
+ }) => [raise({
6330
+ type: "serialize",
6331
+ originEvent: event
6332
+ })]]
6333
+ }),
6334
+ defineBehavior({
6335
+ on: "clipboard.cut",
6336
+ guard: ({
6337
+ snapshot
6338
+ }) => {
6339
+ const focusSpan = getFocusSpan(snapshot), selectionCollapsed = isSelectionCollapsed(snapshot);
6340
+ return focusSpan && selectionCollapsed;
6316
6341
  },
6317
- "update maxBlocks": {
6318
- actions: assign({
6319
- maxBlocks: ({
6320
- event
6321
- }) => event.maxBlocks
6322
- })
6323
- }
6324
- },
6325
- type: "parallel",
6326
- states: {
6327
- "edit mode": {
6328
- initial: "read only",
6329
- states: {
6330
- "read only": {
6331
- initial: "determine initial edit mode",
6332
- on: {
6333
- "behavior event": {
6334
- actions: "handle behavior event",
6335
- guard: ({
6336
- event
6337
- }) => 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"
6338
- }
6339
- },
6340
- states: {
6341
- "determine initial edit mode": {
6342
- on: {
6343
- "done syncing initial value": [{
6344
- target: "#editor.edit mode.read only.read only",
6345
- guard: ({
6346
- context
6347
- }) => context.initialReadOnly
6348
- }, {
6349
- target: "#editor.edit mode.editable"
6350
- }]
6351
- }
6352
- },
6353
- "read only": {
6354
- on: {
6355
- "update readOnly": {
6356
- guard: ({
6357
- event
6358
- }) => !event.readOnly,
6359
- target: "#editor.edit mode.editable",
6360
- actions: ["emit editable"]
6361
- }
6362
- }
6363
- }
6364
- }
6365
- },
6366
- editable: {
6367
- on: {
6368
- "update readOnly": {
6369
- guard: ({
6370
- event
6371
- }) => event.readOnly,
6372
- target: "#editor.edit mode.read only.read only",
6373
- actions: ["emit read only"]
6374
- },
6375
- "behavior event": {
6376
- actions: "handle behavior event"
6377
- },
6378
- blur: {
6379
- actions: "handle blur"
6380
- },
6381
- focus: {
6382
- target: ".focusing",
6383
- actions: [assign({
6384
- slateEditor: ({
6385
- event
6386
- }) => event.editor
6387
- })]
6388
- }
6389
- },
6390
- initial: "idle",
6391
- states: {
6392
- idle: {
6393
- on: {
6394
- dragstart: {
6395
- actions: [assign({
6396
- internalDrag: ({
6397
- event
6398
- }) => ({
6399
- ghost: event.ghost,
6400
- origin: event.origin
6401
- })
6402
- })],
6403
- target: "dragging internally"
6404
- }
6405
- }
6406
- },
6407
- focusing: {
6408
- initial: "checking if busy",
6409
- states: {
6410
- "checking if busy": {
6411
- always: [{
6412
- guard: "slate is busy",
6413
- target: "busy"
6414
- }, {
6415
- target: "#editor.edit mode.editable.idle",
6416
- actions: ["handle focus"]
6417
- }]
6418
- },
6419
- busy: {
6420
- after: {
6421
- 10: {
6422
- target: "checking if busy"
6423
- }
6424
- }
6425
- }
6426
- }
6427
- },
6428
- "dragging internally": {
6429
- exit: [({
6430
- context
6431
- }) => {
6432
- if (context.internalDrag?.ghost)
6433
- try {
6434
- context.internalDrag.ghost.parentNode?.removeChild(context.internalDrag.ghost);
6435
- } catch (error) {
6436
- console.error(new Error(`Removing the internal drag ghost failed due to: ${error.message}`));
6437
- }
6438
- }, assign({
6439
- internalDrag: void 0
6440
- })],
6441
- tags: ["dragging internally"],
6442
- on: {
6443
- dragend: {
6444
- target: "idle"
6445
- },
6446
- drop: {
6447
- target: "idle"
6448
- }
6449
- }
6450
- }
6451
- }
6452
- }
6342
+ actions: [() => [{
6343
+ type: "noop"
6344
+ }]]
6345
+ }),
6346
+ defineBehavior({
6347
+ on: "clipboard.cut",
6348
+ guard: ({
6349
+ snapshot
6350
+ }) => snapshot.context.selection ? {
6351
+ selection: snapshot.context.selection
6352
+ } : !1,
6353
+ actions: [({
6354
+ event
6355
+ }, {
6356
+ selection
6357
+ }) => [raise({
6358
+ type: "serialize",
6359
+ originEvent: event
6360
+ }), raise({
6361
+ type: "delete",
6362
+ at: selection
6363
+ })]]
6364
+ }),
6365
+ defineBehavior({
6366
+ on: "drag.dragstart",
6367
+ actions: [({
6368
+ event
6369
+ }) => [raise({
6370
+ type: "serialize",
6371
+ originEvent: event
6372
+ })]]
6373
+ }),
6374
+ defineBehavior({
6375
+ on: "serialization.success",
6376
+ actions: [({
6377
+ event
6378
+ }) => [{
6379
+ type: "effect",
6380
+ effect: () => {
6381
+ event.originEvent.originEvent.dataTransfer.setData(event.mimeType, event.data);
6382
+ }
6383
+ }]]
6384
+ }),
6385
+ defineBehavior({
6386
+ on: "serialization.failure",
6387
+ actions: [({
6388
+ event
6389
+ }) => [{
6390
+ type: "effect",
6391
+ effect: () => {
6392
+ console.warn(`Serialization of ${event.mimeType} failed with reason "${event.reason}"`);
6453
6393
  }
6394
+ }]]
6395
+ }),
6396
+ defineBehavior({
6397
+ on: "drag.drop",
6398
+ guard: ({
6399
+ snapshot,
6400
+ event
6401
+ }) => {
6402
+ const dragOrigin = snapshot.beta.internalDrag?.origin, dropPosition = event.position.selection;
6403
+ return dragOrigin ? isOverlappingSelection(dropPosition)({
6404
+ ...snapshot,
6405
+ context: {
6406
+ ...snapshot.context,
6407
+ selection: dragOrigin.selection
6408
+ }
6409
+ }) : !1;
6454
6410
  },
6455
- setup: {
6456
- initial: "setting up",
6457
- states: {
6458
- "setting up": {
6459
- exit: ["emit ready"],
6460
- on: {
6461
- "internal.patch": {
6462
- actions: "defer event"
6463
- },
6464
- mutation: {
6465
- actions: "defer event"
6466
- },
6467
- "done syncing initial value": {
6468
- target: "pristine"
6469
- }
6470
- }
6471
- },
6472
- pristine: {
6473
- initial: "idle",
6474
- states: {
6475
- idle: {
6476
- on: {
6477
- normalizing: {
6478
- target: "normalizing"
6479
- },
6480
- "internal.patch": {
6481
- actions: "defer event",
6482
- target: "#editor.setup.dirty"
6483
- },
6484
- mutation: {
6485
- actions: "defer event",
6486
- target: "#editor.setup.dirty"
6487
- }
6488
- }
6489
- },
6490
- normalizing: {
6491
- on: {
6492
- "done normalizing": {
6493
- target: "idle"
6494
- },
6495
- "internal.patch": {
6496
- actions: "defer event"
6497
- },
6498
- mutation: {
6499
- actions: "defer event"
6500
- }
6501
- }
6502
- }
6503
- }
6504
- },
6505
- dirty: {
6506
- entry: ["emit pending events", "clear pending events"],
6507
- on: {
6508
- "internal.patch": {
6509
- actions: "emit patch event"
6510
- },
6511
- mutation: {
6512
- actions: "emit mutation event"
6513
- }
6514
- }
6411
+ actions: [() => [{
6412
+ type: "noop"
6413
+ }]]
6414
+ }),
6415
+ defineBehavior({
6416
+ on: "drag.drop",
6417
+ actions: [({
6418
+ event
6419
+ }) => [raise({
6420
+ type: "select",
6421
+ at: event.position.selection
6422
+ }), raise({
6423
+ type: "deserialize",
6424
+ originEvent: event
6425
+ })]]
6426
+ }),
6427
+ defineBehavior({
6428
+ on: "deserialization.success",
6429
+ guard: ({
6430
+ snapshot,
6431
+ event
6432
+ }) => {
6433
+ if (event.originEvent.type !== "drag.drop" || snapshot.beta.internalDrag === void 0)
6434
+ return !1;
6435
+ const dragOrigin = snapshot.beta.internalDrag.origin, dropPosition = event.originEvent.position.selection, droppingOnDragOrigin = dragOrigin ? isOverlappingSelection(dropPosition)({
6436
+ ...snapshot,
6437
+ context: {
6438
+ ...snapshot.context,
6439
+ selection: dragOrigin.selection
6515
6440
  }
6516
- }
6517
- }
6518
- }
6519
- });
6520
- function createLegacySchema(portableTextType) {
6521
- if (!portableTextType)
6522
- throw new Error("Parameter 'portabletextType' missing (required)");
6523
- const blockType = portableTextType.of?.find(findBlockType);
6524
- if (!blockType)
6525
- throw new Error("Block type is not defined in this schema (required)");
6526
- const childrenField = blockType.fields?.find((field) => field.name === "children");
6527
- if (!childrenField)
6528
- throw new Error("Children field for block type found in schema (required)");
6529
- const ofType = childrenField.type.of;
6530
- if (!ofType)
6531
- throw new Error("Valid types for block children not found in schema (required)");
6532
- const spanType = ofType.find((memberType) => memberType.name === "span");
6533
- if (!spanType)
6534
- throw new Error("Span type not found in schema (required)");
6535
- const inlineObjectTypes = ofType.filter((memberType) => memberType.name !== "span") || [], blockObjectTypes = portableTextType.of?.filter((field) => field.name !== blockType.name) || [];
6536
- return {
6537
- styles: resolveEnabledStyles(blockType),
6538
- decorators: resolveEnabledDecorators(spanType),
6539
- lists: resolveEnabledListItems(blockType),
6540
- block: blockType,
6541
- span: spanType,
6542
- portableText: portableTextType,
6543
- inlineObjects: inlineObjectTypes,
6544
- blockObjects: blockObjectTypes,
6545
- annotations: spanType.annotations
6546
- };
6547
- }
6548
- function resolveEnabledStyles(blockType) {
6549
- const styleField = blockType.fields?.find((btField) => btField.name === "style");
6550
- if (!styleField)
6551
- throw new Error("A field with name 'style' is not defined in the block type (required).");
6552
- const textStyles = styleField.type.options?.list && styleField.type.options.list?.filter((style) => style.value);
6553
- if (!textStyles || textStyles.length === 0)
6554
- throw new Error("The style fields need at least one style defined. I.e: {title: 'Normal', value: 'normal'}.");
6555
- return textStyles;
6556
- }
6557
- function resolveEnabledDecorators(spanType) {
6558
- return spanType.decorators;
6559
- }
6560
- function resolveEnabledListItems(blockType) {
6561
- const listField = blockType.fields?.find((btField) => btField.name === "listItem");
6562
- if (!listField)
6563
- throw new Error("A field with name 'listItem' is not defined in the block type (required).");
6564
- const listItems = listField.type.options?.list && listField.type.options.list.filter((list) => list.value);
6565
- if (!listItems)
6566
- throw new Error("The list field need at least to be an empty array");
6567
- return listItems;
6568
- }
6569
- function findBlockType(type) {
6570
- return type.type ? findBlockType(type.type) : type.name === "block" ? type : null;
6571
- }
6572
- function defineSchema(definition) {
6573
- return definition;
6574
- }
6575
- const temporaryImageName = `tmp-${defaultKeyGenerator()}-image`, temporaryUrlName = `tmp-${defaultKeyGenerator()}-url`, temporaryObjectNames = {
6576
- image: temporaryImageName,
6577
- url: temporaryUrlName
6578
- }, objectNames = {
6579
- [temporaryImageName]: "image",
6580
- [temporaryUrlName]: "url"
6581
- }, defaultObjectTitles = {
6582
- image: "Image",
6583
- url: "URL"
6584
- };
6585
- function legacySchemaToEditorSchema(schema) {
6586
- return {
6587
- annotations: schema.annotations.map((annotation) => ({
6588
- name: annotation.name,
6589
- fields: annotation.fields.map((field) => ({
6590
- name: field.name,
6591
- type: field.type.jsonType
6592
- })),
6593
- title: annotation.title
6594
- })),
6595
- block: {
6596
- name: schema.block.name
6441
+ }) : !1, draggingEntireBlocks = isSelectingEntireBlocks({
6442
+ context: {
6443
+ ...snapshot.context,
6444
+ selection: dragOrigin.selection
6445
+ }
6446
+ }), draggedBlocks = getSelectedBlocks({
6447
+ context: {
6448
+ ...snapshot.context,
6449
+ selection: dragOrigin.selection
6450
+ }
6451
+ });
6452
+ return droppingOnDragOrigin ? !1 : {
6453
+ draggingEntireBlocks,
6454
+ draggedBlocks,
6455
+ dragOrigin,
6456
+ originEvent: event.originEvent
6457
+ };
6597
6458
  },
6598
- blockObjects: schema.blockObjects.map((blockObject) => ({
6599
- name: blockObject.name,
6600
- fields: blockObject.fields.map((field) => ({
6601
- name: field.name,
6602
- type: field.type.jsonType
6603
- })),
6604
- title: blockObject.title
6605
- })),
6606
- decorators: schema.decorators.map((decorator) => ({
6607
- name: decorator.value,
6608
- title: decorator.title,
6609
- value: decorator.value
6610
- })),
6611
- inlineObjects: schema.inlineObjects.map((inlineObject) => ({
6612
- name: inlineObject.name,
6613
- fields: inlineObject.fields.map((field) => ({
6614
- name: field.name,
6615
- type: field.type.jsonType
6616
- })),
6617
- title: inlineObject.title
6618
- })),
6619
- span: {
6620
- name: schema.span.name
6459
+ actions: [({
6460
+ event
6461
+ }, {
6462
+ draggingEntireBlocks,
6463
+ draggedBlocks,
6464
+ dragOrigin,
6465
+ originEvent
6466
+ }) => [...draggingEntireBlocks ? draggedBlocks.map((block) => raise({
6467
+ type: "delete.block",
6468
+ at: block.path
6469
+ })) : [raise({
6470
+ type: "delete",
6471
+ at: dragOrigin.selection
6472
+ })], raise({
6473
+ type: "insert.blocks",
6474
+ blocks: event.data,
6475
+ placement: draggingEntireBlocks ? originEvent.position.block === "start" ? "before" : originEvent.position.block === "end" ? "after" : "auto" : "auto"
6476
+ })]]
6477
+ }),
6478
+ /**
6479
+ * If we are pasting text/plain into a text block then we can probably
6480
+ * assume that the intended behavior is that the pasted text inherits
6481
+ * formatting from the text it's pasted into.
6482
+ */
6483
+ defineBehavior({
6484
+ on: "deserialization.success",
6485
+ guard: ({
6486
+ snapshot,
6487
+ event
6488
+ }) => {
6489
+ if (getFocusTextBlock(snapshot) && event.mimeType === "text/plain" && event.originEvent.type === "clipboard.paste") {
6490
+ const activeDecorators = snapshot.context.activeDecorators;
6491
+ return {
6492
+ activeAnnotations: getActiveAnnotations(snapshot),
6493
+ activeDecorators,
6494
+ textRuns: event.data.flatMap((block) => isTextBlock(snapshot.context.schema, block) ? [getTextBlockText(block)] : [])
6495
+ };
6496
+ }
6497
+ return !1;
6621
6498
  },
6622
- styles: schema.styles.map((style) => ({
6623
- name: style.value,
6624
- title: style.title,
6625
- value: style.value
6626
- })),
6627
- lists: schema.lists.map((list) => ({
6628
- name: list.value,
6629
- title: list.title,
6630
- value: list.value
6631
- }))
6632
- };
6633
- }
6634
- function compileSchemaDefinitionToLegacySchema(definition) {
6635
- const blockObjects = definition?.blockObjects?.map((blockObject) => defineType({
6636
- type: "object",
6637
- // Very naive way to work around `SanitySchema.compile` adding default
6638
- // fields to objects with certain names.
6639
- name: temporaryObjectNames[blockObject.name] ?? blockObject.name,
6640
- title: blockObject.title === void 0 ? (
6641
- // This avoids the default title which is a title case of the object name
6642
- defaultObjectTitles[blockObject.name]
6643
- ) : blockObject.title,
6644
- fields: blockObject.fields?.map((field) => ({
6645
- name: field.name,
6646
- type: field.type
6647
- })) ?? []
6648
- })) ?? [], inlineObjects = definition?.inlineObjects?.map((inlineObject) => defineType({
6649
- type: "object",
6650
- // Very naive way to work around `SanitySchema.compile` adding default
6651
- // fields to objects with certain names.
6652
- name: temporaryObjectNames[inlineObject.name] ?? inlineObject.name,
6653
- title: inlineObject.title === void 0 ? (
6654
- // This avoids the default title which is a title case of the object name
6655
- defaultObjectTitles[inlineObject.name]
6656
- ) : inlineObject.title,
6657
- fields: inlineObject.fields?.map((field) => ({
6658
- name: field.name,
6659
- type: field.type
6660
- })) ?? []
6661
- })) ?? [], portableTextSchema = defineField({
6662
- type: "array",
6663
- name: "portable-text",
6664
- of: [...blockObjects.map((blockObject) => ({
6665
- type: blockObject.name
6666
- })), {
6667
- type: "block",
6668
- name: "block",
6669
- of: inlineObjects.map((inlineObject) => ({
6670
- type: inlineObject.name
6671
- })),
6672
- marks: {
6673
- decorators: definition?.decorators?.map((decorator) => ({
6674
- title: decorator.title ?? startCase(decorator.name),
6675
- value: decorator.name
6676
- })) ?? [],
6677
- annotations: definition?.annotations?.map((annotation) => ({
6678
- name: annotation.name,
6679
- type: "object",
6680
- title: annotation.title,
6681
- fields: annotation.fields?.map((field) => ({
6682
- name: field.name,
6683
- type: field.type
6684
- })) ?? []
6685
- })) ?? []
6686
- },
6687
- lists: definition?.lists?.map((list) => ({
6688
- value: list.name,
6689
- title: list.title ?? startCase(list.name)
6690
- })) ?? [],
6691
- styles: definition?.styles?.map((style) => ({
6692
- value: style.name,
6693
- title: style.title ?? startCase(style.name)
6694
- })) ?? []
6695
- }]
6696
- }), schema = Schema.compile({
6697
- types: [portableTextSchema, ...blockObjects, ...inlineObjects]
6698
- }).get("portable-text"), pteSchema = createLegacySchema(schema);
6699
- return {
6700
- ...pteSchema,
6701
- blockObjects: pteSchema.blockObjects.map((blockObject) => objectNames[blockObject.name] !== void 0 ? {
6702
- ...blockObject,
6703
- name: objectNames[blockObject.name],
6704
- type: {
6705
- ...blockObject.type,
6706
- name: objectNames[blockObject.name]
6499
+ actions: [(_, {
6500
+ activeAnnotations,
6501
+ activeDecorators,
6502
+ textRuns
6503
+ }) => textRuns.flatMap((textRun, index) => index !== textRuns.length - 1 ? [raise({
6504
+ type: "insert.span",
6505
+ text: textRun,
6506
+ decorators: activeDecorators,
6507
+ annotations: activeAnnotations.map(({
6508
+ _key,
6509
+ _type,
6510
+ ...value
6511
+ }) => ({
6512
+ name: _type,
6513
+ value
6514
+ }))
6515
+ }), raise({
6516
+ type: "insert.break"
6517
+ })] : [raise({
6518
+ type: "insert.span",
6519
+ text: textRun,
6520
+ decorators: activeDecorators,
6521
+ annotations: activeAnnotations.map(({
6522
+ _key,
6523
+ _type,
6524
+ ...value
6525
+ }) => ({
6526
+ name: _type,
6527
+ value
6528
+ }))
6529
+ })])]
6530
+ }),
6531
+ defineBehavior({
6532
+ on: "deserialization.success",
6533
+ actions: [({
6534
+ event
6535
+ }) => [raise({
6536
+ type: "insert.blocks",
6537
+ blocks: event.data,
6538
+ placement: "auto"
6539
+ })]]
6540
+ }),
6541
+ defineBehavior({
6542
+ on: "deserialization.failure",
6543
+ actions: [({
6544
+ event
6545
+ }) => [{
6546
+ type: "effect",
6547
+ effect: () => {
6548
+ console.warn(`Deserialization of ${event.mimeType} failed with reason "${event.reason}"`);
6707
6549
  }
6708
- } : blockObject),
6709
- inlineObjects: pteSchema.inlineObjects.map((inlineObject) => objectNames[inlineObject.name] !== void 0 ? {
6710
- ...inlineObject,
6711
- name: objectNames[inlineObject.name]
6712
- } : inlineObject)
6713
- };
6550
+ }]]
6551
+ }),
6552
+ defineBehavior({
6553
+ on: "clipboard.paste",
6554
+ guard: ({
6555
+ snapshot
6556
+ }) => snapshot.context.selection && isSelectionExpanded(snapshot) ? {
6557
+ selection: snapshot.context.selection
6558
+ } : !1,
6559
+ actions: [({
6560
+ event
6561
+ }, {
6562
+ selection
6563
+ }) => [raise({
6564
+ type: "delete",
6565
+ at: selection
6566
+ }), raise({
6567
+ type: "deserialize",
6568
+ originEvent: event
6569
+ })]]
6570
+ }),
6571
+ defineBehavior({
6572
+ on: "clipboard.paste",
6573
+ actions: [({
6574
+ event
6575
+ }) => [raise({
6576
+ type: "deserialize",
6577
+ originEvent: event
6578
+ })]]
6579
+ }),
6580
+ defineBehavior({
6581
+ on: "input.*",
6582
+ actions: [({
6583
+ event
6584
+ }) => [raise({
6585
+ type: "deserialize",
6586
+ originEvent: event
6587
+ })]]
6588
+ }),
6589
+ ...abstractAnnotationBehaviors,
6590
+ ...abstractDecoratorBehaviors,
6591
+ ...abstractDeleteBehaviors,
6592
+ ...abstractInsertBehaviors,
6593
+ ...abstractListItemBehaviors,
6594
+ ...abstractMoveBehaviors,
6595
+ ...abstractStyleBehaviors,
6596
+ ...abstractSelectBehaviors,
6597
+ raiseDeserializationSuccessOrFailure,
6598
+ raiseSerializationSuccessOrFailure,
6599
+ raiseInsertSoftBreak
6600
+ ], abstractBehaviorEventTypes = ["annotation.toggle", "decorator.toggle", "delete.text", "deserialize", "deserialization.success", "deserialization.failure", "insert.blocks", "insert.break", "insert.soft break", "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"];
6601
+ function isAbstractBehaviorEvent(event) {
6602
+ return abstractBehaviorEventTypes.includes(event.type);
6714
6603
  }
6715
- function defaultCompare(a, b) {
6716
- return a === b;
6604
+ 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"];
6605
+ function isNativeBehaviorEvent(event) {
6606
+ return nativeBehaviorEventTypes.includes(event.type);
6717
6607
  }
6718
- function useEditorSelector(editor, selector, t0) {
6719
- const $ = c(3), compare = t0 === void 0 ? defaultCompare : t0;
6720
- let t1;
6721
- return $[0] !== editor || $[1] !== selector ? (t1 = (editorActorSnapshot) => {
6722
- const snapshot = getEditorSnapshot({
6723
- editorActorSnapshot,
6724
- slateEditorInstance: editor._internal.slateEditor.instance
6608
+ function isCustomBehaviorEvent(event) {
6609
+ return event.type.startsWith("custom.");
6610
+ }
6611
+ const debug$2 = debugWithName("behaviors:event");
6612
+ function eventCategory(event) {
6613
+ return isNativeBehaviorEvent(event) ? "native" : isAbstractBehaviorEvent(event) ? "abstract" : isCustomBehaviorEvent(event) ? "custom" : "synthetic";
6614
+ }
6615
+ function performEvent({
6616
+ mode,
6617
+ behaviors,
6618
+ event,
6619
+ editor,
6620
+ keyGenerator,
6621
+ schema,
6622
+ getSnapshot,
6623
+ nativeEvent
6624
+ }) {
6625
+ debug$2(`(${eventCategory(event)})`, JSON.stringify(event, null, 2));
6626
+ const defaultAction = isCustomBehaviorEvent(event) || isNativeBehaviorEvent(event) || isAbstractBehaviorEvent(event) ? void 0 : {
6627
+ ...event,
6628
+ editor
6629
+ }, eventBehaviors = (mode === "raise" ? [...behaviors, ...defaultBehaviors] : behaviors).filter((behavior) => {
6630
+ if (behavior.on === "*")
6631
+ return !0;
6632
+ const [listenedNamespace] = behavior.on.includes("*") && behavior.on.includes(".") ? behavior.on.split(".") : [void 0], [eventNamespace] = event.type.includes(".") ? event.type.split(".") : [void 0];
6633
+ return listenedNamespace !== void 0 && eventNamespace !== void 0 && listenedNamespace === eventNamespace || listenedNamespace !== void 0 && eventNamespace === void 0 && listenedNamespace === event.type ? !0 : behavior.on === event.type;
6634
+ });
6635
+ if (eventBehaviors.length === 0) {
6636
+ if (!defaultAction)
6637
+ return;
6638
+ withApplyingBehaviorActions(editor, () => {
6639
+ try {
6640
+ performAction({
6641
+ context: {
6642
+ keyGenerator,
6643
+ schema
6644
+ },
6645
+ action: defaultAction
6646
+ });
6647
+ } catch (error) {
6648
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6649
+ }
6650
+ }), editor.onChange();
6651
+ return;
6652
+ }
6653
+ const guardSnapshot = getSnapshot();
6654
+ let behaviorOverwritten = !1;
6655
+ for (const eventBehavior of eventBehaviors) {
6656
+ const shouldRun = eventBehavior.guard === void 0 || eventBehavior.guard({
6657
+ snapshot: guardSnapshot,
6658
+ event
6725
6659
  });
6726
- return selector(snapshot);
6727
- }, $[0] = editor, $[1] = selector, $[2] = t1) : t1 = $[2], useSelector(editor._internal.editorActor, t1, compare);
6660
+ if (shouldRun) {
6661
+ for (const actionSet of eventBehavior.actions) {
6662
+ const actionsSnapshot = getSnapshot(), actions = actionSet({
6663
+ snapshot: actionsSnapshot,
6664
+ event
6665
+ }, shouldRun);
6666
+ actions.length !== 0 && (behaviorOverwritten = behaviorOverwritten || actions.some((action) => action.type !== "effect"), withApplyingBehaviorActionSet(editor, () => {
6667
+ for (const action of actions) {
6668
+ if (action.type === "raise") {
6669
+ performEvent({
6670
+ mode,
6671
+ behaviors: mode === "execute" ? isCustomBehaviorEvent(action.event) ? [...behaviors, ...defaultBehaviors] : defaultBehaviors : [...behaviors, ...defaultBehaviors],
6672
+ event: action.event,
6673
+ editor,
6674
+ keyGenerator,
6675
+ schema,
6676
+ getSnapshot,
6677
+ nativeEvent: void 0
6678
+ });
6679
+ continue;
6680
+ }
6681
+ if (action.type === "execute") {
6682
+ if (isAbstractBehaviorEvent(action.event) || isCustomBehaviorEvent(action.event))
6683
+ performEvent({
6684
+ mode: "execute",
6685
+ behaviors: isCustomBehaviorEvent(action.event) ? [...behaviors, ...defaultBehaviors] : defaultBehaviors,
6686
+ event: action.event,
6687
+ editor,
6688
+ keyGenerator,
6689
+ schema,
6690
+ getSnapshot,
6691
+ nativeEvent: void 0
6692
+ });
6693
+ else {
6694
+ const internalAction2 = {
6695
+ ...action.event,
6696
+ editor
6697
+ };
6698
+ let actionFailed2 = !1;
6699
+ if (withApplyingBehaviorActions(editor, () => {
6700
+ try {
6701
+ performAction({
6702
+ context: {
6703
+ keyGenerator,
6704
+ schema
6705
+ },
6706
+ action: internalAction2
6707
+ });
6708
+ } catch (error) {
6709
+ console.error(new Error(`Performing action "${action.event.type}" as a result of "${event.type}" failed due to: ${error.message}`)), actionFailed2 = !0;
6710
+ }
6711
+ }), actionFailed2)
6712
+ break;
6713
+ editor.onChange();
6714
+ }
6715
+ continue;
6716
+ }
6717
+ const internalAction = {
6718
+ ...action,
6719
+ editor
6720
+ };
6721
+ let actionFailed = !1;
6722
+ if (withApplyingBehaviorActions(editor, () => {
6723
+ try {
6724
+ performAction({
6725
+ context: {
6726
+ keyGenerator,
6727
+ schema
6728
+ },
6729
+ action: internalAction
6730
+ });
6731
+ } catch (error) {
6732
+ console.error(new Error(`Performing action "${internalAction.type}" as a result of "${event.type}" failed due to: ${error.message}`)), actionFailed = !0;
6733
+ }
6734
+ }), actionFailed)
6735
+ break;
6736
+ editor.onChange();
6737
+ }
6738
+ }));
6739
+ }
6740
+ if (behaviorOverwritten) {
6741
+ nativeEvent?.preventDefault();
6742
+ break;
6743
+ }
6744
+ }
6745
+ }
6746
+ if (!behaviorOverwritten) {
6747
+ if (!defaultAction)
6748
+ return;
6749
+ withApplyingBehaviorActions(editor, () => {
6750
+ try {
6751
+ performAction({
6752
+ context: {
6753
+ keyGenerator,
6754
+ schema
6755
+ },
6756
+ action: defaultAction
6757
+ });
6758
+ } catch (error) {
6759
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6760
+ }
6761
+ }), editor.onChange();
6762
+ }
6728
6763
  }
6729
- function getEditorSnapshot({
6730
- editorActorSnapshot,
6731
- slateEditorInstance
6764
+ function createEditorSnapshot({
6765
+ converters,
6766
+ editor,
6767
+ keyGenerator,
6768
+ readOnly,
6769
+ schema,
6770
+ hasTag,
6771
+ internalDrag
6732
6772
  }) {
6773
+ const value = slateChildrenToBlocks(schema, editor.children), selection = editor.selection ? slateRangeToSelection({
6774
+ schema,
6775
+ editor,
6776
+ range: editor.selection
6777
+ }) : null;
6733
6778
  return {
6734
6779
  context: {
6735
- converters: [...editorActorSnapshot.context.converters],
6736
6780
  activeDecorators: getActiveDecorators({
6737
- schema: editorActorSnapshot.context.schema,
6738
- slateEditorInstance
6739
- }),
6740
- keyGenerator: editorActorSnapshot.context.keyGenerator,
6741
- readOnly: editorActorSnapshot.matches({
6742
- "edit mode": "read only"
6781
+ schema,
6782
+ slateEditorInstance: editor
6743
6783
  }),
6744
- schema: editorActorSnapshot.context.schema,
6745
- selection: editorActorSnapshot.context.selection,
6746
- value: slateChildrenToBlocks(editorActorSnapshot.context.schema, slateEditorInstance.children)
6784
+ converters,
6785
+ keyGenerator,
6786
+ readOnly,
6787
+ schema,
6788
+ selection,
6789
+ value
6747
6790
  },
6748
6791
  beta: {
6749
- hasTag: (tag) => editorActorSnapshot.hasTag(tag),
6750
- internalDrag: editorActorSnapshot.context.internalDrag
6792
+ hasTag,
6793
+ internalDrag
6751
6794
  }
6752
6795
  };
6753
6796
  }
6754
- const debug$2 = debugWithName("API:editable");
6755
- function createEditableAPI(editor, editorActor) {
6756
- const types = editorActor.getSnapshot().context.schema;
6757
- return {
6758
- focus: () => {
6759
- editorActor.send({
6760
- type: "focus",
6761
- editor
6762
- });
6763
- },
6764
- blur: () => {
6765
- editorActor.send({
6766
- type: "blur",
6767
- editor
6768
- });
6769
- },
6770
- toggleMark: (mark) => {
6771
- editorActor.send({
6772
- type: "behavior event",
6773
- behaviorEvent: {
6774
- type: "decorator.toggle",
6775
- decorator: mark
6776
- },
6777
- editor
6778
- });
6779
- },
6780
- toggleList: (listItem) => {
6781
- editorActor.send({
6782
- type: "behavior event",
6783
- behaviorEvent: {
6784
- type: "list item.toggle",
6785
- listItem
6786
- },
6787
- editor
6788
- });
6789
- },
6790
- toggleBlockStyle: (style) => {
6791
- editorActor.send({
6792
- type: "behavior event",
6793
- behaviorEvent: {
6794
- type: "style.toggle",
6795
- style
6796
- },
6797
- editor
6797
+ const editorMachine = setup({
6798
+ types: {
6799
+ context: {},
6800
+ events: {},
6801
+ emitted: {},
6802
+ input: {},
6803
+ tags: {}
6804
+ },
6805
+ actions: {
6806
+ "add behavior to context": assign({
6807
+ behaviors: ({
6808
+ context,
6809
+ event
6810
+ }) => (assertEvent(event, "add behavior"), /* @__PURE__ */ new Set([...context.behaviors, event.behavior]))
6811
+ }),
6812
+ "remove behavior from context": assign({
6813
+ behaviors: ({
6814
+ context,
6815
+ event
6816
+ }) => (assertEvent(event, "remove behavior"), context.behaviors.delete(event.behavior), /* @__PURE__ */ new Set([...context.behaviors]))
6817
+ }),
6818
+ "assign behaviors": assign({
6819
+ behaviors: ({
6820
+ event
6821
+ }) => (assertEvent(event, "update behaviors"), /* @__PURE__ */ new Set([...event.behaviors]))
6822
+ }),
6823
+ "assign schema": assign({
6824
+ schema: ({
6825
+ event
6826
+ }) => (assertEvent(event, "update schema"), event.schema)
6827
+ }),
6828
+ "emit patch event": enqueueActions(({
6829
+ event,
6830
+ enqueue
6831
+ }) => {
6832
+ assertEvent(event, "internal.patch"), enqueue.emit(event), enqueue.emit({
6833
+ type: "patch",
6834
+ patch: event.patch
6798
6835
  });
6836
+ }),
6837
+ "emit mutation event": emit(({
6838
+ event
6839
+ }) => (assertEvent(event, "mutation"), event)),
6840
+ "emit read only": emit({
6841
+ type: "read only"
6842
+ }),
6843
+ "emit editable": emit({
6844
+ type: "editable"
6845
+ }),
6846
+ "defer event": assign({
6847
+ pendingEvents: ({
6848
+ context,
6849
+ event
6850
+ }) => (assertEvent(event, ["internal.patch", "mutation"]), [...context.pendingEvents, event])
6851
+ }),
6852
+ "emit pending events": enqueueActions(({
6853
+ context,
6854
+ enqueue
6855
+ }) => {
6856
+ for (const event of context.pendingEvents)
6857
+ event.type === "internal.patch" ? (enqueue.emit(event), enqueue.emit({
6858
+ type: "patch",
6859
+ patch: event.patch
6860
+ })) : enqueue.emit(event);
6861
+ }),
6862
+ "emit ready": emit({
6863
+ type: "ready"
6864
+ }),
6865
+ "clear pending events": assign({
6866
+ pendingEvents: []
6867
+ }),
6868
+ "handle blur": ({
6869
+ event
6870
+ }) => {
6871
+ assertEvent(event, "blur");
6872
+ try {
6873
+ ReactEditor.blur(event.editor);
6874
+ } catch (error) {
6875
+ console.error(new Error(`Failed to blur editor: ${error.message}`));
6876
+ }
6799
6877
  },
6800
- isMarkActive: (mark) => {
6878
+ "handle focus": ({
6879
+ context
6880
+ }) => {
6881
+ if (!context.slateEditor) {
6882
+ console.error("No Slate editor found to focus");
6883
+ return;
6884
+ }
6801
6885
  try {
6802
- return isDecoratorActive({
6803
- editor,
6804
- decorator: mark
6805
- });
6806
- } catch (err) {
6807
- return console.warn(err), !1;
6886
+ const currentSelection = context.slateEditor.selection;
6887
+ ReactEditor.focus(context.slateEditor), currentSelection && Transforms.select(context.slateEditor, currentSelection);
6888
+ } catch (error) {
6889
+ console.error(new Error(`Failed to focus editor: ${error.message}`));
6808
6890
  }
6809
6891
  },
6810
- marks: () => ({
6811
- ...Editor.marks(editor) || {}
6812
- }).marks || [],
6813
- undo: () => {
6814
- editorActor.send({
6815
- type: "behavior event",
6816
- behaviorEvent: {
6817
- type: "history.undo"
6818
- },
6819
- editor
6892
+ "handle behavior event": ({
6893
+ context,
6894
+ event,
6895
+ self
6896
+ }) => {
6897
+ assertEvent(event, ["behavior event"]), performEvent({
6898
+ mode: "raise",
6899
+ behaviors: [...context.behaviors.values()],
6900
+ event: event.behaviorEvent,
6901
+ editor: event.editor,
6902
+ keyGenerator: context.keyGenerator,
6903
+ schema: context.schema,
6904
+ getSnapshot: () => createEditorSnapshot({
6905
+ converters: [...context.converters],
6906
+ editor: event.editor,
6907
+ keyGenerator: context.keyGenerator,
6908
+ readOnly: self.getSnapshot().matches({
6909
+ "edit mode": "read only"
6910
+ }),
6911
+ schema: context.schema,
6912
+ hasTag: (tag) => self.getSnapshot().hasTag(tag),
6913
+ internalDrag: context.internalDrag
6914
+ }),
6915
+ nativeEvent: event.nativeEvent
6820
6916
  });
6917
+ }
6918
+ },
6919
+ guards: {
6920
+ "slate is busy": ({
6921
+ context
6922
+ }) => context.slateEditor ? context.slateEditor.operations.length > 0 : !1
6923
+ }
6924
+ }).createMachine({
6925
+ id: "editor",
6926
+ context: ({
6927
+ input
6928
+ }) => ({
6929
+ behaviors: /* @__PURE__ */ new Set([...input.behaviors ?? coreBehaviors]),
6930
+ converters: new Set(input.converters ?? []),
6931
+ getLegacySchema: input.getLegacySchema,
6932
+ keyGenerator: input.keyGenerator,
6933
+ pendingEvents: [],
6934
+ schema: input.schema,
6935
+ selection: null,
6936
+ initialReadOnly: input.readOnly ?? !1,
6937
+ maxBlocks: input.maxBlocks,
6938
+ incomingValue: input.initialValue
6939
+ }),
6940
+ on: {
6941
+ "notify.blurred": {
6942
+ actions: emit(({
6943
+ event
6944
+ }) => ({
6945
+ ...event,
6946
+ type: "blurred"
6947
+ }))
6821
6948
  },
6822
- redo: () => {
6823
- editorActor.send({
6824
- type: "behavior event",
6825
- behaviorEvent: {
6826
- type: "history.redo"
6827
- },
6828
- editor
6829
- });
6949
+ "notify.done loading": {
6950
+ actions: emit({
6951
+ type: "done loading"
6952
+ })
6830
6953
  },
6831
- select: (selection) => {
6832
- const slateSelection = toSlateRange(selection, editor);
6833
- slateSelection ? Transforms.select(editor, slateSelection) : Transforms.deselect(editor), editor.onChange();
6954
+ "notify.error": {
6955
+ actions: emit(({
6956
+ event
6957
+ }) => ({
6958
+ ...event,
6959
+ type: "error"
6960
+ }))
6834
6961
  },
6835
- focusBlock: () => {
6836
- if (editor.selection) {
6837
- const block = Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
6838
- if (block)
6839
- return fromSlateValue([block], types.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
6840
- }
6962
+ "notify.invalid value": {
6963
+ actions: emit(({
6964
+ event
6965
+ }) => ({
6966
+ ...event,
6967
+ type: "invalid value"
6968
+ }))
6841
6969
  },
6842
- focusChild: () => {
6843
- if (editor.selection) {
6844
- const block = Node.descendant(editor, editor.selection.focus.path.slice(0, 1));
6845
- if (block && editor.isTextBlock(block))
6846
- return fromSlateValue([block], types.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0].children[editor.selection.focus.path[1]];
6847
- }
6970
+ "notify.focused": {
6971
+ actions: emit(({
6972
+ event
6973
+ }) => ({
6974
+ ...event,
6975
+ type: "focused"
6976
+ }))
6848
6977
  },
6849
- insertChild: (type, value) => {
6850
- if (type.name !== types.span.name)
6851
- return editorActor.send({
6852
- type: "behavior event",
6853
- behaviorEvent: {
6854
- type: "insert.inline object",
6855
- inlineObject: {
6856
- name: type.name,
6857
- value
6858
- }
6859
- },
6860
- editor
6861
- }), editor.selection ? slateRangeToSelection({
6862
- schema: editorActor.getSnapshot().context.schema,
6863
- editor,
6864
- range: editor.selection
6865
- })?.focus.path ?? [] : [];
6866
- if (!editor.selection)
6867
- throw new Error("The editor has no selection");
6868
- const [focusBlock] = Array.from(Editor.nodes(editor, {
6869
- at: editor.selection.focus.path.slice(0, 1),
6870
- match: (n) => n._type === types.block.name
6871
- }))[0] || [void 0];
6872
- if (!focusBlock)
6873
- throw new Error("No focused text block");
6874
- if (type.name !== types.span.name && !types.inlineObjects.some((t) => t.name === type.name))
6875
- throw new Error("This type cannot be inserted as a child to a text block");
6876
- const child = toSlateValue([{
6877
- _key: editorActor.getSnapshot().context.keyGenerator(),
6878
- _type: types.block.name,
6879
- children: [{
6880
- _key: editorActor.getSnapshot().context.keyGenerator(),
6881
- _type: type.name,
6882
- ...value || {}
6883
- }]
6884
- }], {
6885
- schemaTypes: editorActor.getSnapshot().context.schema
6886
- })[0].children[0], focusChildPath = editor.selection.focus.path.slice(0, 2), isSpanNode = child._type === types.span.name, focusNode = Node.get(editor, focusChildPath);
6887
- return isSpanNode && focusNode._type !== types.span.name && (debug$2("Inserting span child next to inline object child, moving selection + 1"), editor.move({
6888
- distance: 1,
6889
- unit: "character"
6890
- })), Transforms.insertNodes(editor, child, {
6891
- select: !0,
6892
- at: editor.selection
6893
- }), editor.onChange(), editor.selection ? slateRangeToSelection({
6894
- schema: editorActor.getSnapshot().context.schema,
6895
- editor,
6896
- range: editor.selection
6897
- })?.focus.path ?? [] : [];
6978
+ "notify.selection": {
6979
+ actions: [assign({
6980
+ selection: ({
6981
+ event
6982
+ }) => event.selection
6983
+ }), emit(({
6984
+ event
6985
+ }) => ({
6986
+ ...event,
6987
+ type: "selection"
6988
+ }))]
6898
6989
  },
6899
- insertBlock: (type, value) => (editorActor.send({
6900
- type: "behavior event",
6901
- behaviorEvent: {
6902
- type: "insert.block",
6903
- block: {
6904
- _type: type.name,
6905
- ...value || {}
6906
- },
6907
- placement: "auto"
6908
- },
6909
- editor
6910
- }), editor.selection ? slateRangeToSelection({
6911
- schema: editorActor.getSnapshot().context.schema,
6912
- editor,
6913
- range: editor.selection
6914
- })?.focus.path ?? [] : []),
6915
- hasBlockStyle: (style) => {
6916
- try {
6917
- return isStyleActive({
6918
- editor,
6919
- style
6920
- });
6921
- } catch {
6922
- return !1;
6923
- }
6990
+ "notify.unset": {
6991
+ actions: emit(({
6992
+ event
6993
+ }) => ({
6994
+ ...event,
6995
+ type: "unset"
6996
+ }))
6997
+ },
6998
+ "notify.loading": {
6999
+ actions: emit({
7000
+ type: "loading"
7001
+ })
6924
7002
  },
6925
- hasListStyle: (listItem) => {
6926
- try {
6927
- return isListItemActive({
6928
- editor,
6929
- listItem
6930
- });
6931
- } catch {
6932
- return !1;
6933
- }
7003
+ "notify.value changed": {
7004
+ actions: emit(({
7005
+ event
7006
+ }) => ({
7007
+ ...event,
7008
+ type: "value changed"
7009
+ }))
6934
7010
  },
6935
- isVoid: (element) => ![types.block.name, types.span.name].includes(element._type),
6936
- findByPath: (path) => {
6937
- const slatePath = toSlateRange({
6938
- focus: {
6939
- path,
6940
- offset: 0
6941
- },
6942
- anchor: {
6943
- path,
6944
- offset: 0
6945
- }
6946
- }, editor);
6947
- if (slatePath) {
6948
- const [block, blockPath] = Editor.node(editor, slatePath.focus.path.slice(0, 1));
6949
- if (block && blockPath && typeof block._key == "string") {
6950
- if (path.length === 1 && slatePath.focus.path.length === 1)
6951
- return [fromSlateValue([block], types.block.name)[0], [{
6952
- _key: block._key
6953
- }]];
6954
- const ptBlock = fromSlateValue([block], types.block.name, KEY_TO_VALUE_ELEMENT.get(editor))[0];
6955
- if (editor.isTextBlock(ptBlock)) {
6956
- const ptChild = ptBlock.children[slatePath.focus.path[1]];
6957
- if (ptChild)
6958
- return [ptChild, [{
6959
- _key: block._key
6960
- }, "children", {
6961
- _key: ptChild._key
6962
- }]];
6963
- }
6964
- }
6965
- }
6966
- return [void 0, void 0];
7011
+ "add behavior": {
7012
+ actions: "add behavior to context"
6967
7013
  },
6968
- findDOMNode: (element) => {
6969
- let node;
6970
- try {
6971
- const [item] = Array.from(Editor.nodes(editor, {
6972
- at: [],
6973
- match: (n) => n._key === element._key
6974
- }) || [])[0] || [void 0];
6975
- node = ReactEditor.toDOMNode(editor, item);
6976
- } catch {
6977
- }
6978
- return node;
7014
+ "remove behavior": {
7015
+ actions: "remove behavior from context"
6979
7016
  },
6980
- activeAnnotations: () => {
6981
- if (!editor.selection || editor.selection.focus.path.length < 2)
6982
- return [];
6983
- try {
6984
- const activeAnnotations = [], spans = Editor.nodes(editor, {
6985
- at: editor.selection,
6986
- match: (node) => Text.isText(node) && node.marks !== void 0 && Array.isArray(node.marks) && node.marks.length > 0
6987
- });
6988
- for (const [span, path] of spans) {
6989
- const [block] = Editor.node(editor, path, {
6990
- depth: 1
6991
- });
6992
- editor.isTextBlock(block) && block.markDefs?.forEach((def) => {
6993
- Text.isText(span) && span.marks && Array.isArray(span.marks) && span.marks.includes(def._key) && activeAnnotations.push(def);
6994
- });
6995
- }
6996
- return activeAnnotations;
6997
- } catch {
6998
- return [];
6999
- }
7017
+ patches: {
7018
+ actions: emit(({
7019
+ event
7020
+ }) => event)
7000
7021
  },
7001
- isAnnotationActive: (annotationType) => isAnnotationActive({
7002
- editor,
7003
- annotation: {
7004
- name: annotationType
7005
- }
7006
- }),
7007
- addAnnotation: (type, value) => {
7008
- let paths;
7009
- return Editor.withoutNormalizing(editor, () => {
7010
- paths = addAnnotationActionImplementation({
7011
- context: {
7012
- keyGenerator: editorActor.getSnapshot().context.keyGenerator,
7013
- schema: types
7022
+ "update behaviors": {
7023
+ actions: "assign behaviors"
7024
+ },
7025
+ "update key generator": {
7026
+ actions: assign({
7027
+ keyGenerator: ({
7028
+ event
7029
+ }) => event.keyGenerator
7030
+ })
7031
+ },
7032
+ "update schema": {
7033
+ actions: "assign schema"
7034
+ },
7035
+ "update value": {
7036
+ actions: assign({
7037
+ incomingValue: ({
7038
+ event
7039
+ }) => event.value
7040
+ })
7041
+ },
7042
+ "update maxBlocks": {
7043
+ actions: assign({
7044
+ maxBlocks: ({
7045
+ event
7046
+ }) => event.maxBlocks
7047
+ })
7048
+ }
7049
+ },
7050
+ type: "parallel",
7051
+ states: {
7052
+ "edit mode": {
7053
+ initial: "read only",
7054
+ states: {
7055
+ "read only": {
7056
+ initial: "determine initial edit mode",
7057
+ on: {
7058
+ "behavior event": {
7059
+ actions: "handle behavior event",
7060
+ guard: ({
7061
+ event
7062
+ }) => 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"
7063
+ }
7014
7064
  },
7015
- action: {
7016
- annotation: {
7017
- name: type.name,
7018
- value: value ?? {}
7065
+ states: {
7066
+ "determine initial edit mode": {
7067
+ on: {
7068
+ "done syncing initial value": [{
7069
+ target: "#editor.edit mode.read only.read only",
7070
+ guard: ({
7071
+ context
7072
+ }) => context.initialReadOnly
7073
+ }, {
7074
+ target: "#editor.edit mode.editable"
7075
+ }]
7076
+ }
7019
7077
  },
7020
- editor
7078
+ "read only": {
7079
+ on: {
7080
+ "update readOnly": {
7081
+ guard: ({
7082
+ event
7083
+ }) => !event.readOnly,
7084
+ target: "#editor.edit mode.editable",
7085
+ actions: ["emit editable"]
7086
+ }
7087
+ }
7088
+ }
7021
7089
  }
7022
- });
7023
- }), editor.onChange(), paths;
7024
- },
7025
- delete: (selection, options) => {
7026
- if (selection) {
7027
- const range = toSlateRange(selection, editor);
7028
- if (!(range && range.anchor.path.length > 0 && range.focus.path.length > 0))
7029
- throw new Error("Invalid range");
7030
- if (range) {
7031
- if (!options?.mode || options?.mode === "selected") {
7032
- debug$2("Deleting content in selection"), Transforms.delete(editor, {
7033
- at: range,
7034
- hanging: !0,
7035
- voids: !0
7036
- }), editor.onChange();
7037
- return;
7090
+ },
7091
+ editable: {
7092
+ on: {
7093
+ "update readOnly": {
7094
+ guard: ({
7095
+ event
7096
+ }) => event.readOnly,
7097
+ target: "#editor.edit mode.read only.read only",
7098
+ actions: ["emit read only"]
7099
+ },
7100
+ "behavior event": {
7101
+ actions: "handle behavior event"
7102
+ },
7103
+ blur: {
7104
+ actions: "handle blur"
7105
+ },
7106
+ focus: {
7107
+ target: ".focusing",
7108
+ actions: [assign({
7109
+ slateEditor: ({
7110
+ event
7111
+ }) => event.editor
7112
+ })]
7113
+ }
7114
+ },
7115
+ initial: "idle",
7116
+ states: {
7117
+ idle: {
7118
+ on: {
7119
+ dragstart: {
7120
+ actions: [assign({
7121
+ internalDrag: ({
7122
+ event
7123
+ }) => ({
7124
+ ghost: event.ghost,
7125
+ origin: event.origin
7126
+ })
7127
+ })],
7128
+ target: "dragging internally"
7129
+ }
7130
+ }
7131
+ },
7132
+ focusing: {
7133
+ initial: "checking if busy",
7134
+ states: {
7135
+ "checking if busy": {
7136
+ always: [{
7137
+ guard: "slate is busy",
7138
+ target: "busy"
7139
+ }, {
7140
+ target: "#editor.edit mode.editable.idle",
7141
+ actions: ["handle focus"]
7142
+ }]
7143
+ },
7144
+ busy: {
7145
+ after: {
7146
+ 10: {
7147
+ target: "checking if busy"
7148
+ }
7149
+ }
7150
+ }
7151
+ }
7152
+ },
7153
+ "dragging internally": {
7154
+ exit: [({
7155
+ context
7156
+ }) => {
7157
+ if (context.internalDrag?.ghost)
7158
+ try {
7159
+ context.internalDrag.ghost.parentNode?.removeChild(context.internalDrag.ghost);
7160
+ } catch (error) {
7161
+ console.error(new Error(`Removing the internal drag ghost failed due to: ${error.message}`));
7162
+ }
7163
+ }, assign({
7164
+ internalDrag: void 0
7165
+ })],
7166
+ tags: ["dragging internally"],
7167
+ on: {
7168
+ dragend: {
7169
+ target: "idle"
7170
+ },
7171
+ drop: {
7172
+ target: "idle"
7173
+ }
7174
+ }
7175
+ }
7038
7176
  }
7039
- options?.mode === "blocks" && (debug$2("Deleting blocks touched by selection"), Transforms.removeNodes(editor, {
7040
- at: range,
7041
- voids: !0,
7042
- match: (node) => editor.isTextBlock(node) || !editor.isTextBlock(node) && Element.isElement(node)
7043
- })), options?.mode === "children" && (debug$2("Deleting children touched by selection"), Transforms.removeNodes(editor, {
7044
- at: range,
7045
- voids: !0,
7046
- match: (node) => node._type === types.span.name || // Text children
7047
- !editor.isTextBlock(node) && Element.isElement(node)
7048
- })), editor.children.length === 0 && (editor.children = [editor.pteCreateTextBlock({
7049
- decorators: []
7050
- })]), editor.onChange();
7051
7177
  }
7052
7178
  }
7053
7179
  },
7054
- removeAnnotation: (type) => {
7055
- editorActor.send({
7056
- type: "behavior event",
7057
- behaviorEvent: {
7058
- type: "annotation.remove",
7059
- annotation: {
7060
- name: type.name
7180
+ setup: {
7181
+ initial: "setting up",
7182
+ states: {
7183
+ "setting up": {
7184
+ exit: ["emit ready"],
7185
+ on: {
7186
+ "internal.patch": {
7187
+ actions: "defer event"
7188
+ },
7189
+ mutation: {
7190
+ actions: "defer event"
7191
+ },
7192
+ "done syncing initial value": {
7193
+ target: "pristine"
7194
+ }
7061
7195
  }
7062
7196
  },
7063
- editor
7064
- });
7065
- },
7066
- getSelection: () => {
7067
- let ptRange = null;
7068
- if (editor.selection) {
7069
- const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection);
7070
- if (existing)
7071
- return existing;
7072
- ptRange = slateRangeToSelection({
7073
- schema: editorActor.getSnapshot().context.schema,
7074
- editor,
7075
- range: editor.selection
7076
- }), SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange);
7077
- }
7078
- return ptRange;
7079
- },
7080
- getValue: () => fromSlateValue(editor.children, types.block.name, KEY_TO_VALUE_ELEMENT.get(editor)),
7081
- isCollapsedSelection: () => !!editor.selection && Range.isCollapsed(editor.selection),
7082
- isExpandedSelection: () => !!editor.selection && Range.isExpanded(editor.selection),
7083
- insertBreak: () => {
7084
- editor.insertBreak(), editor.onChange();
7085
- },
7086
- getFragment: () => fromSlateValue(editor.getFragment(), types.block.name),
7087
- isSelectionsOverlapping: (selectionA, selectionB) => {
7088
- const rangeA = toSlateRange(selectionA, editor), rangeB = toSlateRange(selectionB, editor);
7089
- return Range.isRange(rangeA) && Range.isRange(rangeB) && Range.includes(rangeA, rangeB);
7090
- }
7091
- };
7092
- }
7093
- function isAnnotationActive({
7094
- editor,
7095
- annotation
7096
- }) {
7097
- if (!editor.selection || editor.selection.focus.path.length < 2)
7098
- return !1;
7099
- try {
7100
- const spans = [...Editor.nodes(editor, {
7101
- at: editor.selection,
7102
- match: (node) => Text.isText(node)
7103
- })];
7104
- if (spans.length === 0 || spans.some(([span]) => !isPortableTextSpan$1(span) || !span.marks || span.marks?.length === 0)) return !1;
7105
- const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {
7106
- const [block] = Editor.node(editor, path, {
7107
- depth: 1
7108
- });
7109
- return editor.isTextBlock(block) && block.markDefs ? [...accMarkDefs, ...block.markDefs] : accMarkDefs;
7110
- }, []);
7111
- return spans.every(([span]) => isPortableTextSpan$1(span) ? span.marks?.map((markKey) => selectionMarkDefs.find((def) => def?._key === markKey)?._type)?.includes(annotation.name) : !1);
7112
- } catch {
7113
- return !1;
7114
- }
7115
- }
7116
- function createInternalEditor(config) {
7117
- const legacySchema = config.schemaDefinition ? compileSchemaDefinitionToLegacySchema(config.schemaDefinition) : createLegacySchema(config.schema.hasOwnProperty("jsonType") ? config.schema : compileType(config.schema)), editorSchema = legacySchemaToEditorSchema(legacySchema), editorActor = createActor(editorMachine, {
7118
- input: editorConfigToMachineInput({
7119
- ...config,
7120
- schema: editorSchema,
7121
- legacySchema
7122
- })
7123
- });
7124
- return editorActor.start(), createInternalEditorFromActor(editorActor, legacySchema);
7125
- }
7126
- function useCreateInternalEditor(config) {
7127
- const legacySchema = config.schemaDefinition ? compileSchemaDefinitionToLegacySchema(config.schemaDefinition) : createLegacySchema(config.schema.hasOwnProperty("jsonType") ? config.schema : compileType(config.schema)), editorSchema = legacySchemaToEditorSchema(legacySchema), editorActor = useActorRef(editorMachine, {
7128
- input: editorConfigToMachineInput({
7129
- ...config,
7130
- schema: editorSchema,
7131
- legacySchema
7132
- })
7133
- });
7134
- return useMemo(() => createInternalEditorFromActor(editorActor, legacySchema), [editorActor, legacySchema]);
7135
- }
7136
- function editorConfigToMachineInput(config) {
7137
- return {
7138
- behaviors: config.behaviors,
7139
- converters: createCoreConverters(config.legacySchema),
7140
- keyGenerator: config.keyGenerator ?? defaultKeyGenerator,
7141
- maxBlocks: config.maxBlocks,
7142
- readOnly: config.readOnly,
7143
- schema: config.schema,
7144
- initialValue: config.initialValue
7145
- };
7146
- }
7147
- function createInternalEditorFromActor(editorActor, legacySchema) {
7148
- const slateEditor = createSlateEditor({
7149
- editorActor
7150
- }), editable = createEditableAPI(slateEditor.instance, editorActor);
7151
- return {
7152
- getSnapshot: () => getEditorSnapshot({
7153
- editorActorSnapshot: editorActor.getSnapshot(),
7154
- slateEditorInstance: slateEditor.instance
7155
- }),
7156
- registerBehavior: (config) => (editorActor.send({
7157
- type: "add behavior",
7158
- behavior: config.behavior
7159
- }), () => {
7160
- editorActor.send({
7161
- type: "remove behavior",
7162
- behavior: config.behavior
7163
- });
7164
- }),
7165
- send: (event) => {
7166
- switch (event.type) {
7167
- case "add behavior":
7168
- case "remove behavior":
7169
- case "update behaviors":
7170
- case "update key generator":
7171
- case "update readOnly":
7172
- case "patches":
7173
- case "update value":
7174
- case "update schema":
7175
- case "update maxBlocks":
7176
- editorActor.send(event);
7177
- break;
7178
- case "blur":
7179
- editorActor.send({
7180
- type: "blur",
7181
- editor: slateEditor.instance
7182
- });
7183
- break;
7184
- case "focus":
7185
- editorActor.send({
7186
- type: "focus",
7187
- editor: slateEditor.instance
7188
- });
7189
- break;
7190
- case "insert.block object":
7191
- editorActor.send({
7192
- type: "behavior event",
7193
- behaviorEvent: {
7194
- type: "insert.block",
7195
- block: {
7196
- _type: event.blockObject.name,
7197
- ...event.blockObject.value ?? {}
7198
- },
7199
- placement: event.placement
7197
+ pristine: {
7198
+ initial: "idle",
7199
+ states: {
7200
+ idle: {
7201
+ on: {
7202
+ normalizing: {
7203
+ target: "normalizing"
7204
+ },
7205
+ "internal.patch": {
7206
+ actions: "defer event",
7207
+ target: "#editor.setup.dirty"
7208
+ },
7209
+ mutation: {
7210
+ actions: "defer event",
7211
+ target: "#editor.setup.dirty"
7212
+ }
7213
+ }
7200
7214
  },
7201
- editor: slateEditor.instance
7202
- });
7203
- break;
7204
- default:
7205
- editorActor.send({
7206
- type: "behavior event",
7207
- behaviorEvent: event,
7208
- editor: slateEditor.instance
7209
- });
7210
- }
7211
- },
7212
- on: (event, listener) => editorActor.on(event, (event2) => {
7213
- switch (event2.type) {
7214
- case "blurred":
7215
- case "done loading":
7216
- case "editable":
7217
- case "error":
7218
- case "focused":
7219
- case "invalid value":
7220
- case "loading":
7221
- case "mutation":
7222
- case "patch":
7223
- case "read only":
7224
- case "ready":
7225
- case "selection":
7226
- case "value changed":
7227
- listener(event2);
7228
- break;
7215
+ normalizing: {
7216
+ on: {
7217
+ "done normalizing": {
7218
+ target: "idle"
7219
+ },
7220
+ "internal.patch": {
7221
+ actions: "defer event"
7222
+ },
7223
+ mutation: {
7224
+ actions: "defer event"
7225
+ }
7226
+ }
7227
+ }
7228
+ }
7229
+ },
7230
+ dirty: {
7231
+ entry: ["emit pending events", "clear pending events"],
7232
+ on: {
7233
+ "internal.patch": {
7234
+ actions: "emit patch event"
7235
+ },
7236
+ mutation: {
7237
+ actions: "emit mutation event"
7238
+ }
7239
+ }
7240
+ }
7229
7241
  }
7230
- }),
7231
- _internal: {
7232
- editable,
7233
- editorActor,
7234
- legacySchema,
7235
- slateEditor
7236
7242
  }
7237
- };
7238
- }
7239
- const EditorActorContext = createContext({}), PortableTextEditorContext = createContext(null), usePortableTextEditor = () => {
7243
+ }
7244
+ }), PortableTextEditorContext = createContext(null), usePortableTextEditor = () => {
7240
7245
  const editor = useContext(PortableTextEditorContext);
7241
7246
  if (!editor)
7242
7247
  throw new Error("The `usePortableTextEditor` hook must be used inside the <PortableTextEditor> component's context.");
@@ -7281,13 +7286,23 @@ class PortableTextEditor extends Component {
7281
7286
  * The editor API (currently implemented with Slate).
7282
7287
  */
7283
7288
  constructor(props) {
7284
- super(props), props.editor ? this.editor = props.editor : this.editor = createInternalEditor({
7285
- keyGenerator: props.keyGenerator ?? defaultKeyGenerator,
7286
- schema: props.schemaType,
7287
- initialValue: props.value,
7288
- maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10),
7289
- readOnly: props.readOnly
7290
- }), this.schemaTypes = this.editor._internal.legacySchema, this.editable = this.editor._internal.editable;
7289
+ if (super(props), props.editor)
7290
+ this.editor = props.editor, this.schemaTypes = this.editor._internal.editorActor.getSnapshot().context.getLegacySchema();
7291
+ else {
7292
+ const legacySchema = createLegacySchema(props.schemaType.hasOwnProperty("jsonType") ? props.schemaType : compileType(props.schemaType)), schema = legacySchemaToEditorSchema(legacySchema), editorActor = createActor(editorMachine, {
7293
+ input: {
7294
+ converters: createCoreConverters(legacySchema),
7295
+ getLegacySchema: () => legacySchema,
7296
+ initialValue: props.value,
7297
+ keyGenerator: props.keyGenerator ?? defaultKeyGenerator,
7298
+ maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10),
7299
+ readOnly: props.readOnly,
7300
+ schema
7301
+ }
7302
+ });
7303
+ editorActor.start(), this.editor = createInternalEditor(editorActor), this.schemaTypes = legacySchema;
7304
+ }
7305
+ this.editable = this.editor._internal.editable;
7291
7306
  }
7292
7307
  componentDidUpdate(prevProps) {
7293
7308
  !this.props.editor && !prevProps.editor && this.props.schemaType !== prevProps.schemaType && (this.schemaTypes = createLegacySchema(this.props.schemaType.hasOwnProperty("jsonType") ? this.props.schemaType : compileType(this.props.schemaType)), this.editor._internal.editorActor.send({
@@ -7773,34 +7788,18 @@ function RouteEventsToChanges(props) {
7773
7788
  }
7774
7789
  const EditorContext = React.createContext(void 0);
7775
7790
  function EditorProvider(props) {
7776
- const $ = c(28), internalEditor = useCreateInternalEditor(props.initialConfig), editorActor = internalEditor._internal.editorActor, slateEditor = internalEditor._internal.slateEditor;
7777
- let t0, t1;
7778
- $[0] !== internalEditor ? (t1 = new PortableTextEditor({
7791
+ const editorActor = useActorRef(editorMachine, {
7792
+ input: editorConfigToMachineInput(props.initialConfig)
7793
+ }), internalEditor = useMemo(() => createInternalEditor(editorActor), [editorActor]), portableTextEditor = useMemo(() => new PortableTextEditor({
7779
7794
  editor: internalEditor
7780
- }), $[0] = internalEditor, $[1] = t1) : t1 = $[1], t0 = t1;
7781
- const portableTextEditor = t0;
7782
- let t2;
7783
- $[2] !== portableTextEditor.change$ ? (t2 = (change) => {
7784
- portableTextEditor.change$.next(change);
7785
- }, $[2] = portableTextEditor.change$, $[3] = t2) : t2 = $[3];
7786
- let t3;
7787
- $[4] !== editorActor || $[5] !== t2 ? (t3 = /* @__PURE__ */ jsx(RouteEventsToChanges, { editorActor, onChange: t2 }), $[4] = editorActor, $[5] = t2, $[6] = t3) : t3 = $[6];
7788
- let t4;
7789
- $[7] !== editorActor || $[8] !== slateEditor.instance ? (t4 = /* @__PURE__ */ jsx(Synchronizer, { editorActor, slateEditor: slateEditor.instance }), $[7] = editorActor, $[8] = slateEditor.instance, $[9] = t4) : t4 = $[9];
7790
- let t5;
7791
- $[10] !== editorActor || $[11] !== props.children ? (t5 = /* @__PURE__ */ jsx(PortableTextEditorSelectionProvider, { editorActor, children: props.children }), $[10] = editorActor, $[11] = props.children, $[12] = t5) : t5 = $[12];
7792
- let t6;
7793
- $[13] !== portableTextEditor || $[14] !== t5 ? (t6 = /* @__PURE__ */ jsx(PortableTextEditorContext.Provider, { value: portableTextEditor, children: t5 }), $[13] = portableTextEditor, $[14] = t5, $[15] = t6) : t6 = $[15];
7794
- let t7;
7795
- $[16] !== slateEditor.initialValue || $[17] !== slateEditor.instance || $[18] !== t6 ? (t7 = /* @__PURE__ */ jsx(Slate, { editor: slateEditor.instance, initialValue: slateEditor.initialValue, children: t6 }), $[16] = slateEditor.initialValue, $[17] = slateEditor.instance, $[18] = t6, $[19] = t7) : t7 = $[19];
7796
- let t8;
7797
- $[20] !== editorActor || $[21] !== t7 ? (t8 = /* @__PURE__ */ jsx(EditorActorContext.Provider, { value: editorActor, children: t7 }), $[20] = editorActor, $[21] = t7, $[22] = t8) : t8 = $[22];
7798
- let t9;
7799
- return $[23] !== internalEditor || $[24] !== t3 || $[25] !== t4 || $[26] !== t8 ? (t9 = /* @__PURE__ */ jsxs(EditorContext.Provider, { value: internalEditor, children: [
7800
- t3,
7801
- t4,
7802
- t8
7803
- ] }), $[23] = internalEditor, $[24] = t3, $[25] = t4, $[26] = t8, $[27] = t9) : t9 = $[27], t9;
7795
+ }), [internalEditor]);
7796
+ return /* @__PURE__ */ jsxs(EditorContext.Provider, { value: internalEditor, children: [
7797
+ /* @__PURE__ */ jsx(RouteEventsToChanges, { editorActor, onChange: (change) => {
7798
+ portableTextEditor.change$.next(change);
7799
+ } }),
7800
+ /* @__PURE__ */ jsx(Synchronizer, { editorActor, slateEditor: internalEditor._internal.slateEditor.instance }),
7801
+ /* @__PURE__ */ jsx(EditorActorContext.Provider, { value: editorActor, children: /* @__PURE__ */ jsx(Slate, { editor: internalEditor._internal.slateEditor.instance, initialValue: internalEditor._internal.slateEditor.initialValue, children: /* @__PURE__ */ jsx(PortableTextEditorContext.Provider, { value: portableTextEditor, children: /* @__PURE__ */ jsx(PortableTextEditorSelectionProvider, { editorActor, children: props.children }) }) }) })
7802
+ ] });
7804
7803
  }
7805
7804
  function useEditor() {
7806
7805
  const editor = React.useContext(EditorContext);