@portabletext/editor 1.47.6 → 1.47.8

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