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