@portabletext/editor 1.47.6 → 1.47.7

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";
@@ -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,2164 @@ 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
5679
- }
5680
- }) : !1, draggingEntireBlocks = isSelectingEntireBlocks({
5681
- context: {
5682
- ...snapshot.context,
5683
- 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
5684
5535
  }
5685
- }), draggedBlocks = getSelectedBlocks({
5686
- context: {
5687
- ...snapshot.context,
5688
- 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
+ }
5689
5554
  }
5690
- });
5691
- return droppingOnDragOrigin ? !1 : {
5692
- draggingEntireBlocks,
5693
- draggedBlocks,
5694
- dragOrigin,
5695
- originEvent: event.originEvent
5696
- };
5555
+ }
5556
+ return [void 0, void 0];
5697
5557
  },
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
- };
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 {
5735
5567
  }
5736
- return !1;
5568
+ return node;
5737
5569
  },
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}"`);
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
+ });
5585
+ }
5586
+ return activeAnnotations;
5587
+ } catch {
5588
+ return [];
5788
5589
  }
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);
5590
+ },
5591
+ isAnnotationActive: (annotationType) => isAnnotationActive({
5592
+ editor,
5593
+ annotation: {
5594
+ name: annotationType
5595
+ }
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;
5614
+ },
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
+ }
5642
+ }
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 : {
5866
- ...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}`));
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({
5877
+ ...event,
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
+ }) => !(event.placement !== "auto" || !getFocusTextBlock(snapshot)),
5945
+ actions: [({
5946
+ event
5947
+ }) => event.blocks.length === 1 ? [raise({
5948
+ type: "insert.block",
5949
+ block: event.blocks[0],
5950
+ placement: "auto",
5951
+ select: "end"
5952
+ })] : event.blocks.flatMap((block, index) => index === 0 ? [raise({
5953
+ type: "split.block"
5954
+ }), raise({
5955
+ type: "select.previous block",
5956
+ select: "end"
5957
+ }), raise({
5958
+ type: "insert.block",
5959
+ block,
5960
+ placement: "auto",
5961
+ select: "end"
5962
+ })] : index === event.blocks.length - 1 ? [raise({
5963
+ type: "select.next block",
5964
+ select: "start"
5965
+ }), raise({
5966
+ type: "insert.block",
5967
+ block,
5968
+ placement: "auto",
5969
+ select: "end"
5970
+ })] : [raise({
5971
+ type: "insert.block",
5972
+ block,
5973
+ placement: "after",
5974
+ select: "end"
5975
+ })])]
5976
+ }), defineBehavior({
5977
+ on: "insert.blocks",
5978
+ guard: ({
5979
+ event
5980
+ }) => event.placement === "auto",
5981
+ actions: [({
5982
+ event
5983
+ }) => event.blocks.map((block, index) => raise({
5984
+ type: "insert.block",
5985
+ block,
5986
+ placement: index === 0 ? "auto" : "after",
5987
+ select: "end"
5988
+ }))]
5989
+ }), defineBehavior({
5990
+ on: "insert.break",
5991
+ actions: [() => [raise({
5992
+ type: "split.block"
5993
+ })]]
5994
+ }), defineBehavior({
5995
+ on: "insert.soft break",
5996
+ actions: [() => [raise({
5997
+ type: "insert.text",
5998
+ text: `
5999
+ `
6000
+ })]]
6001
+ })], abstractListItemBehaviors = [defineBehavior({
6002
+ on: "list item.add",
6003
+ guard: ({
6004
+ snapshot
6005
+ }) => ({
6006
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6007
+ }),
6008
+ actions: [({
6009
+ event
6010
+ }, {
6011
+ selectedTextBlocks
6012
+ }) => selectedTextBlocks.map((block) => raise({
6013
+ type: "block.set",
6014
+ at: block.path,
6015
+ props: {
6016
+ level: 1,
6017
+ listItem: event.listItem
6018
+ }
6019
+ }))]
6020
+ }), defineBehavior({
6021
+ on: "list item.remove",
6022
+ guard: ({
6023
+ snapshot
6024
+ }) => ({
6025
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6026
+ }),
6027
+ actions: [(_, {
6028
+ selectedTextBlocks
6029
+ }) => selectedTextBlocks.map((block) => raise({
6030
+ type: "block.unset",
6031
+ at: block.path,
6032
+ props: ["level", "listItem"]
6033
+ }))]
6034
+ }), defineBehavior({
6035
+ on: "list item.toggle",
6036
+ guard: ({
6037
+ snapshot,
6038
+ event
6039
+ }) => isActiveListItem(event.listItem)(snapshot),
6040
+ actions: [({
6041
+ event
6042
+ }) => [raise({
6043
+ type: "list item.remove",
6044
+ listItem: event.listItem
6045
+ })]]
6046
+ }), defineBehavior({
6047
+ on: "list item.toggle",
6048
+ guard: ({
6049
+ snapshot,
6050
+ event
6051
+ }) => !isActiveListItem(event.listItem)(snapshot),
6052
+ actions: [({
6053
+ event
6054
+ }) => [raise({
6055
+ type: "list item.add",
6056
+ listItem: event.listItem
6057
+ })]]
6058
+ })], abstractMoveBehaviors = [defineBehavior({
6059
+ on: "move.block up",
6060
+ guard: ({
6061
+ snapshot,
6062
+ event
6063
+ }) => {
6064
+ const previousBlock = getPreviousBlock({
6065
+ context: {
6066
+ ...snapshot.context,
6067
+ selection: {
6068
+ anchor: {
6069
+ path: event.at,
6070
+ offset: 0
6071
+ },
6072
+ focus: {
6073
+ path: event.at,
6074
+ offset: 0
5976
6075
  }
5977
- }));
5978
- }
5979
- if (behaviorOverwritten) {
5980
- nativeEvent?.preventDefault();
5981
- break;
6076
+ }
5982
6077
  }
5983
- }
5984
- }
5985
- if (!behaviorOverwritten) {
5986
- if (!defaultAction)
5987
- return;
5988
- withApplyingBehaviorActions(editor, () => {
5989
- try {
5990
- performAction({
5991
- context: {
5992
- keyGenerator,
5993
- schema
6078
+ });
6079
+ return previousBlock ? {
6080
+ previousBlock
6081
+ } : !1;
6082
+ },
6083
+ actions: [({
6084
+ event
6085
+ }, {
6086
+ previousBlock
6087
+ }) => [raise({
6088
+ type: "move.block",
6089
+ at: event.at,
6090
+ to: previousBlock.path
6091
+ })]]
6092
+ }), defineBehavior({
6093
+ on: "move.block down",
6094
+ guard: ({
6095
+ snapshot,
6096
+ event
6097
+ }) => {
6098
+ const nextBlock = getNextBlock({
6099
+ context: {
6100
+ ...snapshot.context,
6101
+ selection: {
6102
+ anchor: {
6103
+ path: event.at,
6104
+ offset: 0
5994
6105
  },
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}`));
6106
+ focus: {
6107
+ path: event.at,
6108
+ offset: 0
6109
+ }
6110
+ }
5999
6111
  }
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: {}
6112
+ });
6113
+ return nextBlock ? {
6114
+ nextBlock
6115
+ } : !1;
6080
6116
  },
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;
6117
+ actions: [({
6118
+ event
6119
+ }, {
6120
+ nextBlock
6121
+ }) => [raise({
6122
+ type: "move.block",
6123
+ at: event.at,
6124
+ to: nextBlock.path
6125
+ })]]
6126
+ })], abstractSelectBehaviors = [defineBehavior({
6127
+ on: "select.previous block",
6128
+ guard: ({
6129
+ snapshot,
6130
+ event
6131
+ }) => {
6132
+ const previousBlock = getPreviousBlock(snapshot);
6133
+ if (!previousBlock)
6134
+ return !1;
6135
+ const point = event.select === "end" ? getBlockEndPoint(previousBlock) : getBlockStartPoint(previousBlock);
6136
+ return {
6137
+ selection: {
6138
+ anchor: point,
6139
+ focus: point
6160
6140
  }
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}`));
6141
+ };
6142
+ },
6143
+ actions: [(_, {
6144
+ selection
6145
+ }) => [raise({
6146
+ type: "select",
6147
+ at: selection
6148
+ })]]
6149
+ }), defineBehavior({
6150
+ on: "select.next block",
6151
+ guard: ({
6152
+ snapshot,
6153
+ event
6154
+ }) => {
6155
+ const nextBlock = getNextBlock(snapshot);
6156
+ if (!nextBlock)
6157
+ return !1;
6158
+ const point = event.select === "end" ? getBlockEndPoint(nextBlock) : getBlockStartPoint(nextBlock);
6159
+ return {
6160
+ selection: {
6161
+ anchor: point,
6162
+ focus: point
6166
6163
  }
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
- }
6164
+ };
6194
6165
  },
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
6166
+ actions: [(_, {
6167
+ selection
6168
+ }) => [raise({
6169
+ type: "select",
6170
+ at: selection
6171
+ })]]
6172
+ })], abstractStyleBehaviors = [defineBehavior({
6173
+ on: "style.add",
6174
+ guard: ({
6175
+ snapshot
6204
6176
  }) => ({
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
6177
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6214
6178
  }),
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
- }) => ({
6179
+ actions: [({
6180
+ event
6181
+ }, {
6182
+ selectedTextBlocks
6183
+ }) => selectedTextBlocks.map((block) => raise({
6184
+ type: "block.set",
6185
+ at: block.path,
6186
+ props: {
6187
+ style: event.style
6188
+ }
6189
+ }))]
6190
+ }), defineBehavior({
6191
+ on: "style.remove",
6192
+ guard: ({
6193
+ snapshot
6194
+ }) => ({
6195
+ selectedTextBlocks: getSelectedTextBlocks(snapshot)
6196
+ }),
6197
+ actions: [(_, {
6198
+ selectedTextBlocks
6199
+ }) => selectedTextBlocks.map((block) => raise({
6200
+ type: "block.unset",
6201
+ at: block.path,
6202
+ props: ["style"]
6203
+ }))]
6204
+ }), defineBehavior({
6205
+ on: "style.toggle",
6206
+ guard: ({
6207
+ snapshot,
6208
+ event
6209
+ }) => isActiveStyle(event.style)(snapshot),
6210
+ actions: [({
6211
+ event
6212
+ }) => [raise({
6213
+ type: "style.remove",
6214
+ style: event.style
6215
+ })]]
6216
+ }), defineBehavior({
6217
+ on: "style.toggle",
6218
+ guard: ({
6219
+ snapshot,
6220
+ event
6221
+ }) => !isActiveStyle(event.style)(snapshot),
6222
+ actions: [({
6223
+ event
6224
+ }) => [raise({
6225
+ type: "style.add",
6226
+ style: event.style
6227
+ })]]
6228
+ })], keyIs = {
6229
+ lineBreak: (event) => event.key === "Enter" && event.shiftKey
6230
+ }, raiseInsertSoftBreak = defineBehavior({
6231
+ on: "keyboard.keydown",
6232
+ guard: ({
6233
+ event
6234
+ }) => keyIs.lineBreak(event.originEvent),
6235
+ actions: [() => [raise({
6236
+ type: "insert.soft break"
6237
+ })]]
6238
+ }), raiseDeserializationSuccessOrFailure = defineBehavior({
6239
+ on: "deserialize",
6240
+ guard: ({
6241
+ snapshot,
6242
+ event
6243
+ }) => {
6244
+ let success;
6245
+ const failures = [];
6246
+ for (const converter of snapshot.context.converters) {
6247
+ const data = event.originEvent.originEvent.dataTransfer.getData(converter.mimeType);
6248
+ if (!data)
6249
+ continue;
6250
+ const deserializeEvent = converter.deserialize({
6251
+ snapshot,
6252
+ event: {
6253
+ type: "deserialize",
6254
+ data
6255
+ }
6256
+ });
6257
+ if (deserializeEvent.type === "deserialization.success") {
6258
+ success = deserializeEvent;
6259
+ break;
6260
+ } else
6261
+ failures.push(deserializeEvent);
6262
+ }
6263
+ return success || {
6264
+ type: "deserialization.failure",
6265
+ mimeType: "*/*",
6266
+ reason: failures.map((failure) => failure.reason).join(", ")
6267
+ };
6268
+ },
6269
+ actions: [({
6270
+ event
6271
+ }, deserializeEvent) => [raise({
6272
+ ...deserializeEvent,
6273
+ originEvent: event.originEvent
6274
+ })]]
6275
+ }), raiseSerializationSuccessOrFailure = defineBehavior({
6276
+ on: "serialize",
6277
+ guard: ({
6278
+ snapshot,
6279
+ event
6280
+ }) => {
6281
+ if (snapshot.context.converters.length === 0)
6282
+ return !1;
6283
+ const serializeEvents = snapshot.context.converters.map((converter) => converter.serialize({
6284
+ snapshot,
6285
+ event: {
6282
6286
  ...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"
6287
+ originEvent: event.originEvent.type
6288
+ }
6289
+ }));
6290
+ return serializeEvents.length === 0 ? !1 : serializeEvents;
6291
+ },
6292
+ actions: [({
6293
+ event
6294
+ }, serializeEvents) => serializeEvents.map((serializeEvent) => raise({
6295
+ ...serializeEvent,
6296
+ originEvent: event.originEvent
6297
+ }))]
6298
+ }), defaultBehaviors = [
6299
+ defineBehavior({
6300
+ on: "clipboard.copy",
6301
+ guard: ({
6302
+ snapshot
6303
+ }) => {
6304
+ const focusSpan = getFocusSpan(snapshot), selectionCollapsed = isSelectionCollapsed(snapshot);
6305
+ return focusSpan && selectionCollapsed;
6309
6306
  },
6310
- "update value": {
6311
- actions: assign({
6312
- incomingValue: ({
6313
- event
6314
- }) => event.value
6315
- })
6307
+ actions: [() => [{
6308
+ type: "noop"
6309
+ }]]
6310
+ }),
6311
+ defineBehavior({
6312
+ on: "clipboard.copy",
6313
+ actions: [({
6314
+ event
6315
+ }) => [raise({
6316
+ type: "serialize",
6317
+ originEvent: event
6318
+ })]]
6319
+ }),
6320
+ defineBehavior({
6321
+ on: "clipboard.cut",
6322
+ guard: ({
6323
+ snapshot
6324
+ }) => {
6325
+ const focusSpan = getFocusSpan(snapshot), selectionCollapsed = isSelectionCollapsed(snapshot);
6326
+ return focusSpan && selectionCollapsed;
6316
6327
  },
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
- }
6328
+ actions: [() => [{
6329
+ type: "noop"
6330
+ }]]
6331
+ }),
6332
+ defineBehavior({
6333
+ on: "clipboard.cut",
6334
+ guard: ({
6335
+ snapshot
6336
+ }) => snapshot.context.selection ? {
6337
+ selection: snapshot.context.selection
6338
+ } : !1,
6339
+ actions: [({
6340
+ event
6341
+ }, {
6342
+ selection
6343
+ }) => [raise({
6344
+ type: "serialize",
6345
+ originEvent: event
6346
+ }), raise({
6347
+ type: "delete",
6348
+ at: selection
6349
+ })]]
6350
+ }),
6351
+ defineBehavior({
6352
+ on: "drag.dragstart",
6353
+ actions: [({
6354
+ event
6355
+ }) => [raise({
6356
+ type: "serialize",
6357
+ originEvent: event
6358
+ })]]
6359
+ }),
6360
+ defineBehavior({
6361
+ on: "serialization.success",
6362
+ actions: [({
6363
+ event
6364
+ }) => [{
6365
+ type: "effect",
6366
+ effect: () => {
6367
+ event.originEvent.originEvent.dataTransfer.setData(event.mimeType, event.data);
6368
+ }
6369
+ }]]
6370
+ }),
6371
+ defineBehavior({
6372
+ on: "serialization.failure",
6373
+ actions: [({
6374
+ event
6375
+ }) => [{
6376
+ type: "effect",
6377
+ effect: () => {
6378
+ console.warn(`Serialization of ${event.mimeType} failed with reason "${event.reason}"`);
6453
6379
  }
6380
+ }]]
6381
+ }),
6382
+ defineBehavior({
6383
+ on: "drag.drop",
6384
+ guard: ({
6385
+ snapshot,
6386
+ event
6387
+ }) => {
6388
+ const dragOrigin = snapshot.beta.internalDrag?.origin, dropPosition = event.position.selection;
6389
+ return dragOrigin ? isOverlappingSelection(dropPosition)({
6390
+ ...snapshot,
6391
+ context: {
6392
+ ...snapshot.context,
6393
+ selection: dragOrigin.selection
6394
+ }
6395
+ }) : !1;
6454
6396
  },
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
- }
6397
+ actions: [() => [{
6398
+ type: "noop"
6399
+ }]]
6400
+ }),
6401
+ defineBehavior({
6402
+ on: "drag.drop",
6403
+ actions: [({
6404
+ event
6405
+ }) => [raise({
6406
+ type: "select",
6407
+ at: event.position.selection
6408
+ }), raise({
6409
+ type: "deserialize",
6410
+ originEvent: event
6411
+ })]]
6412
+ }),
6413
+ defineBehavior({
6414
+ on: "deserialization.success",
6415
+ guard: ({
6416
+ snapshot,
6417
+ event
6418
+ }) => {
6419
+ if (event.originEvent.type !== "drag.drop" || snapshot.beta.internalDrag === void 0)
6420
+ return !1;
6421
+ const dragOrigin = snapshot.beta.internalDrag.origin, dropPosition = event.originEvent.position.selection, droppingOnDragOrigin = dragOrigin ? isOverlappingSelection(dropPosition)({
6422
+ ...snapshot,
6423
+ context: {
6424
+ ...snapshot.context,
6425
+ selection: dragOrigin.selection
6515
6426
  }
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
6427
+ }) : !1, draggingEntireBlocks = isSelectingEntireBlocks({
6428
+ context: {
6429
+ ...snapshot.context,
6430
+ selection: dragOrigin.selection
6431
+ }
6432
+ }), draggedBlocks = getSelectedBlocks({
6433
+ context: {
6434
+ ...snapshot.context,
6435
+ selection: dragOrigin.selection
6436
+ }
6437
+ });
6438
+ return droppingOnDragOrigin ? !1 : {
6439
+ draggingEntireBlocks,
6440
+ draggedBlocks,
6441
+ dragOrigin,
6442
+ originEvent: event.originEvent
6443
+ };
6597
6444
  },
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
6445
+ actions: [({
6446
+ event
6447
+ }, {
6448
+ draggingEntireBlocks,
6449
+ draggedBlocks,
6450
+ dragOrigin,
6451
+ originEvent
6452
+ }) => [...draggingEntireBlocks ? draggedBlocks.map((block) => raise({
6453
+ type: "delete.block",
6454
+ at: block.path
6455
+ })) : [raise({
6456
+ type: "delete",
6457
+ at: dragOrigin.selection
6458
+ })], raise({
6459
+ type: "insert.blocks",
6460
+ blocks: event.data,
6461
+ placement: draggingEntireBlocks ? originEvent.position.block === "start" ? "before" : originEvent.position.block === "end" ? "after" : "auto" : "auto"
6462
+ })]]
6463
+ }),
6464
+ /**
6465
+ * If we are pasting text/plain into a text block then we can probably
6466
+ * assume that the intended behavior is that the pasted text inherits
6467
+ * formatting from the text it's pasted into.
6468
+ */
6469
+ defineBehavior({
6470
+ on: "deserialization.success",
6471
+ guard: ({
6472
+ snapshot,
6473
+ event
6474
+ }) => {
6475
+ if (getFocusTextBlock(snapshot) && event.mimeType === "text/plain" && event.originEvent.type === "clipboard.paste") {
6476
+ const activeDecorators = snapshot.context.activeDecorators;
6477
+ return {
6478
+ activeAnnotations: getActiveAnnotations(snapshot),
6479
+ activeDecorators,
6480
+ textRuns: event.data.flatMap((block) => isTextBlock(snapshot.context.schema, block) ? [getTextBlockText(block)] : [])
6481
+ };
6482
+ }
6483
+ return !1;
6621
6484
  },
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]
6485
+ actions: [(_, {
6486
+ activeAnnotations,
6487
+ activeDecorators,
6488
+ textRuns
6489
+ }) => textRuns.flatMap((textRun, index) => index !== textRuns.length - 1 ? [raise({
6490
+ type: "insert.span",
6491
+ text: textRun,
6492
+ decorators: activeDecorators,
6493
+ annotations: activeAnnotations.map(({
6494
+ _key,
6495
+ _type,
6496
+ ...value
6497
+ }) => ({
6498
+ name: _type,
6499
+ value
6500
+ }))
6501
+ }), raise({
6502
+ type: "insert.break"
6503
+ })] : [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
+ })])]
6516
+ }),
6517
+ defineBehavior({
6518
+ on: "deserialization.success",
6519
+ actions: [({
6520
+ event
6521
+ }) => [raise({
6522
+ type: "insert.blocks",
6523
+ blocks: event.data,
6524
+ placement: "auto"
6525
+ })]]
6526
+ }),
6527
+ defineBehavior({
6528
+ on: "deserialization.failure",
6529
+ actions: [({
6530
+ event
6531
+ }) => [{
6532
+ type: "effect",
6533
+ effect: () => {
6534
+ console.warn(`Deserialization of ${event.mimeType} failed with reason "${event.reason}"`);
6707
6535
  }
6708
- } : blockObject),
6709
- inlineObjects: pteSchema.inlineObjects.map((inlineObject) => objectNames[inlineObject.name] !== void 0 ? {
6710
- ...inlineObject,
6711
- name: objectNames[inlineObject.name]
6712
- } : inlineObject)
6713
- };
6536
+ }]]
6537
+ }),
6538
+ defineBehavior({
6539
+ on: "clipboard.paste",
6540
+ guard: ({
6541
+ snapshot
6542
+ }) => snapshot.context.selection && isSelectionExpanded(snapshot) ? {
6543
+ selection: snapshot.context.selection
6544
+ } : !1,
6545
+ actions: [({
6546
+ event
6547
+ }, {
6548
+ selection
6549
+ }) => [raise({
6550
+ type: "delete",
6551
+ at: selection
6552
+ }), raise({
6553
+ type: "deserialize",
6554
+ originEvent: event
6555
+ })]]
6556
+ }),
6557
+ defineBehavior({
6558
+ on: "clipboard.paste",
6559
+ actions: [({
6560
+ event
6561
+ }) => [raise({
6562
+ type: "deserialize",
6563
+ originEvent: event
6564
+ })]]
6565
+ }),
6566
+ defineBehavior({
6567
+ on: "input.*",
6568
+ actions: [({
6569
+ event
6570
+ }) => [raise({
6571
+ type: "deserialize",
6572
+ originEvent: event
6573
+ })]]
6574
+ }),
6575
+ ...abstractAnnotationBehaviors,
6576
+ ...abstractDecoratorBehaviors,
6577
+ ...abstractDeleteBehaviors,
6578
+ ...abstractInsertBehaviors,
6579
+ ...abstractListItemBehaviors,
6580
+ ...abstractMoveBehaviors,
6581
+ ...abstractStyleBehaviors,
6582
+ ...abstractSelectBehaviors,
6583
+ raiseDeserializationSuccessOrFailure,
6584
+ raiseSerializationSuccessOrFailure,
6585
+ raiseInsertSoftBreak
6586
+ ], 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"];
6587
+ function isAbstractBehaviorEvent(event) {
6588
+ return abstractBehaviorEventTypes.includes(event.type);
6714
6589
  }
6715
- function defaultCompare(a, b) {
6716
- return a === b;
6590
+ 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"];
6591
+ function isNativeBehaviorEvent(event) {
6592
+ return nativeBehaviorEventTypes.includes(event.type);
6717
6593
  }
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
6594
+ function isCustomBehaviorEvent(event) {
6595
+ return event.type.startsWith("custom.");
6596
+ }
6597
+ const debug$2 = debugWithName("behaviors:event");
6598
+ function eventCategory(event) {
6599
+ return isNativeBehaviorEvent(event) ? "native" : isAbstractBehaviorEvent(event) ? "abstract" : isCustomBehaviorEvent(event) ? "custom" : "synthetic";
6600
+ }
6601
+ function performEvent({
6602
+ mode,
6603
+ behaviors,
6604
+ event,
6605
+ editor,
6606
+ keyGenerator,
6607
+ schema,
6608
+ getSnapshot,
6609
+ nativeEvent
6610
+ }) {
6611
+ debug$2(`(${eventCategory(event)})`, JSON.stringify(event, null, 2));
6612
+ const defaultAction = isCustomBehaviorEvent(event) || isNativeBehaviorEvent(event) || isAbstractBehaviorEvent(event) ? void 0 : {
6613
+ ...event,
6614
+ editor
6615
+ }, eventBehaviors = (mode === "raise" ? [...behaviors, ...defaultBehaviors] : behaviors).filter((behavior) => {
6616
+ if (behavior.on === "*")
6617
+ return !0;
6618
+ const [listenedNamespace] = behavior.on.includes("*") && behavior.on.includes(".") ? behavior.on.split(".") : [void 0], [eventNamespace] = event.type.includes(".") ? event.type.split(".") : [void 0];
6619
+ return listenedNamespace !== void 0 && eventNamespace !== void 0 && listenedNamespace === eventNamespace || listenedNamespace !== void 0 && eventNamespace === void 0 && listenedNamespace === event.type ? !0 : behavior.on === event.type;
6620
+ });
6621
+ if (eventBehaviors.length === 0) {
6622
+ if (!defaultAction)
6623
+ return;
6624
+ withApplyingBehaviorActions(editor, () => {
6625
+ try {
6626
+ performAction({
6627
+ context: {
6628
+ keyGenerator,
6629
+ schema
6630
+ },
6631
+ action: defaultAction
6632
+ });
6633
+ } catch (error) {
6634
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6635
+ }
6636
+ }), editor.onChange();
6637
+ return;
6638
+ }
6639
+ const guardSnapshot = getSnapshot();
6640
+ let behaviorOverwritten = !1;
6641
+ for (const eventBehavior of eventBehaviors) {
6642
+ const shouldRun = eventBehavior.guard === void 0 || eventBehavior.guard({
6643
+ snapshot: guardSnapshot,
6644
+ event
6725
6645
  });
6726
- return selector(snapshot);
6727
- }, $[0] = editor, $[1] = selector, $[2] = t1) : t1 = $[2], useSelector(editor._internal.editorActor, t1, compare);
6646
+ if (shouldRun) {
6647
+ for (const actionSet of eventBehavior.actions) {
6648
+ const actionsSnapshot = getSnapshot(), actions = actionSet({
6649
+ snapshot: actionsSnapshot,
6650
+ event
6651
+ }, shouldRun);
6652
+ actions.length !== 0 && (behaviorOverwritten = behaviorOverwritten || actions.some((action) => action.type !== "effect"), withApplyingBehaviorActionSet(editor, () => {
6653
+ for (const action of actions) {
6654
+ if (action.type === "raise") {
6655
+ performEvent({
6656
+ mode,
6657
+ behaviors: mode === "execute" ? isCustomBehaviorEvent(action.event) ? [...behaviors, ...defaultBehaviors] : defaultBehaviors : [...behaviors, ...defaultBehaviors],
6658
+ event: action.event,
6659
+ editor,
6660
+ keyGenerator,
6661
+ schema,
6662
+ getSnapshot,
6663
+ nativeEvent: void 0
6664
+ });
6665
+ continue;
6666
+ }
6667
+ if (action.type === "execute") {
6668
+ if (isAbstractBehaviorEvent(action.event) || isCustomBehaviorEvent(action.event))
6669
+ performEvent({
6670
+ mode: "execute",
6671
+ behaviors: isCustomBehaviorEvent(action.event) ? [...behaviors, ...defaultBehaviors] : defaultBehaviors,
6672
+ event: action.event,
6673
+ editor,
6674
+ keyGenerator,
6675
+ schema,
6676
+ getSnapshot,
6677
+ nativeEvent: void 0
6678
+ });
6679
+ else {
6680
+ const internalAction2 = {
6681
+ ...action.event,
6682
+ editor
6683
+ };
6684
+ let actionFailed2 = !1;
6685
+ if (withApplyingBehaviorActions(editor, () => {
6686
+ try {
6687
+ performAction({
6688
+ context: {
6689
+ keyGenerator,
6690
+ schema
6691
+ },
6692
+ action: internalAction2
6693
+ });
6694
+ } catch (error) {
6695
+ console.error(new Error(`Performing action "${action.event.type}" as a result of "${event.type}" failed due to: ${error.message}`)), actionFailed2 = !0;
6696
+ }
6697
+ }), actionFailed2)
6698
+ break;
6699
+ editor.onChange();
6700
+ }
6701
+ continue;
6702
+ }
6703
+ const internalAction = {
6704
+ ...action,
6705
+ editor
6706
+ };
6707
+ let actionFailed = !1;
6708
+ if (withApplyingBehaviorActions(editor, () => {
6709
+ try {
6710
+ performAction({
6711
+ context: {
6712
+ keyGenerator,
6713
+ schema
6714
+ },
6715
+ action: internalAction
6716
+ });
6717
+ } catch (error) {
6718
+ console.error(new Error(`Performing action "${internalAction.type}" as a result of "${event.type}" failed due to: ${error.message}`)), actionFailed = !0;
6719
+ }
6720
+ }), actionFailed)
6721
+ break;
6722
+ editor.onChange();
6723
+ }
6724
+ }));
6725
+ }
6726
+ if (behaviorOverwritten) {
6727
+ nativeEvent?.preventDefault();
6728
+ break;
6729
+ }
6730
+ }
6731
+ }
6732
+ if (!behaviorOverwritten) {
6733
+ if (!defaultAction)
6734
+ return;
6735
+ withApplyingBehaviorActions(editor, () => {
6736
+ try {
6737
+ performAction({
6738
+ context: {
6739
+ keyGenerator,
6740
+ schema
6741
+ },
6742
+ action: defaultAction
6743
+ });
6744
+ } catch (error) {
6745
+ console.error(new Error(`Performing action "${defaultAction.type}" as a result of "${event.type}" failed due to: ${error.message}`));
6746
+ }
6747
+ }), editor.onChange();
6748
+ }
6728
6749
  }
6729
- function getEditorSnapshot({
6730
- editorActorSnapshot,
6731
- slateEditorInstance
6750
+ function createEditorSnapshot({
6751
+ converters,
6752
+ editor,
6753
+ keyGenerator,
6754
+ readOnly,
6755
+ schema,
6756
+ hasTag,
6757
+ internalDrag
6732
6758
  }) {
6759
+ const value = slateChildrenToBlocks(schema, editor.children), selection = editor.selection ? slateRangeToSelection({
6760
+ schema,
6761
+ editor,
6762
+ range: editor.selection
6763
+ }) : null;
6733
6764
  return {
6734
6765
  context: {
6735
- converters: [...editorActorSnapshot.context.converters],
6736
6766
  activeDecorators: getActiveDecorators({
6737
- schema: editorActorSnapshot.context.schema,
6738
- slateEditorInstance
6739
- }),
6740
- keyGenerator: editorActorSnapshot.context.keyGenerator,
6741
- readOnly: editorActorSnapshot.matches({
6742
- "edit mode": "read only"
6767
+ schema,
6768
+ slateEditorInstance: editor
6743
6769
  }),
6744
- schema: editorActorSnapshot.context.schema,
6745
- selection: editorActorSnapshot.context.selection,
6746
- value: slateChildrenToBlocks(editorActorSnapshot.context.schema, slateEditorInstance.children)
6770
+ converters,
6771
+ keyGenerator,
6772
+ readOnly,
6773
+ schema,
6774
+ selection,
6775
+ value
6747
6776
  },
6748
6777
  beta: {
6749
- hasTag: (tag) => editorActorSnapshot.hasTag(tag),
6750
- internalDrag: editorActorSnapshot.context.internalDrag
6778
+ hasTag,
6779
+ internalDrag
6751
6780
  }
6752
6781
  };
6753
6782
  }
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
6783
+ const editorMachine = setup({
6784
+ types: {
6785
+ context: {},
6786
+ events: {},
6787
+ emitted: {},
6788
+ input: {},
6789
+ tags: {}
6790
+ },
6791
+ actions: {
6792
+ "add behavior to context": assign({
6793
+ behaviors: ({
6794
+ context,
6795
+ event
6796
+ }) => (assertEvent(event, "add behavior"), /* @__PURE__ */ new Set([...context.behaviors, event.behavior]))
6797
+ }),
6798
+ "remove behavior from context": assign({
6799
+ behaviors: ({
6800
+ context,
6801
+ event
6802
+ }) => (assertEvent(event, "remove behavior"), context.behaviors.delete(event.behavior), /* @__PURE__ */ new Set([...context.behaviors]))
6803
+ }),
6804
+ "assign behaviors": assign({
6805
+ behaviors: ({
6806
+ event
6807
+ }) => (assertEvent(event, "update behaviors"), /* @__PURE__ */ new Set([...event.behaviors]))
6808
+ }),
6809
+ "assign schema": assign({
6810
+ schema: ({
6811
+ event
6812
+ }) => (assertEvent(event, "update schema"), event.schema)
6813
+ }),
6814
+ "emit patch event": enqueueActions(({
6815
+ event,
6816
+ enqueue
6817
+ }) => {
6818
+ assertEvent(event, "internal.patch"), enqueue.emit(event), enqueue.emit({
6819
+ type: "patch",
6820
+ patch: event.patch
6798
6821
  });
6822
+ }),
6823
+ "emit mutation event": emit(({
6824
+ event
6825
+ }) => (assertEvent(event, "mutation"), event)),
6826
+ "emit read only": emit({
6827
+ type: "read only"
6828
+ }),
6829
+ "emit editable": emit({
6830
+ type: "editable"
6831
+ }),
6832
+ "defer event": assign({
6833
+ pendingEvents: ({
6834
+ context,
6835
+ event
6836
+ }) => (assertEvent(event, ["internal.patch", "mutation"]), [...context.pendingEvents, event])
6837
+ }),
6838
+ "emit pending events": enqueueActions(({
6839
+ context,
6840
+ enqueue
6841
+ }) => {
6842
+ for (const event of context.pendingEvents)
6843
+ event.type === "internal.patch" ? (enqueue.emit(event), enqueue.emit({
6844
+ type: "patch",
6845
+ patch: event.patch
6846
+ })) : enqueue.emit(event);
6847
+ }),
6848
+ "emit ready": emit({
6849
+ type: "ready"
6850
+ }),
6851
+ "clear pending events": assign({
6852
+ pendingEvents: []
6853
+ }),
6854
+ "handle blur": ({
6855
+ event
6856
+ }) => {
6857
+ assertEvent(event, "blur");
6858
+ try {
6859
+ ReactEditor.blur(event.editor);
6860
+ } catch (error) {
6861
+ console.error(new Error(`Failed to blur editor: ${error.message}`));
6862
+ }
6799
6863
  },
6800
- isMarkActive: (mark) => {
6864
+ "handle focus": ({
6865
+ context
6866
+ }) => {
6867
+ if (!context.slateEditor) {
6868
+ console.error("No Slate editor found to focus");
6869
+ return;
6870
+ }
6801
6871
  try {
6802
- return isDecoratorActive({
6803
- editor,
6804
- decorator: mark
6805
- });
6806
- } catch (err) {
6807
- return console.warn(err), !1;
6872
+ const currentSelection = context.slateEditor.selection;
6873
+ ReactEditor.focus(context.slateEditor), currentSelection && Transforms.select(context.slateEditor, currentSelection);
6874
+ } catch (error) {
6875
+ console.error(new Error(`Failed to focus editor: ${error.message}`));
6808
6876
  }
6809
6877
  },
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
6878
+ "handle behavior event": ({
6879
+ context,
6880
+ event,
6881
+ self
6882
+ }) => {
6883
+ assertEvent(event, ["behavior event"]), performEvent({
6884
+ mode: "raise",
6885
+ behaviors: [...context.behaviors.values()],
6886
+ event: event.behaviorEvent,
6887
+ editor: event.editor,
6888
+ keyGenerator: context.keyGenerator,
6889
+ schema: context.schema,
6890
+ getSnapshot: () => createEditorSnapshot({
6891
+ converters: [...context.converters],
6892
+ editor: event.editor,
6893
+ keyGenerator: context.keyGenerator,
6894
+ readOnly: self.getSnapshot().matches({
6895
+ "edit mode": "read only"
6896
+ }),
6897
+ schema: context.schema,
6898
+ hasTag: (tag) => self.getSnapshot().hasTag(tag),
6899
+ internalDrag: context.internalDrag
6900
+ }),
6901
+ nativeEvent: event.nativeEvent
6820
6902
  });
6903
+ }
6904
+ },
6905
+ guards: {
6906
+ "slate is busy": ({
6907
+ context
6908
+ }) => context.slateEditor ? context.slateEditor.operations.length > 0 : !1
6909
+ }
6910
+ }).createMachine({
6911
+ id: "editor",
6912
+ context: ({
6913
+ input
6914
+ }) => ({
6915
+ behaviors: /* @__PURE__ */ new Set([...input.behaviors ?? coreBehaviors]),
6916
+ converters: new Set(input.converters ?? []),
6917
+ getLegacySchema: input.getLegacySchema,
6918
+ keyGenerator: input.keyGenerator,
6919
+ pendingEvents: [],
6920
+ schema: input.schema,
6921
+ selection: null,
6922
+ initialReadOnly: input.readOnly ?? !1,
6923
+ maxBlocks: input.maxBlocks,
6924
+ incomingValue: input.initialValue
6925
+ }),
6926
+ on: {
6927
+ "notify.blurred": {
6928
+ actions: emit(({
6929
+ event
6930
+ }) => ({
6931
+ ...event,
6932
+ type: "blurred"
6933
+ }))
6821
6934
  },
6822
- redo: () => {
6823
- editorActor.send({
6824
- type: "behavior event",
6825
- behaviorEvent: {
6826
- type: "history.redo"
6827
- },
6828
- editor
6829
- });
6935
+ "notify.done loading": {
6936
+ actions: emit({
6937
+ type: "done loading"
6938
+ })
6830
6939
  },
6831
- select: (selection) => {
6832
- const slateSelection = toSlateRange(selection, editor);
6833
- slateSelection ? Transforms.select(editor, slateSelection) : Transforms.deselect(editor), editor.onChange();
6940
+ "notify.error": {
6941
+ actions: emit(({
6942
+ event
6943
+ }) => ({
6944
+ ...event,
6945
+ type: "error"
6946
+ }))
6834
6947
  },
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
- }
6948
+ "notify.invalid value": {
6949
+ actions: emit(({
6950
+ event
6951
+ }) => ({
6952
+ ...event,
6953
+ type: "invalid value"
6954
+ }))
6841
6955
  },
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
- }
6956
+ "notify.focused": {
6957
+ actions: emit(({
6958
+ event
6959
+ }) => ({
6960
+ ...event,
6961
+ type: "focused"
6962
+ }))
6848
6963
  },
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 ?? [] : [];
6964
+ "notify.selection": {
6965
+ actions: [assign({
6966
+ selection: ({
6967
+ event
6968
+ }) => event.selection
6969
+ }), emit(({
6970
+ event
6971
+ }) => ({
6972
+ ...event,
6973
+ type: "selection"
6974
+ }))]
6898
6975
  },
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
- }
6976
+ "notify.unset": {
6977
+ actions: emit(({
6978
+ event
6979
+ }) => ({
6980
+ ...event,
6981
+ type: "unset"
6982
+ }))
6983
+ },
6984
+ "notify.loading": {
6985
+ actions: emit({
6986
+ type: "loading"
6987
+ })
6924
6988
  },
6925
- hasListStyle: (listItem) => {
6926
- try {
6927
- return isListItemActive({
6928
- editor,
6929
- listItem
6930
- });
6931
- } catch {
6932
- return !1;
6933
- }
6989
+ "notify.value changed": {
6990
+ actions: emit(({
6991
+ event
6992
+ }) => ({
6993
+ ...event,
6994
+ type: "value changed"
6995
+ }))
6934
6996
  },
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];
6997
+ "add behavior": {
6998
+ actions: "add behavior to context"
6967
6999
  },
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;
7000
+ "remove behavior": {
7001
+ actions: "remove behavior from context"
6979
7002
  },
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
- }
7003
+ patches: {
7004
+ actions: emit(({
7005
+ event
7006
+ }) => event)
7000
7007
  },
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
7008
+ "update behaviors": {
7009
+ actions: "assign behaviors"
7010
+ },
7011
+ "update key generator": {
7012
+ actions: assign({
7013
+ keyGenerator: ({
7014
+ event
7015
+ }) => event.keyGenerator
7016
+ })
7017
+ },
7018
+ "update schema": {
7019
+ actions: "assign schema"
7020
+ },
7021
+ "update value": {
7022
+ actions: assign({
7023
+ incomingValue: ({
7024
+ event
7025
+ }) => event.value
7026
+ })
7027
+ },
7028
+ "update maxBlocks": {
7029
+ actions: assign({
7030
+ maxBlocks: ({
7031
+ event
7032
+ }) => event.maxBlocks
7033
+ })
7034
+ }
7035
+ },
7036
+ type: "parallel",
7037
+ states: {
7038
+ "edit mode": {
7039
+ initial: "read only",
7040
+ states: {
7041
+ "read only": {
7042
+ initial: "determine initial edit mode",
7043
+ on: {
7044
+ "behavior event": {
7045
+ actions: "handle behavior event",
7046
+ guard: ({
7047
+ event
7048
+ }) => 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"
7049
+ }
7014
7050
  },
7015
- action: {
7016
- annotation: {
7017
- name: type.name,
7018
- value: value ?? {}
7051
+ states: {
7052
+ "determine initial edit mode": {
7053
+ on: {
7054
+ "done syncing initial value": [{
7055
+ target: "#editor.edit mode.read only.read only",
7056
+ guard: ({
7057
+ context
7058
+ }) => context.initialReadOnly
7059
+ }, {
7060
+ target: "#editor.edit mode.editable"
7061
+ }]
7062
+ }
7019
7063
  },
7020
- editor
7064
+ "read only": {
7065
+ on: {
7066
+ "update readOnly": {
7067
+ guard: ({
7068
+ event
7069
+ }) => !event.readOnly,
7070
+ target: "#editor.edit mode.editable",
7071
+ actions: ["emit editable"]
7072
+ }
7073
+ }
7074
+ }
7021
7075
  }
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;
7076
+ },
7077
+ editable: {
7078
+ on: {
7079
+ "update readOnly": {
7080
+ guard: ({
7081
+ event
7082
+ }) => event.readOnly,
7083
+ target: "#editor.edit mode.read only.read only",
7084
+ actions: ["emit read only"]
7085
+ },
7086
+ "behavior event": {
7087
+ actions: "handle behavior event"
7088
+ },
7089
+ blur: {
7090
+ actions: "handle blur"
7091
+ },
7092
+ focus: {
7093
+ target: ".focusing",
7094
+ actions: [assign({
7095
+ slateEditor: ({
7096
+ event
7097
+ }) => event.editor
7098
+ })]
7099
+ }
7100
+ },
7101
+ initial: "idle",
7102
+ states: {
7103
+ idle: {
7104
+ on: {
7105
+ dragstart: {
7106
+ actions: [assign({
7107
+ internalDrag: ({
7108
+ event
7109
+ }) => ({
7110
+ ghost: event.ghost,
7111
+ origin: event.origin
7112
+ })
7113
+ })],
7114
+ target: "dragging internally"
7115
+ }
7116
+ }
7117
+ },
7118
+ focusing: {
7119
+ initial: "checking if busy",
7120
+ states: {
7121
+ "checking if busy": {
7122
+ always: [{
7123
+ guard: "slate is busy",
7124
+ target: "busy"
7125
+ }, {
7126
+ target: "#editor.edit mode.editable.idle",
7127
+ actions: ["handle focus"]
7128
+ }]
7129
+ },
7130
+ busy: {
7131
+ after: {
7132
+ 10: {
7133
+ target: "checking if busy"
7134
+ }
7135
+ }
7136
+ }
7137
+ }
7138
+ },
7139
+ "dragging internally": {
7140
+ exit: [({
7141
+ context
7142
+ }) => {
7143
+ if (context.internalDrag?.ghost)
7144
+ try {
7145
+ context.internalDrag.ghost.parentNode?.removeChild(context.internalDrag.ghost);
7146
+ } catch (error) {
7147
+ console.error(new Error(`Removing the internal drag ghost failed due to: ${error.message}`));
7148
+ }
7149
+ }, assign({
7150
+ internalDrag: void 0
7151
+ })],
7152
+ tags: ["dragging internally"],
7153
+ on: {
7154
+ dragend: {
7155
+ target: "idle"
7156
+ },
7157
+ drop: {
7158
+ target: "idle"
7159
+ }
7160
+ }
7161
+ }
7038
7162
  }
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
7163
  }
7052
7164
  }
7053
7165
  },
7054
- removeAnnotation: (type) => {
7055
- editorActor.send({
7056
- type: "behavior event",
7057
- behaviorEvent: {
7058
- type: "annotation.remove",
7059
- annotation: {
7060
- name: type.name
7166
+ setup: {
7167
+ initial: "setting up",
7168
+ states: {
7169
+ "setting up": {
7170
+ exit: ["emit ready"],
7171
+ on: {
7172
+ "internal.patch": {
7173
+ actions: "defer event"
7174
+ },
7175
+ mutation: {
7176
+ actions: "defer event"
7177
+ },
7178
+ "done syncing initial value": {
7179
+ target: "pristine"
7180
+ }
7061
7181
  }
7062
7182
  },
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
7183
+ pristine: {
7184
+ initial: "idle",
7185
+ states: {
7186
+ idle: {
7187
+ on: {
7188
+ normalizing: {
7189
+ target: "normalizing"
7190
+ },
7191
+ "internal.patch": {
7192
+ actions: "defer event",
7193
+ target: "#editor.setup.dirty"
7194
+ },
7195
+ mutation: {
7196
+ actions: "defer event",
7197
+ target: "#editor.setup.dirty"
7198
+ }
7199
+ }
7200
7200
  },
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;
7201
+ normalizing: {
7202
+ on: {
7203
+ "done normalizing": {
7204
+ target: "idle"
7205
+ },
7206
+ "internal.patch": {
7207
+ actions: "defer event"
7208
+ },
7209
+ mutation: {
7210
+ actions: "defer event"
7211
+ }
7212
+ }
7213
+ }
7214
+ }
7215
+ },
7216
+ dirty: {
7217
+ entry: ["emit pending events", "clear pending events"],
7218
+ on: {
7219
+ "internal.patch": {
7220
+ actions: "emit patch event"
7221
+ },
7222
+ mutation: {
7223
+ actions: "emit mutation event"
7224
+ }
7225
+ }
7226
+ }
7229
7227
  }
7230
- }),
7231
- _internal: {
7232
- editable,
7233
- editorActor,
7234
- legacySchema,
7235
- slateEditor
7236
7228
  }
7237
- };
7238
- }
7239
- const EditorActorContext = createContext({}), PortableTextEditorContext = createContext(null), usePortableTextEditor = () => {
7229
+ }
7230
+ }), PortableTextEditorContext = createContext(null), usePortableTextEditor = () => {
7240
7231
  const editor = useContext(PortableTextEditorContext);
7241
7232
  if (!editor)
7242
7233
  throw new Error("The `usePortableTextEditor` hook must be used inside the <PortableTextEditor> component's context.");
@@ -7281,13 +7272,23 @@ class PortableTextEditor extends Component {
7281
7272
  * The editor API (currently implemented with Slate).
7282
7273
  */
7283
7274
  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;
7275
+ if (super(props), props.editor)
7276
+ this.editor = props.editor, this.schemaTypes = this.editor._internal.editorActor.getSnapshot().context.getLegacySchema();
7277
+ else {
7278
+ const legacySchema = createLegacySchema(props.schemaType.hasOwnProperty("jsonType") ? props.schemaType : compileType(props.schemaType)), schema = legacySchemaToEditorSchema(legacySchema), editorActor = createActor(editorMachine, {
7279
+ input: {
7280
+ converters: createCoreConverters(legacySchema),
7281
+ getLegacySchema: () => legacySchema,
7282
+ initialValue: props.value,
7283
+ keyGenerator: props.keyGenerator ?? defaultKeyGenerator,
7284
+ maxBlocks: props.maxBlocks === void 0 ? void 0 : Number.parseInt(props.maxBlocks.toString(), 10),
7285
+ readOnly: props.readOnly,
7286
+ schema
7287
+ }
7288
+ });
7289
+ editorActor.start(), this.editor = createInternalEditor(editorActor), this.schemaTypes = legacySchema;
7290
+ }
7291
+ this.editable = this.editor._internal.editable;
7291
7292
  }
7292
7293
  componentDidUpdate(prevProps) {
7293
7294
  !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 +7774,18 @@ function RouteEventsToChanges(props) {
7773
7774
  }
7774
7775
  const EditorContext = React.createContext(void 0);
7775
7776
  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({
7777
+ const editorActor = useActorRef(editorMachine, {
7778
+ input: editorConfigToMachineInput(props.initialConfig)
7779
+ }), internalEditor = useMemo(() => createInternalEditor(editorActor), [editorActor]), portableTextEditor = useMemo(() => new PortableTextEditor({
7779
7780
  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;
7781
+ }), [internalEditor]);
7782
+ return /* @__PURE__ */ jsxs(EditorContext.Provider, { value: internalEditor, children: [
7783
+ /* @__PURE__ */ jsx(RouteEventsToChanges, { editorActor, onChange: (change) => {
7784
+ portableTextEditor.change$.next(change);
7785
+ } }),
7786
+ /* @__PURE__ */ jsx(Synchronizer, { editorActor, slateEditor: internalEditor._internal.slateEditor.instance }),
7787
+ /* @__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 }) }) }) })
7788
+ ] });
7804
7789
  }
7805
7790
  function useEditor() {
7806
7791
  const editor = React.useContext(EditorContext);