@portabletext/editor 1.6.1 → 1.7.0

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.
Files changed (36) hide show
  1. package/README.md +5 -0
  2. package/lib/index.d.mts +3317 -3488
  3. package/lib/index.d.ts +3317 -3488
  4. package/lib/index.esm.js +4316 -4081
  5. package/lib/index.esm.js.map +1 -1
  6. package/lib/index.js +4307 -4072
  7. package/lib/index.js.map +1 -1
  8. package/lib/index.mjs +4316 -4081
  9. package/lib/index.mjs.map +1 -1
  10. package/package.json +10 -11
  11. package/src/editor/Editable.tsx +5 -4
  12. package/src/editor/PortableTextEditor.tsx +90 -66
  13. package/src/editor/behavior/behavior.action.insert-break.ts +12 -2
  14. package/src/editor/behavior/behavior.actions.ts +51 -11
  15. package/src/editor/behavior/behavior.types.ts +23 -0
  16. package/src/editor/components/Synchronizer.tsx +11 -4
  17. package/src/editor/create-slate-editor.tsx +67 -0
  18. package/src/editor/editor-machine.ts +58 -8
  19. package/src/editor/key-generator.ts +30 -1
  20. package/src/editor/plugins/create-with-event-listeners.ts +62 -1
  21. package/src/editor/plugins/createWithEditableAPI.ts +800 -728
  22. package/src/editor/plugins/createWithMaxBlocks.ts +7 -2
  23. package/src/editor/plugins/createWithPatches.ts +4 -4
  24. package/src/editor/plugins/createWithPlaceholderBlock.ts +8 -3
  25. package/src/editor/plugins/createWithPortableTextMarkModel.ts +3 -4
  26. package/src/editor/plugins/createWithUndoRedo.ts +6 -7
  27. package/src/editor/plugins/createWithUtils.ts +2 -8
  28. package/src/editor/plugins/{index.ts → with-plugins.ts} +22 -79
  29. package/src/editor/use-editor.ts +46 -14
  30. package/src/index.ts +9 -1
  31. package/src/types/editor.ts +0 -1
  32. package/src/types/options.ts +1 -3
  33. package/src/utils/__tests__/operationToPatches.test.ts +7 -14
  34. package/src/utils/__tests__/patchToOperations.test.ts +4 -7
  35. package/src/editor/components/SlateContainer.tsx +0 -79
  36. package/src/editor/hooks/usePortableTextReadOnly.ts +0 -20
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/editor/behavior/behavior.types.ts","../src/editor/behavior/behavior.utils.ts","../src/editor/behavior/behavior.core.block-objects.ts","../src/editor/behavior/behavior.core.decorators.ts","../src/editor/behavior/behavior.core.lists.ts","../src/editor/behavior/behavior.core.ts","../src/editor/behavior/behavior.markdown.ts","../src/utils/getPortableTextMemberSchemaTypes.ts","../src/editor/define-schema.ts","../src/utils/debug.ts","../src/utils/paths.ts","../src/utils/ranges.ts","../src/utils/selection.ts","../src/utils/values.ts","../src/utils/weakMaps.ts","../src/editor/nodes/DefaultObject.tsx","../src/editor/nodes/index.ts","../src/editor/components/DraggableBlock.tsx","../src/editor/components/Element.tsx","../src/editor/hooks/usePortableTextEditor.ts","../src/editor/nodes/DefaultAnnotation.tsx","../src/utils/schema.ts","../src/utils/operationToPatches.ts","../src/editor/plugins/create-with-event-listeners.ts","../../../node_modules/.pnpm/@portabletext+toolkit@2.0.16/node_modules/@portabletext/toolkit/dist/index.js","../src/utils/sibling-utils.ts","../src/utils/withChanges.ts","../src/utils/withUndoRedo.ts","../src/editor/plugins/createWithPortableTextMarkModel.ts","../src/editor/plugins/createWithEditableAPI.ts","../src/editor/plugins/createWithMaxBlocks.ts","../src/editor/plugins/createWithObjectKeys.ts","../../../node_modules/.pnpm/@sanity+diff-match-patch@3.1.1/node_modules/@sanity/diff-match-patch/dist/index.js","../src/utils/applyPatch.ts","../src/utils/withoutPatching.ts","../src/editor/plugins/createWithUndoRedo.ts","../src/editor/plugins/createWithPatches.ts","../src/editor/plugins/createWithPlaceholderBlock.ts","../src/editor/plugins/createWithPortableTextBlockStyle.ts","../src/editor/plugins/createWithPortableTextLists.ts","../src/editor/plugins/createWithPortableTextSelections.ts","../src/editor/plugins/createWithSchemaTypes.ts","../src/editor/plugins/createWithUtils.ts","../src/editor/plugins/createWithHotKeys.ts","../src/utils/validateValue.ts","../src/editor/plugins/createWithInsertData.ts","../src/editor/plugins/index.ts","../src/editor/components/SlateContainer.tsx","../src/editor/hooks/usePortableTextReadOnly.ts","../src/editor/hooks/useSyncValue.ts","../src/editor/components/Synchronizer.tsx","../src/editor/editor-actor-context.ts","../src/editor/behavior/behavior.action.insert-break.ts","../src/editor/behavior/behavior.actions.ts","../src/editor/editor-machine.ts","../src/editor/hooks/usePortableTextEditorSelection.tsx","../src/editor/key-generator.ts","../src/editor/PortableTextEditor.tsx","../src/editor/components/Leaf.tsx","../src/editor/withSyncRangeDecorations.ts","../src/editor/Editable.tsx","../src/editor/use-editor.ts"],"sourcesContent":["import type {KeyedSegment, PortableTextBlock} from '@sanity/types'\nimport type {TextUnit} from 'slate'\nimport type {TextInsertTextOptions} from 'slate/dist/interfaces/transforms/text'\nimport type {\n EditorSelection,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\n\n/**\n * @alpha\n */\nexport type BehaviorContext = {\n schema: PortableTextMemberSchemaTypes\n value: Array<PortableTextBlock>\n selection: NonNullable<EditorSelection>\n}\n\n/**\n * @alpha\n */\nexport type BehaviorEvent =\n | {\n type: 'decorator.add'\n decorator: string\n }\n | {\n type: 'decorator.remove'\n decorator: string\n }\n | {\n type: 'decorator.toggle'\n decorator: string\n }\n | {\n type: 'delete backward'\n unit: TextUnit\n }\n | {\n type: 'delete forward'\n unit: TextUnit\n }\n | {\n type: 'insert soft break'\n }\n | {\n type: 'insert break'\n }\n | {\n type: 'insert text'\n text: string\n options?: TextInsertTextOptions\n }\n\n/**\n * @alpha\n */\nexport type BehaviorGuard<\n TBehaviorEvent extends BehaviorEvent,\n TGuardResponse,\n> = ({\n context,\n event,\n}: {\n event: TBehaviorEvent\n context: BehaviorContext\n}) => TGuardResponse | false\n\n/**\n * @alpha\n */\nexport type BehaviorActionIntend =\n | BehaviorEvent\n | {\n type: 'insert text block'\n decorators: Array<string>\n }\n | {\n type: 'set block'\n paths: Array<[KeyedSegment]>\n style?: string\n listItem?: string\n level?: number\n }\n | {\n type: 'unset block'\n paths: Array<[KeyedSegment]>\n props: Array<'style' | 'listItem' | 'level'>\n }\n | {\n type: 'delete'\n selection: NonNullable<EditorSelection>\n }\n | {\n type: 'effect'\n effect: () => void\n }\n | {\n type: 'select'\n selection: EditorSelection\n }\n | {\n type: 'reselect'\n }\n\n/**\n * @alpha\n */\nexport type BehaviorAction = BehaviorActionIntend & {\n editor: PortableTextSlateEditor\n}\n\n/**\n * @alpha\n */\nexport type Behavior<\n TBehaviorEventType extends BehaviorEvent['type'] = BehaviorEvent['type'],\n TGuardResponse = true,\n> = {\n /**\n * The internal editor event that triggers this behavior.\n */\n on: TBehaviorEventType\n /**\n * Predicate function that determines if the behavior should be executed.\n * Returning a non-nullable value from the guard will pass the value to the\n * actions and execute them.\n */\n guard?: BehaviorGuard<\n PickFromUnion<BehaviorEvent, 'type', TBehaviorEventType>,\n TGuardResponse\n >\n /**\n * Array of behavior action sets.\n */\n actions: Array<BehaviorActionIntendSet<TBehaviorEventType, TGuardResponse>>\n}\n\n/**\n * @alpha\n */\nexport type BehaviorActionIntendSet<\n TBehaviorEventType extends BehaviorEvent['type'] = BehaviorEvent['type'],\n TGuardResponse = true,\n> = (\n {\n context,\n event,\n }: {\n context: BehaviorContext\n event: PickFromUnion<BehaviorEvent, 'type', TBehaviorEventType>\n },\n guardResponse: TGuardResponse,\n) => Array<BehaviorActionIntend>\n\n/**\n * @alpha\n */\nexport function defineBehavior<\n TBehaviorEventType extends BehaviorEvent['type'],\n TGuardResponse = true,\n>(behavior: Behavior<TBehaviorEventType, TGuardResponse>): Behavior {\n return behavior as unknown as Behavior\n}\n\n/**\n * @alpha\n */\nexport type PickFromUnion<\n TUnion,\n TTagKey extends keyof TUnion,\n TPickedTags extends TUnion[TTagKey],\n> = TUnion extends Record<TTagKey, TPickedTags> ? TUnion : never\n","import {\n isKeySegment,\n isPortableTextSpan,\n isPortableTextTextBlock,\n type KeyedSegment,\n type PortableTextBlock,\n type PortableTextObject,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport type {BehaviorContext} from './behavior.types'\n\n/**\n * Selection utilities\n */\n\nexport function selectionIsCollapsed(context: BehaviorContext) {\n return (\n context.selection?.anchor.path.join() ===\n context.selection?.focus.path.join() &&\n context.selection?.anchor.offset === context.selection?.focus.offset\n )\n}\n\n/**\n * Value utilities\n */\n\nexport function getFocusBlock(\n context: BehaviorContext,\n): {node: PortableTextBlock; path: [KeyedSegment]} | undefined {\n const key = context.selection\n ? isKeySegment(context.selection.focus.path[0])\n ? context.selection.focus.path[0]._key\n : undefined\n : undefined\n\n const node = key\n ? context.value.find((block) => block._key === key)\n : undefined\n\n return node && key ? {node, path: [{_key: key}]} : undefined\n}\n\nexport function getFocusTextBlock(\n context: BehaviorContext,\n): {node: PortableTextTextBlock; path: [KeyedSegment]} | undefined {\n const focusBlock = getFocusBlock(context)\n\n return focusBlock && isPortableTextTextBlock(focusBlock.node)\n ? {node: focusBlock.node, path: focusBlock.path}\n : undefined\n}\n\nexport function getFocusBlockObject(\n context: BehaviorContext,\n): {node: PortableTextObject; path: [KeyedSegment]} | undefined {\n const focusBlock = getFocusBlock(context)\n\n return focusBlock && !isPortableTextTextBlock(focusBlock.node)\n ? {node: focusBlock.node, path: focusBlock.path}\n : undefined\n}\n\nexport function getFocusChild(context: BehaviorContext):\n | {\n node: PortableTextObject | PortableTextSpan\n path: [KeyedSegment, 'children', KeyedSegment]\n }\n | undefined {\n const focusBlock = getFocusTextBlock(context)\n\n if (!focusBlock) {\n return undefined\n }\n\n const key = context.selection\n ? isKeySegment(context.selection.focus.path[2])\n ? context.selection.focus.path[2]._key\n : undefined\n : undefined\n\n const node = key\n ? focusBlock.node.children.find((span) => span._key === key)\n : undefined\n\n return node && key\n ? {node, path: [...focusBlock.path, 'children', {_key: key}]}\n : undefined\n}\n\nexport function getFocusSpan(\n context: BehaviorContext,\n):\n | {node: PortableTextSpan; path: [KeyedSegment, 'children', KeyedSegment]}\n | undefined {\n const focusChild = getFocusChild(context)\n\n return focusChild && isPortableTextSpan(focusChild.node)\n ? {node: focusChild.node, path: focusChild.path}\n : undefined\n}\n\nexport function getSelectionStartBlock(context: BehaviorContext):\n | {\n node: PortableTextBlock\n path: [KeyedSegment]\n }\n | undefined {\n const key = context.selection.backward\n ? isKeySegment(context.selection.focus.path[0])\n ? context.selection.focus.path[0]._key\n : undefined\n : isKeySegment(context.selection.anchor.path[0])\n ? context.selection.anchor.path[0]._key\n : undefined\n\n const node = key\n ? context.value.find((block) => block._key === key)\n : undefined\n\n return node && key ? {node, path: [{_key: key}]} : undefined\n}\n\nexport function getSelectionEndBlock(context: BehaviorContext):\n | {\n node: PortableTextBlock\n path: [KeyedSegment]\n }\n | undefined {\n const key = context.selection.backward\n ? isKeySegment(context.selection.anchor.path[0])\n ? context.selection.anchor.path[0]._key\n : undefined\n : isKeySegment(context.selection.focus.path[0])\n ? context.selection.focus.path[0]._key\n : undefined\n\n const node = key\n ? context.value.find((block) => block._key === key)\n : undefined\n\n return node && key ? {node, path: [{_key: key}]} : undefined\n}\n\nexport function getPreviousBlock(\n context: BehaviorContext,\n): {node: PortableTextBlock; path: [KeyedSegment]} | undefined {\n let previousBlock: {node: PortableTextBlock; path: [KeyedSegment]} | undefined\n const selectionStartBlock = getSelectionStartBlock(context)\n\n if (!selectionStartBlock) {\n return undefined\n }\n\n let foundSelectionStartBlock = false\n\n for (const block of context.value) {\n if (block._key === selectionStartBlock.node._key) {\n foundSelectionStartBlock = true\n break\n }\n\n previousBlock = {node: block, path: [{_key: block._key}]}\n }\n\n if (foundSelectionStartBlock && previousBlock) {\n return previousBlock\n }\n\n return undefined\n}\n\nexport function getNextBlock(\n context: BehaviorContext,\n): {node: PortableTextBlock; path: [KeyedSegment]} | undefined {\n let nextBlock: {node: PortableTextBlock; path: [KeyedSegment]} | undefined\n const selectionEndBlock = getSelectionEndBlock(context)\n\n if (!selectionEndBlock) {\n return undefined\n }\n\n let foundSelectionEndBlock = false\n\n for (const block of context.value) {\n if (block._key === selectionEndBlock.node._key) {\n foundSelectionEndBlock = true\n continue\n }\n\n if (foundSelectionEndBlock) {\n nextBlock = {node: block, path: [{_key: block._key}]}\n break\n }\n }\n\n if (foundSelectionEndBlock && nextBlock) {\n return nextBlock\n }\n\n return undefined\n}\n\nexport function isEmptyTextBlock(block: PortableTextTextBlock) {\n return block.children.length === 1 && block.children[0].text === ''\n}\n","import {isPortableTextTextBlock} from '@sanity/types'\nimport {defineBehavior} from './behavior.types'\nimport {\n getFocusBlockObject,\n getFocusTextBlock,\n getNextBlock,\n getPreviousBlock,\n isEmptyTextBlock,\n selectionIsCollapsed,\n} from './behavior.utils'\n\nconst breakingBlockObject = defineBehavior({\n on: 'insert break',\n guard: ({context}) => {\n const focusBlockObject = getFocusBlockObject(context)\n\n return !!focusBlockObject\n },\n actions: [() => [{type: 'insert text block', decorators: []}]],\n})\n\nconst deletingEmptyTextBlockAfterBlockObject = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const focusTextBlock = getFocusTextBlock(context)\n const selectionCollapsed = selectionIsCollapsed(context)\n const previousBlock = getPreviousBlock(context)\n\n if (!focusTextBlock || !selectionCollapsed || !previousBlock) {\n return false\n }\n\n if (\n isEmptyTextBlock(focusTextBlock.node) &&\n !isPortableTextTextBlock(previousBlock.node)\n ) {\n return {focusTextBlock, previousBlock}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock, previousBlock}) => [\n {\n type: 'delete',\n selection: {\n anchor: {path: focusTextBlock.path, offset: 0},\n focus: {path: focusTextBlock.path, offset: 0},\n },\n },\n {\n type: 'select',\n selection: {\n anchor: {path: previousBlock.path, offset: 0},\n focus: {path: previousBlock.path, offset: 0},\n },\n },\n ],\n ],\n})\n\nconst deletingEmptyTextBlockBeforeBlockObject = defineBehavior({\n on: 'delete forward',\n guard: ({context}) => {\n const focusTextBlock = getFocusTextBlock(context)\n const selectionCollapsed = selectionIsCollapsed(context)\n const nextBlock = getNextBlock(context)\n\n if (!focusTextBlock || !selectionCollapsed || !nextBlock) {\n return false\n }\n\n if (\n isEmptyTextBlock(focusTextBlock.node) &&\n !isPortableTextTextBlock(nextBlock.node)\n ) {\n return {focusTextBlock, nextBlock}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock, nextBlock}) => [\n {\n type: 'delete',\n selection: {\n anchor: {path: focusTextBlock.path, offset: 0},\n focus: {path: focusTextBlock.path, offset: 0},\n },\n },\n {\n type: 'select',\n selection: {\n anchor: {path: nextBlock.path, offset: 0},\n focus: {path: nextBlock.path, offset: 0},\n },\n },\n ],\n ],\n})\n\nexport const coreBlockObjectBehaviors = {\n breakingBlockObject,\n deletingEmptyTextBlockAfterBlockObject,\n deletingEmptyTextBlockBeforeBlockObject,\n}\n","import {defineBehavior} from './behavior.types'\n\nconst decoratorAdd = defineBehavior({\n on: 'decorator.add',\n actions: [\n ({event}) => [\n {\n type: 'decorator.add',\n decorator: event.decorator,\n },\n {\n type: 'reselect',\n },\n ],\n ],\n})\n\nconst decoratorRemove = defineBehavior({\n on: 'decorator.remove',\n actions: [\n ({event}) => [\n {\n type: 'decorator.remove',\n decorator: event.decorator,\n },\n {\n type: 'reselect',\n },\n ],\n ],\n})\n\nconst decoratorToggle = defineBehavior({\n on: 'decorator.toggle',\n actions: [\n ({event}) => [\n {\n type: 'decorator.toggle',\n decorator: event.decorator,\n },\n {\n type: 'reselect',\n },\n ],\n ],\n})\n\nexport const coreDecoratorBehaviors = {\n decoratorAdd,\n decoratorRemove,\n decoratorToggle,\n}\n","import {defineBehavior} from './behavior.types'\nimport {\n getFocusSpan,\n getFocusTextBlock,\n selectionIsCollapsed,\n} from './behavior.utils'\n\nconst clearListOnBackspace = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const atTheBeginningOfBLock =\n focusTextBlock.node.children[0]._key === focusSpan.node._key &&\n context.selection.focus.offset === 0\n\n if (atTheBeginningOfBLock && focusTextBlock.node.level === 1) {\n return {focusTextBlock}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock}) => [\n {\n type: 'unset block',\n props: ['listItem', 'level'],\n paths: [focusTextBlock.path],\n },\n ],\n ],\n})\n\nconst unindentListOnBackspace = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const atTheBeginningOfBLock =\n focusTextBlock.node.children[0]._key === focusSpan.node._key &&\n context.selection.focus.offset === 0\n\n if (\n atTheBeginningOfBLock &&\n focusTextBlock.node.level !== undefined &&\n focusTextBlock.node.level > 1\n ) {\n return {focusTextBlock, level: focusTextBlock.node.level - 1}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock, level}) => [\n {\n type: 'set block',\n level,\n paths: [focusTextBlock.path],\n },\n ],\n ],\n})\n\nexport const coreListBehaviors = {clearListOnBackspace, unindentListOnBackspace}\n","import {coreBlockObjectBehaviors} from './behavior.core.block-objects'\nimport {coreDecoratorBehaviors} from './behavior.core.decorators'\nimport {coreListBehaviors} from './behavior.core.lists'\nimport {defineBehavior} from './behavior.types'\n\nconst softReturn = defineBehavior({\n on: 'insert soft break',\n actions: [() => [{type: 'insert text', text: '\\n'}]],\n})\n\n/**\n * @alpha\n */\nexport const coreBehaviors = [\n softReturn,\n coreDecoratorBehaviors.decoratorAdd,\n coreDecoratorBehaviors.decoratorRemove,\n coreDecoratorBehaviors.decoratorToggle,\n coreBlockObjectBehaviors.breakingBlockObject,\n coreBlockObjectBehaviors.deletingEmptyTextBlockAfterBlockObject,\n coreBlockObjectBehaviors.deletingEmptyTextBlockBeforeBlockObject,\n coreListBehaviors.clearListOnBackspace,\n coreListBehaviors.unindentListOnBackspace,\n]\n\n/**\n * @alpha\n */\nexport const coreBehavior = {\n softReturn,\n decorators: coreDecoratorBehaviors,\n blockObjects: coreBlockObjectBehaviors,\n lists: coreListBehaviors,\n}\n","import type {PortableTextMemberSchemaTypes} from '../../types/editor'\nimport {defineBehavior} from './behavior.types'\nimport {\n getFocusSpan,\n getFocusTextBlock,\n selectionIsCollapsed,\n} from './behavior.utils'\n\n/**\n * @alpha\n */\nexport type MarkdownBehaviorsConfig = {\n mapDefaultStyle: (schema: PortableTextMemberSchemaTypes) => string | undefined\n mapHeadingStyle: (\n schema: PortableTextMemberSchemaTypes,\n level: number,\n ) => string | undefined\n mapBlockquoteStyle: (\n schema: PortableTextMemberSchemaTypes,\n ) => string | undefined\n mapUnorderedListStyle: (\n schema: PortableTextMemberSchemaTypes,\n ) => string | undefined\n mapOrderedListStyle: (\n schema: PortableTextMemberSchemaTypes,\n ) => string | undefined\n}\n\n/**\n * @alpha\n */\nexport function createMarkdownBehaviors(config: MarkdownBehaviorsConfig) {\n const automaticBlockquoteOnSpace = defineBehavior({\n on: 'insert text',\n guard: ({context, event}) => {\n const isSpace = event.text === ' '\n\n if (!isSpace) {\n return false\n }\n\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const caretAtTheEndOfQuote = context.selection.focus.offset === 1\n const looksLikeMarkdownQuote = /^>/.test(focusSpan.node.text)\n const blockquoteStyle = config.mapBlockquoteStyle(context.schema)\n\n if (\n caretAtTheEndOfQuote &&\n looksLikeMarkdownQuote &&\n blockquoteStyle !== undefined\n ) {\n return {focusTextBlock, focusSpan, style: blockquoteStyle}\n }\n\n return false\n },\n actions: [\n () => [\n {\n type: 'insert text',\n text: ' ',\n },\n ],\n (_, {focusTextBlock, focusSpan, style}) => [\n {\n type: 'unset block',\n props: ['listItem', 'level'],\n paths: [focusTextBlock.path],\n },\n {\n type: 'set block',\n style,\n paths: [focusTextBlock.path],\n },\n {\n type: 'delete',\n selection: {\n anchor: {\n path: focusSpan.path,\n offset: 0,\n },\n focus: {\n path: focusSpan.path,\n offset: 2,\n },\n },\n },\n ],\n ],\n })\n const automaticHeadingOnSpace = defineBehavior({\n on: 'insert text',\n guard: ({context, event}) => {\n const isSpace = event.text === ' '\n\n if (!isSpace) {\n return false\n }\n\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const markdownHeadingSearch = /^#+/.exec(focusSpan.node.text)\n const headingLevel = markdownHeadingSearch\n ? markdownHeadingSearch[0].length\n : undefined\n const caretAtTheEndOfHeading =\n context.selection.focus.offset === headingLevel\n\n if (!caretAtTheEndOfHeading) {\n return false\n }\n\n const headingStyle =\n headingLevel !== undefined\n ? config.mapHeadingStyle(context.schema, headingLevel)\n : undefined\n\n if (headingLevel !== undefined && headingStyle !== undefined) {\n return {\n focusTextBlock,\n focusSpan,\n style: headingStyle,\n level: headingLevel,\n }\n }\n\n return false\n },\n actions: [\n () => [\n {\n type: 'insert text',\n text: ' ',\n },\n ],\n (_, {focusTextBlock, focusSpan, style, level}) => [\n {\n type: 'unset block',\n props: ['listItem', 'level'],\n paths: [focusTextBlock.path],\n },\n {\n type: 'set block',\n style,\n paths: [focusTextBlock.path],\n },\n {\n type: 'delete',\n selection: {\n anchor: {\n path: focusSpan.path,\n offset: 0,\n },\n focus: {\n path: focusSpan.path,\n offset: level + 1,\n },\n },\n },\n ],\n ],\n })\n const clearStyleOnBackspace = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const atTheBeginningOfBLock =\n focusTextBlock.node.children[0]._key === focusSpan.node._key &&\n context.selection.focus.offset === 0\n\n const defaultStyle = config.mapDefaultStyle(context.schema)\n\n if (\n atTheBeginningOfBLock &&\n defaultStyle &&\n focusTextBlock.node.style !== defaultStyle\n ) {\n return {defaultStyle, focusTextBlock}\n }\n\n return false\n },\n actions: [\n (_, {defaultStyle, focusTextBlock}) => [\n {\n type: 'set block',\n style: defaultStyle,\n paths: [focusTextBlock.path],\n },\n ],\n ],\n })\n const automaticListOnSpace = defineBehavior({\n on: 'insert text',\n guard: ({context, event}) => {\n const isSpace = event.text === ' '\n\n if (!isSpace) {\n return false\n }\n\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const defaultStyle = config.mapDefaultStyle(context.schema)\n const looksLikeUnorderedList = /^(-|\\*)/.test(focusSpan.node.text)\n const unorderedListStyle = config.mapUnorderedListStyle(context.schema)\n const caretAtTheEndOfUnorderedList = context.selection.focus.offset === 1\n\n if (\n defaultStyle &&\n caretAtTheEndOfUnorderedList &&\n looksLikeUnorderedList &&\n unorderedListStyle !== undefined\n ) {\n return {\n focusTextBlock,\n focusSpan,\n listItem: unorderedListStyle,\n listItemLength: 1,\n style: defaultStyle,\n }\n }\n\n const looksLikeOrderedList = /^1./.test(focusSpan.node.text)\n const orderedListStyle = config.mapOrderedListStyle(context.schema)\n const caretAtTheEndOfOrderedList = context.selection.focus.offset === 2\n\n if (\n defaultStyle &&\n caretAtTheEndOfOrderedList &&\n looksLikeOrderedList &&\n orderedListStyle !== undefined\n ) {\n return {\n focusTextBlock,\n focusSpan,\n listItem: orderedListStyle,\n listItemLength: 2,\n style: defaultStyle,\n }\n }\n\n return false\n },\n actions: [\n () => [\n {\n type: 'insert text',\n text: ' ',\n },\n ],\n (_, {focusTextBlock, focusSpan, style, listItem, listItemLength}) => [\n {\n type: 'set block',\n listItem,\n level: 1,\n style,\n paths: [focusTextBlock.path],\n },\n {\n type: 'delete',\n selection: {\n anchor: {\n path: focusSpan.path,\n offset: 0,\n },\n focus: {\n path: focusSpan.path,\n offset: listItemLength + 1,\n },\n },\n },\n ],\n ],\n })\n\n const markdownBehaviors = [\n automaticBlockquoteOnSpace,\n automaticHeadingOnSpace,\n clearStyleOnBackspace,\n automaticListOnSpace,\n ]\n\n return markdownBehaviors\n}\n","import type {\n ArraySchemaType,\n BlockSchemaType,\n ObjectSchemaType,\n PortableTextBlock,\n SchemaType,\n SpanSchemaType,\n} from '@sanity/types'\nimport type {PortableTextMemberSchemaTypes} from '../types/editor'\n\nexport function getPortableTextMemberSchemaTypes(\n portableTextType: ArraySchemaType<PortableTextBlock>,\n): PortableTextMemberSchemaTypes {\n if (!portableTextType) {\n throw new Error(\"Parameter 'portabletextType' missing (required)\")\n }\n const blockType = portableTextType.of?.find(findBlockType) as\n | BlockSchemaType\n | undefined\n if (!blockType) {\n throw new Error('Block type is not defined in this schema (required)')\n }\n const childrenField = blockType.fields?.find(\n (field) => field.name === 'children',\n ) as {type: ArraySchemaType} | undefined\n if (!childrenField) {\n throw new Error('Children field for block type found in schema (required)')\n }\n const ofType = childrenField.type.of\n if (!ofType) {\n throw new Error(\n 'Valid types for block children not found in schema (required)',\n )\n }\n const spanType = ofType.find((memberType) => memberType.name === 'span') as\n | ObjectSchemaType\n | undefined\n if (!spanType) {\n throw new Error('Span type not found in schema (required)')\n }\n const inlineObjectTypes = (ofType.filter(\n (memberType) => memberType.name !== 'span',\n ) || []) as ObjectSchemaType[]\n const blockObjectTypes = (portableTextType.of?.filter(\n (field) => field.name !== blockType.name,\n ) || []) as ObjectSchemaType[]\n return {\n styles: resolveEnabledStyles(blockType),\n decorators: resolveEnabledDecorators(spanType),\n lists: resolveEnabledListItems(blockType),\n block: blockType,\n span: spanType,\n portableText: portableTextType,\n inlineObjects: inlineObjectTypes,\n blockObjects: blockObjectTypes,\n annotations: (spanType as SpanSchemaType).annotations,\n }\n}\n\nfunction resolveEnabledStyles(blockType: ObjectSchemaType) {\n const styleField = blockType.fields?.find(\n (btField) => btField.name === 'style',\n )\n if (!styleField) {\n throw new Error(\n \"A field with name 'style' is not defined in the block type (required).\",\n )\n }\n const textStyles =\n styleField.type.options?.list &&\n styleField.type.options.list?.filter(\n (style: {value: string}) => style.value,\n )\n if (!textStyles || textStyles.length === 0) {\n throw new Error(\n 'The style fields need at least one style ' +\n \"defined. I.e: {title: 'Normal', value: 'normal'}.\",\n )\n }\n return textStyles\n}\n\nfunction resolveEnabledDecorators(spanType: ObjectSchemaType) {\n return (spanType as any).decorators\n}\n\nfunction resolveEnabledListItems(blockType: ObjectSchemaType) {\n const listField = blockType.fields?.find(\n (btField) => btField.name === 'listItem',\n )\n if (!listField) {\n throw new Error(\n \"A field with name 'listItem' is not defined in the block type (required).\",\n )\n }\n const listItems =\n listField.type.options?.list &&\n listField.type.options.list.filter((list: {value: string}) => list.value)\n if (!listItems) {\n throw new Error('The list field need at least to be an empty array')\n }\n return listItems\n}\n\nfunction findBlockType(type: SchemaType): BlockSchemaType | null {\n if (type.type) {\n return findBlockType(type.type)\n }\n\n if (type.name === 'block') {\n return type as BlockSchemaType\n }\n\n return null\n}\n","import {Schema as SanitySchema} from '@sanity/schema'\nimport {\n defineField,\n defineType,\n type BlockDecoratorDefinition,\n type ObjectSchemaType,\n} from '@sanity/types'\nimport startCase from 'lodash.startcase'\nimport type {PortableTextMemberSchemaTypes} from '../types/editor'\nimport {getPortableTextMemberSchemaTypes} from '../utils/getPortableTextMemberSchemaTypes'\n\n/**\n * @alpha\n */\nexport type BaseDefinition = {\n name: string\n title?: string\n icon?: BlockDecoratorDefinition['icon']\n}\n\n/**\n * @alpha\n */\nexport type SchemaDefinition<\n TBaseDefinition extends BaseDefinition = BaseDefinition,\n> = {\n decorators?: ReadonlyArray<TBaseDefinition>\n blockObjects?: ReadonlyArray<TBaseDefinition>\n inlineObjects?: ReadonlyArray<TBaseDefinition>\n annotations?: ReadonlyArray<TBaseDefinition>\n lists?: ReadonlyArray<TBaseDefinition>\n styles?: ReadonlyArray<TBaseDefinition>\n}\n\n/**\n * @alpha\n */\nexport function defineSchema<const TSchemaDefinition extends SchemaDefinition>(\n definition: TSchemaDefinition,\n): TSchemaDefinition {\n return definition\n}\n\nexport function compileSchemaDefinition<\n TSchemaDefinition extends SchemaDefinition,\n>(definition?: TSchemaDefinition) {\n const blockObjects =\n definition?.blockObjects?.map((blockObject) =>\n defineType({\n type: 'object',\n // Very naive way to work around `SanitySchema.compile` adding default\n // fields to objects with the name `image`\n name: blockObject.name === 'image' ? 'tmp-image' : blockObject.name,\n title: blockObject.title,\n icon: blockObject.icon,\n fields: [],\n }),\n ) ?? []\n const inlineObjects =\n definition?.inlineObjects?.map((inlineObject) =>\n defineType({\n type: 'object',\n name: inlineObject.name,\n title: inlineObject.title,\n icon: inlineObject.icon,\n fields: [],\n }),\n ) ?? []\n\n const portableTextSchema = defineField({\n type: 'array',\n name: 'portable-text',\n of: [\n ...blockObjects.map((blockObject) => ({type: blockObject.name})),\n {\n type: 'block',\n name: 'block',\n of: inlineObjects.map((inlineObject) => ({type: inlineObject.name})),\n marks: {\n decorators:\n definition?.decorators?.map((decorator) => ({\n title: decorator.title ?? startCase(decorator.name),\n value: decorator.name,\n icon: decorator.icon,\n })) ?? [],\n annotations:\n definition?.annotations?.map((annotation) => ({\n name: annotation.name,\n type: 'object',\n title: annotation.title,\n icon: annotation.icon,\n })) ?? [],\n },\n lists:\n definition?.lists?.map((list) => ({\n value: list.name,\n title: list.title ?? startCase(list.name),\n icon: list.icon,\n })) ?? [],\n styles:\n definition?.styles?.map((style) => ({\n value: style.name,\n title: style.title ?? startCase(style.name),\n icon: style.icon,\n })) ?? [],\n },\n ],\n })\n\n const schema = SanitySchema.compile({\n types: [portableTextSchema, ...blockObjects, ...inlineObjects],\n }).get('portable-text')\n\n const pteSchema = getPortableTextMemberSchemaTypes(schema)\n\n return {\n ...pteSchema,\n blockObjects: pteSchema.blockObjects.map((blockObject) =>\n blockObject.name === 'tmp-image'\n ? ({\n ...blockObject,\n name: 'image',\n type: {\n ...blockObject.type,\n name: 'image',\n },\n } as ObjectSchemaType)\n : blockObject,\n ),\n } satisfies PortableTextMemberSchemaTypes\n}\n","import debug from 'debug'\n\nconst rootName = 'sanity-pte:'\n\nexport default debug(rootName)\nexport function debugWithName(name: string): debug.Debugger {\n const namespace = `${rootName}${name}`\n if (debug && debug.enabled(namespace)) {\n return debug(namespace)\n }\n return debug(rootName)\n}\n","import {isKeySegment, type Path} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport {\n Editor,\n Element,\n type Descendant,\n type Point,\n type Path as SlatePath,\n} from 'slate'\nimport type {\n EditorSelectionPoint,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport type {ObjectWithKeyAndType} from './ranges'\n\nexport function createKeyedPath(\n point: Point,\n value: ObjectWithKeyAndType[] | undefined,\n types: PortableTextMemberSchemaTypes,\n): Path | null {\n const blockPath = [point.path[0]]\n if (!value) {\n return null\n }\n const block = value[blockPath[0]]\n if (!block) {\n return null\n }\n const keyedBlockPath = [{_key: block._key}]\n if (block._type !== types.block.name) {\n return keyedBlockPath as Path\n }\n let keyedChildPath: Path | undefined\n const childPath = point.path.slice(0, 2)\n const child = Array.isArray(block.children) && block.children[childPath[1]]\n if (child) {\n keyedChildPath = ['children', {_key: child._key}]\n }\n return (\n keyedChildPath ? [...keyedBlockPath, ...keyedChildPath] : keyedBlockPath\n ) as Path\n}\n\nexport function createArrayedPath(\n point: EditorSelectionPoint,\n editor: Editor,\n): SlatePath {\n if (!editor) {\n return []\n }\n const [block, blockPath] = Array.from(\n Editor.nodes(editor, {\n at: [],\n match: (n) =>\n isKeySegment(point.path[0]) &&\n (n as Descendant)._key === point.path[0]._key,\n }),\n )[0] || [undefined, undefined]\n if (!block || !Element.isElement(block)) {\n return []\n }\n if (editor.isVoid(block)) {\n return [blockPath[0], 0]\n }\n const childPath = [point.path[2]]\n const childIndex = block.children.findIndex((child) =>\n isEqual([{_key: child._key}], childPath),\n )\n if (childIndex >= 0 && block.children[childIndex]) {\n const child = block.children[childIndex]\n if (Element.isElement(child) && editor.isVoid(child)) {\n return blockPath.concat(childIndex).concat(0)\n }\n return blockPath.concat(childIndex)\n }\n return blockPath\n}\n","import {Point, Range, type BaseRange, type Editor, type Operation} from 'slate'\nimport type {\n EditorSelection,\n EditorSelectionPoint,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport {createArrayedPath, createKeyedPath} from './paths'\n\nexport interface ObjectWithKeyAndType {\n _key: string\n _type: string\n children?: ObjectWithKeyAndType[]\n}\n\nexport function toPortableTextRange(\n value: ObjectWithKeyAndType[] | undefined,\n range: BaseRange | Partial<BaseRange> | null,\n types: PortableTextMemberSchemaTypes,\n): EditorSelection {\n if (!range) {\n return null\n }\n let anchor: EditorSelectionPoint | null = null\n let focus: EditorSelectionPoint | null = null\n const anchorPath = range.anchor && createKeyedPath(range.anchor, value, types)\n if (anchorPath && range.anchor) {\n anchor = {\n path: anchorPath,\n offset: range.anchor.offset,\n }\n }\n const focusPath = range.focus && createKeyedPath(range.focus, value, types)\n if (focusPath && range.focus) {\n focus = {\n path: focusPath,\n offset: range.focus.offset,\n }\n }\n const backward = Boolean(\n Range.isRange(range) ? Range.isBackward(range) : undefined,\n )\n return anchor && focus ? {anchor, focus, backward} : null\n}\n\nexport function toSlateRange(\n selection: EditorSelection,\n editor: Editor,\n): Range | null {\n if (!selection || !editor) {\n return null\n }\n const anchor = {\n path: createArrayedPath(selection.anchor, editor),\n offset: selection.anchor.offset,\n }\n const focus = {\n path: createArrayedPath(selection.focus, editor),\n offset: selection.focus.offset,\n }\n if (focus.path.length === 0 || anchor.path.length === 0) {\n return null\n }\n const range = anchor && focus ? {anchor, focus} : null\n return range\n}\n\nexport function moveRangeByOperation(\n range: Range,\n operation: Operation,\n): Range | null {\n const anchor = Point.transform(range.anchor, operation)\n const focus = Point.transform(range.focus, operation)\n\n if (anchor === null || focus === null) {\n return null\n }\n\n if (Point.equals(anchor, range.anchor) && Point.equals(focus, range.focus)) {\n return range\n }\n\n return {anchor, focus}\n}\n","import type {Path, PortableTextBlock} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport type {EditorSelection, EditorSelectionPoint} from '../types/editor'\n\nexport function normalizePoint(\n point: EditorSelectionPoint,\n value: PortableTextBlock[],\n): EditorSelectionPoint | null {\n if (!point || !value) {\n return null\n }\n const newPath: Path = []\n let newOffset: number = point.offset || 0\n const blockKey =\n typeof point.path[0] === 'object' &&\n '_key' in point.path[0] &&\n point.path[0]._key\n const childKey =\n typeof point.path[2] === 'object' &&\n '_key' in point.path[2] &&\n point.path[2]._key\n const block: PortableTextBlock | undefined = value.find(\n (blk) => blk._key === blockKey,\n )\n if (block) {\n newPath.push({_key: block._key})\n } else {\n return null\n }\n if (block && point.path[1] === 'children') {\n if (\n !block.children ||\n (Array.isArray(block.children) && block.children.length === 0)\n ) {\n return null\n }\n const child =\n Array.isArray(block.children) &&\n block.children.find((cld) => cld._key === childKey)\n if (child) {\n newPath.push('children')\n newPath.push({_key: child._key})\n newOffset =\n child.text && child.text.length >= point.offset\n ? point.offset\n : (child.text && child.text.length) || 0\n } else {\n return null\n }\n }\n return {path: newPath, offset: newOffset}\n}\n\nexport function normalizeSelection(\n selection: EditorSelection,\n value: PortableTextBlock[] | undefined,\n): EditorSelection | null {\n if (!selection || !value || value.length === 0) {\n return null\n }\n let newAnchor: EditorSelectionPoint | null = null\n let newFocus: EditorSelectionPoint | null = null\n const {anchor, focus} = selection\n if (\n anchor &&\n value.find((blk) => isEqual({_key: blk._key}, anchor.path[0]))\n ) {\n newAnchor = normalizePoint(anchor, value)\n }\n if (focus && value.find((blk) => isEqual({_key: blk._key}, focus.path[0]))) {\n newFocus = normalizePoint(focus, value)\n }\n if (newAnchor && newFocus) {\n return {anchor: newAnchor, focus: newFocus, backward: selection.backward}\n }\n return null\n}\n","import type {\n PathSegment,\n PortableTextBlock,\n PortableTextChild,\n PortableTextObject,\n PortableTextTextBlock,\n} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport {Element, Text, type Descendant, type Node} from 'slate'\nimport type {PortableTextMemberSchemaTypes} from '../types/editor'\n\nexport const EMPTY_MARKDEFS: PortableTextObject[] = []\n\nexport const VOID_CHILD_KEY = 'void-child'\n\ntype Partial<T> = {\n [P in keyof T]?: T[P]\n}\n\nfunction keepObjectEquality(\n object: PortableTextBlock | PortableTextChild,\n keyMap: Record<string, PortableTextBlock | PortableTextChild>,\n) {\n const value = keyMap[object._key]\n if (value && isEqual(object, value)) {\n return value\n }\n keyMap[object._key] = object\n return object\n}\n\nexport function toSlateValue(\n value: PortableTextBlock[] | undefined,\n {schemaTypes}: {schemaTypes: PortableTextMemberSchemaTypes},\n keyMap: Record<string, any> = {},\n): Descendant[] {\n if (value && Array.isArray(value)) {\n return value.map((block) => {\n const {_type, _key, ...rest} = block\n const voidChildren = [\n {_key: VOID_CHILD_KEY, _type: 'span', text: '', marks: []},\n ]\n const isPortableText = block && block._type === schemaTypes.block.name\n if (isPortableText) {\n const textBlock = block as PortableTextTextBlock\n let hasInlines = false\n const hasMissingStyle = typeof textBlock.style === 'undefined'\n const hasMissingMarkDefs = typeof textBlock.markDefs === 'undefined'\n const hasMissingChildren = typeof textBlock.children === 'undefined'\n\n const children = (textBlock.children || []).map((child) => {\n const {_type: cType, _key: cKey, ...cRest} = child\n // Return 'slate' version of inline object where the actual\n // value is stored in the `value` property.\n // In slate, inline objects are represented as regular\n // children with actual text node in order to be able to\n // be selected the same way as the rest of the (text) content.\n if (cType !== 'span') {\n hasInlines = true\n return keepObjectEquality(\n {\n _type: cType,\n _key: cKey,\n children: voidChildren,\n value: cRest,\n __inline: true,\n },\n keyMap,\n )\n }\n // Original child object (span)\n return child\n })\n // Return original block\n if (\n !hasMissingStyle &&\n !hasMissingMarkDefs &&\n !hasMissingChildren &&\n !hasInlines &&\n Element.isElement(block)\n ) {\n // Original object\n return block\n }\n // TODO: remove this when we have a better way to handle missing style\n if (hasMissingStyle) {\n rest.style = schemaTypes.styles[0].value\n }\n return keepObjectEquality({_type, _key, ...rest, children}, keyMap)\n }\n return keepObjectEquality(\n {\n _type,\n _key,\n children: voidChildren,\n value: rest,\n },\n keyMap,\n )\n }) as Descendant[]\n }\n return []\n}\n\nexport function fromSlateValue(\n value: Descendant[],\n textBlockType: string,\n keyMap: Record<string, PortableTextBlock | PortableTextChild> = {},\n): PortableTextBlock[] {\n return value.map((block) => {\n const {_key, _type} = block\n if (!_key || !_type) {\n throw new Error('Not a valid block')\n }\n if (\n _type === textBlockType &&\n 'children' in block &&\n Array.isArray(block.children) &&\n _key\n ) {\n let hasInlines = false\n const children = block.children.map((child) => {\n const {_type: _cType} = child\n if ('value' in child && _cType !== 'span') {\n hasInlines = true\n const {\n value: v,\n _key: k,\n _type: t,\n __inline: _i,\n children: _c,\n ...rest\n } = child\n return keepObjectEquality(\n {...rest, ...v, _key: k as string, _type: t as string},\n keyMap,\n )\n }\n return child\n })\n if (!hasInlines) {\n return block as PortableTextBlock // Original object\n }\n return keepObjectEquality(\n {...block, children, _key, _type},\n keyMap,\n ) as PortableTextBlock\n }\n const blockValue = 'value' in block && block.value\n return keepObjectEquality(\n {_key, _type, ...(typeof blockValue === 'object' ? blockValue : {})},\n keyMap,\n ) as PortableTextBlock\n })\n}\n\nexport function isEqualToEmptyEditor(\n children: Descendant[] | PortableTextBlock[],\n schemaTypes: PortableTextMemberSchemaTypes,\n): boolean {\n return (\n children === undefined ||\n (children && Array.isArray(children) && children.length === 0) ||\n (children &&\n Array.isArray(children) &&\n children.length === 1 &&\n Element.isElement(children[0]) &&\n children[0]._type === schemaTypes.block.name &&\n 'style' in children[0] &&\n children[0].style === schemaTypes.styles[0].value &&\n !('listItem' in children[0]) &&\n Array.isArray(children[0].children) &&\n children[0].children.length === 1 &&\n Text.isText(children[0].children[0]) &&\n children[0].children[0]._type === 'span' &&\n !children[0].children[0].marks?.join('') &&\n children[0].children[0].text === '')\n )\n}\n\nexport function findBlockAndIndexFromPath(\n firstPathSegment: PathSegment,\n children: (Node | Partial<Node>)[],\n): [Element | undefined, number | undefined] {\n let blockIndex = -1\n const isNumber = Number.isInteger(Number(firstPathSegment))\n if (isNumber) {\n blockIndex = Number(firstPathSegment)\n } else if (children) {\n blockIndex = children.findIndex(\n (blk) =>\n Element.isElement(blk) && isEqual({_key: blk._key}, firstPathSegment),\n )\n }\n if (blockIndex > -1) {\n return [children[blockIndex] as Element, blockIndex]\n }\n return [undefined, -1]\n}\n\nexport function findChildAndIndexFromPath(\n secondPathSegment: PathSegment,\n block: Element,\n): [Element | Text | undefined, number] {\n let childIndex = -1\n const isNumber = Number.isInteger(Number(secondPathSegment))\n if (isNumber) {\n childIndex = Number(secondPathSegment)\n } else {\n childIndex = block.children.findIndex((child) =>\n isEqual({_key: child._key}, secondPathSegment),\n )\n }\n if (childIndex > -1) {\n return [block.children[childIndex] as Element | Text, childIndex]\n }\n return [undefined, -1]\n}\n\nexport function getValueOrInitialValue(\n value: unknown,\n initialValue: PortableTextBlock[],\n): PortableTextBlock[] | undefined {\n if (value && Array.isArray(value) && value.length > 0) {\n return value\n }\n return initialValue\n}\n","import type {Editor, Element, Range} from 'slate'\nimport type {EditorSelection} from '..'\n\n// Is the editor currently receiving remote changes that are being applied to the content?\nexport const IS_PROCESSING_REMOTE_CHANGES: WeakMap<Editor, boolean> =\n new WeakMap()\n// Is the editor currently producing local changes that are not yet submitted?\nexport const IS_PROCESSING_LOCAL_CHANGES: WeakMap<Editor, boolean> =\n new WeakMap()\n\n// Is the editor dragging something?\nexport const IS_DRAGGING: WeakMap<Editor, boolean> = new WeakMap()\n// Is the editor dragging a element?\nexport const IS_DRAGGING_BLOCK_ELEMENT: WeakMap<Editor, Element> = new WeakMap()\n\n// When dragging elements, this will be the target element\nexport const IS_DRAGGING_ELEMENT_TARGET: WeakMap<Editor, Element> =\n new WeakMap()\n// Target position for dragging over a block\nexport const IS_DRAGGING_BLOCK_TARGET_POSITION: WeakMap<\n Editor,\n 'top' | 'bottom'\n> = new WeakMap()\n\nexport const KEY_TO_SLATE_ELEMENT: WeakMap<Editor, any | undefined> =\n new WeakMap()\nexport const KEY_TO_VALUE_ELEMENT: WeakMap<Editor, any | undefined> =\n new WeakMap()\n\n// Keep object relation to slate range in the portable-text-range\nexport const SLATE_TO_PORTABLE_TEXT_RANGE = new WeakMap<\n Range,\n EditorSelection\n>()\n","import type {PortableTextBlock, PortableTextChild} from '@sanity/types'\n\ntype Props = {\n value: PortableTextBlock | PortableTextChild\n}\n\nconst DefaultObject = (props: Props): JSX.Element => {\n return (\n <div>\n <pre>{JSON.stringify(props.value, null, 2)}</pre>\n </div>\n )\n}\n\nDefaultObject.displayName = 'DefaultObject'\n\nexport default DefaultObject\n","import {styled} from 'styled-components'\n\nexport const DefaultBlockObject = styled.div<{selected: boolean}>`\n user-select: none;\n border: ${(props) => {\n if (props.selected) {\n return '1px solid blue'\n }\n return '1px solid transparent'\n }};\n`\n\nexport const DefaultInlineObject = styled.span<{selected: boolean}>`\n background: #999;\n border: ${(props) => {\n if (props.selected) {\n return '1px solid blue'\n }\n return '1px solid transparent'\n }};\n`\n\ntype ListItemProps = {listLevel: number; listStyle: string}\n\nexport const DefaultListItem = styled.div<ListItemProps>`\n &.pt-list-item {\n width: fit-content;\n position: relative;\n display: block;\n\n /* Important 'transform' in order to force refresh the ::before and ::after rules\n in Webkit: https://stackoverflow.com/a/21947628/831480\n */\n transform: translateZ(0);\n margin-left: ${(props: ListItemProps) => getLeftPositionForListLevel(props.listLevel)};\n }\n &.pt-list-item > .pt-list-item-inner {\n display: flex;\n margin: 0;\n padding: 0;\n &:before {\n justify-content: flex-start;\n vertical-align: top;\n }\n }\n &.pt-list-item-bullet > .pt-list-item-inner:before {\n content: '${(props: ListItemProps) =>\n getContentForListLevelAndStyle(props.listLevel, props.listStyle)}';\n font-size: 0.4375rem; /* 7px */\n line-height: 1.5rem; /* Same as body text */\n /* Optical alignment */\n position: relative;\n }\n }\n &.pt-list-item-bullet > .pt-list-item-inner {\n &:before {\n min-width: 1.5rem; /* Make sure space between bullet and text never shrinks */\n }\n }\n &.pt-list-item-number {\n counter-increment: ${(props: {listLevel: number}) =>\n getCounterIncrementForListLevel(props.listLevel)};\n counter-reset: ${(props: {listLevel: number}) => getCounterResetForListLevel(props.listLevel)};\n }\n & + :not(.pt-list-item-number) {\n counter-reset: listItemNumber;\n }\n &.pt-list-item-number > .pt-list-item-inner:before {\n content: ${(props) => getCounterContentForListLevel(props.listLevel)};\n min-width: 1.5rem; /* Make sure space between number and text never shrinks */\n /* Optical alignment */\n position: relative;\n top: 1px;\n }\n`\n\nexport const DefaultListItemInner = styled.div``\n\nfunction getLeftPositionForListLevel(level: number) {\n switch (Number(level)) {\n case 1:\n return '1.5em'\n case 2:\n return '3em'\n case 3:\n return '4.5em'\n case 4:\n return '6em'\n case 5:\n return '7.5em'\n case 6:\n return '9em'\n case 7:\n return '10.5em'\n case 8:\n return '12em'\n case 9:\n return '13.5em'\n case 10:\n return '15em'\n default:\n return '0em'\n }\n}\n\nconst bullets = ['●', '○', '■']\n\nfunction getContentForListLevelAndStyle(level: number, style: string) {\n const normalizedLevel = (level - 1) % 3\n if (style === 'bullet') {\n return bullets[normalizedLevel]\n }\n return '*'\n}\n\nfunction getCounterIncrementForListLevel(level: number) {\n switch (level) {\n case 1:\n return 'listItemNumber'\n case 2:\n return 'listItemAlpha'\n case 3:\n return 'listItemRoman'\n case 4:\n return 'listItemNumberNext'\n case 5:\n return 'listItemLetterNext'\n case 6:\n return 'listItemRomanNext'\n case 7:\n return 'listItemNumberNextNext'\n case 8:\n return 'listItemAlphaNextNext'\n case 9:\n return 'listItemRomanNextNext'\n default:\n return 'listItemNumberNextNextNext'\n }\n}\n\nfunction getCounterResetForListLevel(level: number) {\n switch (level) {\n case 1:\n return 'listItemAlpha'\n case 2:\n return 'listItemRoman'\n case 3:\n return 'listItemNumberNext'\n case 4:\n return 'listItemLetterNext'\n case 5:\n return 'listItemRomanNext'\n case 6:\n return 'listItemNumberNextNext'\n case 7:\n return 'listItemAlphaNextNext'\n case 8:\n return 'listItemRomanNextNext'\n case 9:\n return 'listItemNumberNextNextNext'\n default:\n return 'listItemNumberNextNextNext'\n }\n}\n\nfunction getCounterContentForListLevel(level: number) {\n switch (level) {\n case 1:\n return `counter(listItemNumber) '. '`\n case 2:\n return `counter(listItemAlpha, lower-alpha) '. '`\n case 3:\n return `counter(listItemRoman, lower-roman) '. '`\n case 4:\n return `counter(listItemNumberNext) '. '`\n case 5:\n return `counter(listItemLetterNext, lower-alpha) '. '`\n case 6:\n return `counter(listItemRomanNext, lower-roman) '. '`\n case 7:\n return `counter(listItemNumberNextNext) '. '`\n case 8:\n return `counter(listItemAlphaNextNext, lower-alpha) '. '`\n case 9:\n return `counter(listItemRomanNextNext, lower-roman) '. '`\n default:\n return `counter(listItemNumberNextNextNext) '. '`\n }\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type DragEvent,\n type MutableRefObject,\n type ReactNode,\n} from 'react'\nimport {Editor, Path, Transforms, type Element as SlateElement} from 'slate'\nimport {ReactEditor, useSlateStatic} from 'slate-react'\nimport {debugWithName} from '../../utils/debug'\nimport {\n IS_DRAGGING,\n IS_DRAGGING_BLOCK_ELEMENT,\n IS_DRAGGING_BLOCK_TARGET_POSITION,\n IS_DRAGGING_ELEMENT_TARGET,\n} from '../../utils/weakMaps'\n\nconst debug = debugWithName('components:DraggableBlock')\nconst debugRenders = false\n\n/**\n * @internal\n */\nexport interface DraggableBlockProps {\n children: ReactNode\n element: SlateElement\n readOnly: boolean\n blockRef: MutableRefObject<HTMLDivElement | null>\n}\n\n/**\n * Implements drag and drop functionality on editor block nodes\n * @internal\n */\nexport const DraggableBlock = ({\n children,\n element,\n readOnly,\n blockRef,\n}: DraggableBlockProps) => {\n const editor = useSlateStatic()\n const dragGhostRef: MutableRefObject<undefined | HTMLElement> = useRef()\n const [isDragOver, setIsDragOver] = useState(false)\n const isVoid = useMemo(\n () => Editor.isVoid(editor, element),\n [editor, element],\n )\n const isInline = useMemo(\n () => Editor.isInline(editor, element),\n [editor, element],\n )\n\n const [blockElement, setBlockElement] = useState<HTMLElement | null>(null)\n\n useEffect(\n () =>\n setBlockElement(\n blockRef ? blockRef.current : ReactEditor.toDOMNode(editor, element),\n ),\n [editor, element, blockRef],\n )\n\n // Note: this is called not for the dragging block, but for the targets when the block is dragged over them\n const handleDragOver = useCallback(\n (event: DragEvent) => {\n const isMyDragOver = IS_DRAGGING_BLOCK_ELEMENT.get(editor)\n // debug('Drag over', blockElement)\n if (!isMyDragOver || !blockElement) {\n return\n }\n event.preventDefault()\n event.dataTransfer.dropEffect = 'move'\n IS_DRAGGING_ELEMENT_TARGET.set(editor, element)\n const elementRect = blockElement.getBoundingClientRect()\n const offset = elementRect.top\n const height = elementRect.height\n const Y = event.pageY\n const loc = Math.abs(offset - Y)\n let position: 'top' | 'bottom' = 'bottom'\n if (element === editor.children[0]) {\n position = 'top'\n } else if (loc < height / 2) {\n position = 'top'\n IS_DRAGGING_BLOCK_TARGET_POSITION.set(editor, position)\n } else {\n position = 'bottom'\n IS_DRAGGING_BLOCK_TARGET_POSITION.set(editor, position)\n }\n if (isMyDragOver === element) {\n event.dataTransfer.dropEffect = 'none'\n return\n }\n setIsDragOver(true)\n },\n [blockElement, editor, element],\n )\n\n // Note: this is called not for the dragging block, but for the targets when the block is dragged over them\n const handleDragLeave = useCallback(() => {\n setIsDragOver(false)\n }, [])\n\n // Note: this is called for the dragging block\n const handleDragEnd = useCallback(\n (event: DragEvent) => {\n const targetBlock = IS_DRAGGING_ELEMENT_TARGET.get(editor)\n if (targetBlock) {\n IS_DRAGGING.set(editor, false)\n event.preventDefault()\n event.stopPropagation()\n IS_DRAGGING_ELEMENT_TARGET.delete(editor)\n if (dragGhostRef.current) {\n debug('Removing drag ghost')\n document.body.removeChild(dragGhostRef.current)\n }\n const dragPosition = IS_DRAGGING_BLOCK_TARGET_POSITION.get(editor)\n IS_DRAGGING_BLOCK_TARGET_POSITION.delete(editor)\n let targetPath = ReactEditor.findPath(editor, targetBlock)\n const myPath = ReactEditor.findPath(editor, element)\n const isBefore = Path.isBefore(myPath, targetPath)\n if (dragPosition === 'bottom' && !isBefore) {\n // If it is already at the bottom, don't do anything.\n if (targetPath[0] >= editor.children.length - 1) {\n debug('target is already at the bottom, not moving')\n return\n }\n const originalPath = targetPath\n targetPath = Path.next(targetPath)\n debug(\n `Adjusting targetPath from ${JSON.stringify(originalPath)} to ${JSON.stringify(\n targetPath,\n )}`,\n )\n }\n if (\n dragPosition === 'top' &&\n isBefore &&\n targetPath[0] !== editor.children.length - 1\n ) {\n const originalPath = targetPath\n targetPath = Path.previous(targetPath)\n debug(\n `Adjusting targetPath from ${JSON.stringify(originalPath)} to ${JSON.stringify(\n targetPath,\n )}`,\n )\n }\n if (Path.equals(targetPath, myPath)) {\n event.preventDefault()\n debug('targetPath and myPath is the same, not moving')\n return\n }\n debug(\n `Moving element ${element._key} from path ${JSON.stringify(myPath)} to ${JSON.stringify(\n targetPath,\n )} (${dragPosition})`,\n )\n Transforms.moveNodes(editor, {at: myPath, to: targetPath})\n editor.onChange()\n return\n }\n debug('No target element, not doing anything')\n },\n [editor, element],\n )\n // Note: this is called not for the dragging block, but for the drop target\n const handleDrop = useCallback(\n (event: DragEvent) => {\n if (IS_DRAGGING_BLOCK_ELEMENT.get(editor)) {\n debug('On drop (prevented)', element)\n event.preventDefault()\n event.stopPropagation()\n setIsDragOver(false)\n }\n },\n [editor, element],\n )\n // Note: this is called for the dragging block\n const handleDrag = useCallback(\n (event: DragEvent) => {\n if (!isVoid) {\n IS_DRAGGING_BLOCK_ELEMENT.delete(editor)\n return\n }\n IS_DRAGGING.set(editor, true)\n IS_DRAGGING_BLOCK_ELEMENT.set(editor, element)\n event.stopPropagation() // Stop propagation so that leafs don't get this and take focus/selection!\n\n const target = event.target\n\n if (target instanceof HTMLElement) {\n target.style.opacity = '1'\n }\n },\n [editor, element, isVoid],\n )\n\n // Note: this is called for the dragging block\n const handleDragStart = useCallback(\n (event: DragEvent) => {\n if (!isVoid || isInline) {\n debug('Not dragging block')\n IS_DRAGGING_BLOCK_ELEMENT.delete(editor)\n IS_DRAGGING.set(editor, false)\n return\n }\n debug('Drag start')\n IS_DRAGGING.set(editor, true)\n if (event.dataTransfer) {\n event.dataTransfer.setData('application/portable-text', 'something')\n event.dataTransfer.effectAllowed = 'move'\n }\n // Clone blockElement so that it will not be visually clipped by scroll-containers etc.\n // The application that uses the portable-text-editor may indicate the element used as\n // drag ghost by adding a truthy data attribute 'data-pt-drag-ghost-element' to a HTML element.\n if (blockElement && blockElement instanceof HTMLElement) {\n let dragGhost = blockElement.cloneNode(true) as HTMLElement\n const customGhost = dragGhost.querySelector(\n '[data-pt-drag-ghost-element]',\n )\n if (customGhost) {\n dragGhost = customGhost as HTMLElement\n }\n\n // Set the `data-dragged` attribute so the consumer can style the element while it’s dragged\n dragGhost.setAttribute('data-dragged', '')\n\n if (document.body) {\n dragGhostRef.current = dragGhost\n dragGhost.style.position = 'absolute'\n dragGhost.style.left = '-99999px'\n dragGhost.style.boxSizing = 'border-box'\n document.body.appendChild(dragGhost)\n const rect = blockElement.getBoundingClientRect()\n const x = event.clientX - rect.left\n const y = event.clientY - rect.top\n dragGhost.style.width = `${rect.width}px`\n dragGhost.style.height = `${rect.height}px`\n event.dataTransfer.setDragImage(dragGhost, x, y)\n }\n }\n handleDrag(event)\n },\n [blockElement, editor, handleDrag, isInline, isVoid],\n )\n\n const isDraggingOverFirstBlock =\n isDragOver && editor.children[0] === IS_DRAGGING_ELEMENT_TARGET.get(editor)\n const isDraggingOverLastBlock =\n isDragOver &&\n editor.children[editor.children.length - 1] ===\n IS_DRAGGING_ELEMENT_TARGET.get(editor)\n const dragPosition = IS_DRAGGING_BLOCK_TARGET_POSITION.get(editor)\n\n const isDraggingOverTop =\n isDraggingOverFirstBlock ||\n (isDragOver &&\n !isDraggingOverFirstBlock &&\n !isDraggingOverLastBlock &&\n dragPosition === 'top')\n const isDraggingOverBottom =\n isDraggingOverLastBlock ||\n (isDragOver &&\n !isDraggingOverFirstBlock &&\n !isDraggingOverLastBlock &&\n dragPosition === 'bottom')\n\n const dropIndicator = useMemo(\n () => (\n <div\n className=\"pt-drop-indicator\"\n style={{\n position: 'absolute',\n width: '100%',\n height: 1,\n borderBottom: '1px solid currentColor',\n zIndex: 5,\n }}\n />\n ),\n [],\n )\n\n if (readOnly) {\n return <>{children}</>\n }\n\n if (debugRenders) {\n debug('render')\n }\n\n return (\n <div\n draggable={isVoid}\n onDragStart={handleDragStart}\n onDrag={handleDrag}\n onDragOver={handleDragOver}\n onDragLeave={handleDragLeave}\n onDragEnd={handleDragEnd}\n onDrop={handleDrop}\n >\n {isDraggingOverTop && dropIndicator}\n {children}\n {isDraggingOverBottom && dropIndicator}\n </div>\n )\n}\n\nDraggableBlock.displayName = 'DraggableBlock'\n","import type {\n Path,\n PortableTextChild,\n PortableTextObject,\n PortableTextTextBlock,\n} from '@sanity/types'\nimport {useMemo, useRef, type FunctionComponent, type ReactElement} from 'react'\nimport {Editor, Range, Element as SlateElement} from 'slate'\nimport {\n ReactEditor,\n useSelected,\n useSlateStatic,\n type RenderElementProps,\n} from 'slate-react'\nimport type {\n BlockRenderProps,\n PortableTextMemberSchemaTypes,\n RenderBlockFunction,\n RenderChildFunction,\n RenderListItemFunction,\n RenderStyleFunction,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue} from '../../utils/values'\nimport {KEY_TO_VALUE_ELEMENT} from '../../utils/weakMaps'\nimport ObjectNode from '../nodes/DefaultObject'\nimport {\n DefaultBlockObject,\n DefaultListItem,\n DefaultListItemInner,\n} from '../nodes/index'\nimport {DraggableBlock} from './DraggableBlock'\n\nconst debug = debugWithName('components:Element')\nconst debugRenders = false\nconst EMPTY_ANNOTATIONS: PortableTextObject[] = []\n\n/**\n * @internal\n */\nexport interface ElementProps {\n attributes: RenderElementProps['attributes']\n children: ReactElement\n element: SlateElement\n schemaTypes: PortableTextMemberSchemaTypes\n readOnly: boolean\n renderBlock?: RenderBlockFunction\n renderChild?: RenderChildFunction\n renderListItem?: RenderListItemFunction\n renderStyle?: RenderStyleFunction\n spellCheck?: boolean\n}\n\nconst inlineBlockStyle = {display: 'inline-block'}\n\n/**\n * Renders Portable Text block and inline object nodes in Slate\n * @internal\n */\nexport const Element: FunctionComponent<ElementProps> = ({\n attributes,\n children,\n element,\n schemaTypes,\n readOnly,\n renderBlock,\n renderChild,\n renderListItem,\n renderStyle,\n spellCheck,\n}) => {\n const editor = useSlateStatic()\n const selected = useSelected()\n const blockRef = useRef<HTMLDivElement | null>(null)\n const inlineBlockObjectRef = useRef(null)\n const focused =\n (selected && editor.selection && Range.isCollapsed(editor.selection)) ||\n false\n\n const value = useMemo(\n () =>\n fromSlateValue(\n [element],\n schemaTypes.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0],\n [editor, element, schemaTypes.block.name],\n )\n\n let renderedBlock = children\n\n let className: string | undefined\n\n const blockPath: Path = useMemo(() => [{_key: element._key}], [element])\n\n if (typeof element._type !== 'string') {\n throw new Error(`Expected element to have a _type property`)\n }\n\n if (typeof element._key !== 'string') {\n throw new Error(`Expected element to have a _key property`)\n }\n\n // Test for inline objects first\n if (editor.isInline(element)) {\n const path = ReactEditor.findPath(editor, element)\n const [block] = Editor.node(editor, path, {depth: 1})\n const schemaType = schemaTypes.inlineObjects.find(\n (_type) => _type.name === element._type,\n )\n if (!schemaType) {\n throw new Error('Could not find type for inline block element')\n }\n if (SlateElement.isElement(block)) {\n const elmPath: Path = [\n {_key: block._key},\n 'children',\n {_key: element._key},\n ]\n if (debugRenders) {\n debug(`Render ${element._key} (inline object)`)\n }\n return (\n <span {...attributes}>\n {/* Note that children must follow immediately or cut and selections will not work properly in Chrome. */}\n {children}\n <span\n draggable={!readOnly}\n className=\"pt-inline-object\"\n data-testid=\"pt-inline-object\"\n ref={inlineBlockObjectRef}\n key={element._key}\n style={inlineBlockStyle}\n contentEditable={false}\n >\n {renderChild &&\n renderChild({\n annotations: EMPTY_ANNOTATIONS, // These inline objects currently doesn't support annotations. This is a limitation of the current PT spec/model.\n children: <ObjectNode value={value} />,\n editorElementRef: inlineBlockObjectRef,\n focused,\n path: elmPath,\n schemaType,\n selected,\n type: schemaType,\n value: value as PortableTextChild,\n })}\n {!renderChild && <ObjectNode value={value} />}\n </span>\n </span>\n )\n }\n throw new Error('Block not found!')\n }\n\n // If not inline, it's either a block (text) or a block object (non-text)\n // NOTE: text blocks aren't draggable with DraggableBlock (yet?)\n if (element._type === schemaTypes.block.name) {\n className = `pt-block pt-text-block`\n const isListItem = 'listItem' in element\n if (debugRenders) {\n debug(`Render ${element._key} (text block)`)\n }\n const style = ('style' in element && element.style) || 'normal'\n className = `pt-block pt-text-block pt-text-block-style-${style}`\n const blockStyleType = schemaTypes.styles.find(\n (item) => item.value === style,\n )\n if (renderStyle && blockStyleType) {\n renderedBlock = renderStyle({\n block: element as PortableTextTextBlock,\n children,\n focused,\n selected,\n value: style,\n path: blockPath,\n schemaType: blockStyleType,\n editorElementRef: blockRef,\n })\n }\n let level: number | undefined\n if (isListItem) {\n if (typeof element.level === 'number') {\n level = element.level\n }\n className += ` pt-list-item pt-list-item-${element.listItem} pt-list-item-level-${level || 1}`\n }\n if (editor.isListBlock(value) && isListItem && element.listItem) {\n const listType = schemaTypes.lists.find(\n (item) => item.value === element.listItem,\n )\n if (renderListItem && listType) {\n renderedBlock = renderListItem({\n block: value,\n children: renderedBlock,\n focused,\n selected,\n value: element.listItem,\n path: blockPath,\n schemaType: listType,\n level: value.level || 1,\n editorElementRef: blockRef,\n })\n } else {\n renderedBlock = (\n <DefaultListItem\n listStyle={value.listItem || schemaTypes.lists[0].value}\n listLevel={value.level || 1}\n >\n <DefaultListItemInner>{renderedBlock}</DefaultListItemInner>\n </DefaultListItem>\n )\n }\n }\n const renderProps: Omit<BlockRenderProps, 'type'> = Object.defineProperty(\n {\n children: renderedBlock,\n editorElementRef: blockRef,\n focused,\n level,\n listItem: isListItem ? element.listItem : undefined,\n path: blockPath,\n selected,\n style,\n schemaType: schemaTypes.block,\n value,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaTypes.block\n },\n },\n )\n\n const propsOrDefaultRendered = renderBlock\n ? renderBlock(renderProps as BlockRenderProps)\n : children\n return (\n <div\n key={element._key}\n {...attributes}\n className={className}\n spellCheck={spellCheck}\n >\n <DraggableBlock\n element={element}\n readOnly={readOnly}\n blockRef={blockRef}\n >\n <div ref={blockRef}>{propsOrDefaultRendered}</div>\n </DraggableBlock>\n </div>\n )\n }\n const schemaType = schemaTypes.blockObjects.find(\n (_type) => _type.name === element._type,\n )\n if (!schemaType) {\n throw new Error(\n `Could not find schema type for block element of _type ${element._type}`,\n )\n }\n if (debugRenders) {\n debug(`Render ${element._key} (object block)`)\n }\n className = 'pt-block pt-object-block'\n const block = fromSlateValue(\n [element],\n schemaTypes.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0]\n let renderedBlockFromProps: JSX.Element | undefined\n if (renderBlock) {\n const _props: Omit<BlockRenderProps, 'type'> = Object.defineProperty(\n {\n children: <ObjectNode value={value} />,\n editorElementRef: blockRef,\n focused,\n path: blockPath,\n schemaType,\n selected,\n value: block,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaType\n },\n },\n )\n renderedBlockFromProps = renderBlock(_props as BlockRenderProps)\n }\n return (\n <div key={element._key} {...attributes} className={className}>\n {children}\n <DraggableBlock element={element} readOnly={readOnly} blockRef={blockRef}>\n {renderedBlockFromProps && (\n <div ref={blockRef} contentEditable={false}>\n {renderedBlockFromProps}\n </div>\n )}\n {!renderedBlockFromProps && (\n <DefaultBlockObject selected={selected}>\n <ObjectNode value={value} />\n </DefaultBlockObject>\n )}\n </DraggableBlock>\n </div>\n )\n}\n\nElement.displayName = 'Element'\n","import {createContext, useContext} from 'react'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\n/**\n * A React context for sharing the editor object.\n */\nexport const PortableTextEditorContext =\n createContext<PortableTextEditor | null>(null)\n\n/**\n * @public\n * Get the current editor object from the React context.\n */\nexport const usePortableTextEditor = (): PortableTextEditor => {\n const editor = useContext(PortableTextEditorContext)\n\n if (!editor) {\n throw new Error(\n `The \\`usePortableTextEditor\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n\n return editor\n}\n","import type {PortableTextObject} from '@sanity/types'\nimport {useCallback, type ReactNode} from 'react'\n\ntype Props = {\n annotation: PortableTextObject\n children: ReactNode\n}\nexport function DefaultAnnotation(props: Props) {\n const handleClick = useCallback(\n () => alert(JSON.stringify(props.annotation)),\n [props.annotation],\n )\n return (\n <span style={{color: 'blue'}} onClick={handleClick}>\n {props.children}\n </span>\n )\n}\n\nDefaultAnnotation.displayName = 'DefaultAnnotation'\n","import {Schema} from '@sanity/schema'\n\nexport function compileType(rawType: any) {\n return Schema.compile({\n name: 'blockTypeSchema',\n types: [rawType],\n }).get(rawType.name)\n}\n","import {\n diffMatchPatch,\n insert,\n set,\n setIfMissing,\n unset,\n type InsertPosition,\n type Patch,\n} from '@portabletext/patches'\nimport type {Path, PortableTextSpan, PortableTextTextBlock} from '@sanity/types'\nimport {get, isUndefined, omitBy} from 'lodash'\nimport {\n Text,\n type Descendant,\n type InsertNodeOperation,\n type InsertTextOperation,\n type MergeNodeOperation,\n type MoveNodeOperation,\n type RemoveNodeOperation,\n type RemoveTextOperation,\n type SetNodeOperation,\n type SplitNodeOperation,\n} from 'slate'\nimport type {PatchFunctions} from '../editor/plugins/createWithPatches'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../types/editor'\nimport {debugWithName} from './debug'\nimport {fromSlateValue} from './values'\n\nconst debug = debugWithName('operationToPatches')\n\nexport function createOperationToPatches(\n types: PortableTextMemberSchemaTypes,\n): PatchFunctions {\n const textBlockName = types.block.name\n function insertTextPatch(\n editor: PortableTextSlateEditor,\n operation: InsertTextOperation,\n beforeValue: Descendant[],\n ) {\n if (debug.enabled) {\n debug('Operation', JSON.stringify(operation, null, 2))\n }\n const block =\n editor.isTextBlock(editor.children[operation.path[0]]) &&\n editor.children[operation.path[0]]\n if (!block) {\n throw new Error('Could not find block')\n }\n const textChild =\n editor.isTextBlock(block) &&\n editor.isTextSpan(block.children[operation.path[1]]) &&\n (block.children[operation.path[1]] as PortableTextSpan)\n if (!textChild) {\n throw new Error('Could not find child')\n }\n const path: Path = [\n {_key: block._key},\n 'children',\n {_key: textChild._key},\n 'text',\n ]\n const prevBlock = beforeValue[operation.path[0]]\n const prevChild =\n editor.isTextBlock(prevBlock) && prevBlock.children[operation.path[1]]\n const prevText = editor.isTextSpan(prevChild) ? prevChild.text : ''\n const patch = diffMatchPatch(prevText, textChild.text, path)\n return patch.value.length ? [patch] : []\n }\n\n function removeTextPatch(\n editor: PortableTextSlateEditor,\n operation: RemoveTextOperation,\n beforeValue: Descendant[],\n ) {\n const block = editor && editor.children[operation.path[0]]\n if (!block) {\n throw new Error('Could not find block')\n }\n const child =\n (editor.isTextBlock(block) && block.children[operation.path[1]]) ||\n undefined\n const textChild: PortableTextSpan | undefined = editor.isTextSpan(child)\n ? child\n : undefined\n if (child && !textChild) {\n throw new Error('Expected span')\n }\n if (!textChild) {\n throw new Error('Could not find child')\n }\n const path: Path = [\n {_key: block._key},\n 'children',\n {_key: textChild._key},\n 'text',\n ]\n const beforeBlock = beforeValue[operation.path[0]]\n const prevTextChild =\n editor.isTextBlock(beforeBlock) && beforeBlock.children[operation.path[1]]\n const prevText = editor.isTextSpan(prevTextChild) && prevTextChild.text\n const patch = diffMatchPatch(prevText || '', textChild.text, path)\n return patch.value ? [patch] : []\n }\n\n function setNodePatch(\n editor: PortableTextSlateEditor,\n operation: SetNodeOperation,\n ) {\n if (operation.path.length === 1) {\n const block = editor.children[operation.path[0]]\n if (typeof block._key !== 'string') {\n throw new Error('Expected block to have a _key')\n }\n const setNode = omitBy(\n {...editor.children[operation.path[0]], ...operation.newProperties},\n isUndefined,\n ) as unknown as Descendant\n return [\n set(fromSlateValue([setNode], textBlockName)[0], [{_key: block._key}]),\n ]\n } else if (operation.path.length === 2) {\n const block = editor.children[operation.path[0]]\n if (editor.isTextBlock(block)) {\n const child = block.children[operation.path[1]]\n if (child) {\n const blockKey = block._key\n const childKey = child._key\n const patches: Patch[] = []\n const keys = Object.keys(operation.newProperties)\n keys.forEach((keyName) => {\n // Special case for setting _key on a child. We have to target it by index and not the _key.\n if (keys.length === 1 && keyName === '_key') {\n const val = get(operation.newProperties, keyName)\n patches.push(\n set(val, [\n {_key: blockKey},\n 'children',\n block.children.indexOf(child),\n keyName,\n ]),\n )\n } else {\n const val = get(operation.newProperties, keyName)\n patches.push(\n set(val, [\n {_key: blockKey},\n 'children',\n {_key: childKey},\n keyName,\n ]),\n )\n }\n })\n return patches\n }\n throw new Error('Could not find a valid child')\n }\n throw new Error('Could not find a valid block')\n } else {\n throw new Error(\n `Unexpected path encountered: ${JSON.stringify(operation.path)}`,\n )\n }\n }\n\n function insertNodePatch(\n editor: PortableTextSlateEditor,\n operation: InsertNodeOperation,\n beforeValue: Descendant[],\n ): Patch[] {\n const block = beforeValue[operation.path[0]]\n const isTextBlock = editor.isTextBlock(block)\n if (operation.path.length === 1) {\n const position = operation.path[0] === 0 ? 'before' : 'after'\n const beforeBlock = beforeValue[operation.path[0] - 1]\n const targetKey =\n operation.path[0] === 0 ? block?._key : beforeBlock?._key\n if (targetKey) {\n return [\n insert(\n [fromSlateValue([operation.node as Descendant], textBlockName)[0]],\n position,\n [{_key: targetKey}],\n ),\n ]\n }\n return [\n setIfMissing(beforeValue, []),\n insert(\n [fromSlateValue([operation.node as Descendant], textBlockName)[0]],\n 'before',\n [operation.path[0]],\n ),\n ]\n } else if (\n isTextBlock &&\n operation.path.length === 2 &&\n editor.children[operation.path[0]]\n ) {\n const position =\n block.children.length === 0 || !block.children[operation.path[1] - 1]\n ? 'before'\n : 'after'\n const node = {...operation.node} as Descendant\n if (!node._type && Text.isText(node)) {\n node._type = 'span'\n node.marks = []\n }\n const blk = fromSlateValue(\n [\n {\n _key: 'bogus',\n _type: textBlockName,\n children: [node],\n },\n ],\n textBlockName,\n )[0] as PortableTextTextBlock\n const child = blk.children[0]\n return [\n insert([child], position, [\n {_key: block._key},\n 'children',\n block.children.length <= 1 || !block.children[operation.path[1] - 1]\n ? 0\n : {_key: block.children[operation.path[1] - 1]._key},\n ]),\n ]\n }\n debug(\n 'Something was inserted into a void block. Not producing editor patches.',\n )\n return []\n }\n\n function splitNodePatch(\n editor: PortableTextSlateEditor,\n operation: SplitNodeOperation,\n beforeValue: Descendant[],\n ) {\n const patches: Patch[] = []\n const splitBlock = editor.children[operation.path[0]]\n if (!editor.isTextBlock(splitBlock)) {\n throw new Error(\n `Block with path ${JSON.stringify(\n operation.path[0],\n )} is not a text block and can't be split`,\n )\n }\n if (operation.path.length === 1) {\n const oldBlock = beforeValue[operation.path[0]]\n if (editor.isTextBlock(oldBlock)) {\n const targetValue = fromSlateValue(\n [editor.children[operation.path[0] + 1]],\n textBlockName,\n )[0]\n if (targetValue) {\n patches.push(\n insert([targetValue], 'after', [{_key: splitBlock._key}]),\n )\n const spansToUnset = oldBlock.children.slice(operation.position)\n spansToUnset.forEach((span) => {\n const path = [{_key: oldBlock._key}, 'children', {_key: span._key}]\n patches.push(unset(path))\n })\n }\n }\n return patches\n }\n if (operation.path.length === 2) {\n const splitSpan = splitBlock.children[operation.path[1]]\n if (editor.isTextSpan(splitSpan)) {\n const targetSpans = (\n fromSlateValue(\n [\n {\n ...splitBlock,\n children: splitBlock.children.slice(\n operation.path[1] + 1,\n operation.path[1] + 2,\n ),\n } as Descendant,\n ],\n textBlockName,\n )[0] as PortableTextTextBlock\n ).children\n\n patches.push(\n insert(targetSpans, 'after', [\n {_key: splitBlock._key},\n 'children',\n {_key: splitSpan._key},\n ]),\n )\n patches.push(\n set(splitSpan.text, [\n {_key: splitBlock._key},\n 'children',\n {_key: splitSpan._key},\n 'text',\n ]),\n )\n }\n return patches\n }\n return patches\n }\n\n function removeNodePatch(\n editor: PortableTextSlateEditor,\n operation: RemoveNodeOperation,\n beforeValue: Descendant[],\n ) {\n const block = beforeValue[operation.path[0]]\n if (operation.path.length === 1) {\n // Remove a single block\n if (block && block._key) {\n return [unset([{_key: block._key}])]\n }\n throw new Error('Block not found')\n } else if (editor.isTextBlock(block) && operation.path.length === 2) {\n const spanToRemove = block.children[operation.path[1]]\n\n if (spanToRemove) {\n const spansMatchingKey = block.children.filter(\n (span) => span._key === operation.node._key,\n )\n\n if (spansMatchingKey.length > 1) {\n console.warn(\n `Multiple spans have \\`_key\\` ${operation.node._key}. It's ambiguous which one to remove.`,\n JSON.stringify(block, null, 2),\n )\n return []\n }\n\n return [\n unset([{_key: block._key}, 'children', {_key: spanToRemove._key}]),\n ]\n }\n debug('Span not found in editor trying to remove node')\n return []\n } else {\n debug('Not creating patch inside object block')\n return []\n }\n }\n\n function mergeNodePatch(\n editor: PortableTextSlateEditor,\n operation: MergeNodeOperation,\n beforeValue: Descendant[],\n ) {\n const patches: Patch[] = []\n\n const block = beforeValue[operation.path[0]]\n const updatedBlock = editor.children[operation.path[0]]\n\n if (operation.path.length === 1) {\n if (block?._key) {\n const newBlock = fromSlateValue(\n [editor.children[operation.path[0] - 1]],\n textBlockName,\n )[0]\n patches.push(set(newBlock, [{_key: newBlock._key}]))\n patches.push(unset([{_key: block._key}]))\n } else {\n throw new Error('Target key not found!')\n }\n } else if (\n editor.isTextBlock(block) &&\n editor.isTextBlock(updatedBlock) &&\n operation.path.length === 2\n ) {\n const updatedSpan =\n updatedBlock.children[operation.path[1] - 1] &&\n editor.isTextSpan(updatedBlock.children[operation.path[1] - 1])\n ? updatedBlock.children[operation.path[1] - 1]\n : undefined\n const removedSpan =\n block.children[operation.path[1]] &&\n editor.isTextSpan(block.children[operation.path[1]])\n ? block.children[operation.path[1]]\n : undefined\n\n if (updatedSpan) {\n const spansMatchingKey = block.children.filter(\n (span) => span._key === updatedSpan._key,\n )\n\n if (spansMatchingKey.length === 1) {\n patches.push(\n set(updatedSpan.text, [\n {_key: block._key},\n 'children',\n {_key: updatedSpan._key},\n 'text',\n ]),\n )\n } else {\n console.warn(\n `Multiple spans have \\`_key\\` ${updatedSpan._key}. It's ambiguous which one to update.`,\n JSON.stringify(block, null, 2),\n )\n }\n }\n\n if (removedSpan) {\n const spansMatchingKey = block.children.filter(\n (span) => span._key === removedSpan._key,\n )\n\n if (spansMatchingKey.length === 1) {\n patches.push(\n unset([{_key: block._key}, 'children', {_key: removedSpan._key}]),\n )\n } else {\n console.warn(\n `Multiple spans have \\`_key\\` ${removedSpan._key}. It's ambiguous which one to remove.`,\n JSON.stringify(block, null, 2),\n )\n }\n }\n } else {\n debug(\"Void nodes can't be merged, not creating any patches\")\n }\n return patches\n }\n\n function moveNodePatch(\n editor: PortableTextSlateEditor,\n operation: MoveNodeOperation,\n beforeValue: Descendant[],\n ) {\n const patches: Patch[] = []\n const block = beforeValue[operation.path[0]]\n const targetBlock = beforeValue[operation.newPath[0]]\n if (operation.path.length === 1) {\n const position: InsertPosition =\n operation.path[0] > operation.newPath[0] ? 'before' : 'after'\n patches.push(unset([{_key: block._key}]))\n patches.push(\n insert([fromSlateValue([block], textBlockName)[0]], position, [\n {_key: targetBlock._key},\n ]),\n )\n } else if (\n operation.path.length === 2 &&\n editor.isTextBlock(block) &&\n editor.isTextBlock(targetBlock)\n ) {\n const child = block.children[operation.path[1]]\n const targetChild = targetBlock.children[operation.newPath[1]]\n const position =\n operation.newPath[1] === targetBlock.children.length\n ? 'after'\n : 'before'\n const childToInsert = (\n fromSlateValue([block], textBlockName)[0] as PortableTextTextBlock\n ).children[operation.path[1]]\n patches.push(unset([{_key: block._key}, 'children', {_key: child._key}]))\n patches.push(\n insert([childToInsert], position, [\n {_key: targetBlock._key},\n 'children',\n {_key: targetChild._key},\n ]),\n )\n }\n return patches\n }\n\n return {\n insertNodePatch,\n insertTextPatch,\n mergeNodePatch,\n moveNodePatch,\n removeNodePatch,\n removeTextPatch,\n setNodePatch,\n splitNodePatch,\n }\n}\n","import type {Editor} from 'slate'\nimport type {EditorActor} from '../editor-machine'\n\nexport function createWithEventListeners(editorActor: EditorActor) {\n return function withEventListeners(editor: Editor) {\n editor.addMark = (mark) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.add',\n decorator: mark,\n },\n editor,\n })\n return\n }\n\n editor.removeMark = (mark) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.remove',\n decorator: mark,\n },\n editor,\n })\n return\n }\n\n editor.deleteBackward = (unit) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'delete backward',\n unit,\n },\n editor,\n })\n return\n }\n\n editor.deleteForward = (unit) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'delete forward',\n unit,\n },\n editor,\n })\n return\n }\n\n editor.insertBreak = () => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'insert break',\n },\n editor,\n })\n return\n }\n\n editor.insertSoftBreak = () => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'insert soft break',\n },\n editor,\n })\n return\n }\n\n editor.insertText = (text, options) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'insert text',\n text,\n options,\n },\n editor,\n })\n return\n }\n\n return editor\n }\n}\n","function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction isPortableTextSpan(node) {\n return node._type === \"span\" && \"text\" in node && typeof node.text == \"string\" && (typeof node.marks > \"u\" || Array.isArray(node.marks) && node.marks.every(mark => typeof mark == \"string\"));\n}\nfunction isPortableTextBlock(node) {\n return (\n // A block doesn't _have_ to be named 'block' - to differentiate between\n // allowed child types and marks, one might name them differently\n typeof node._type == \"string\" &&\n // Toolkit-types like nested spans are @-prefixed\n node._type[0] !== \"@\" && (\n // `markDefs` isn't _required_ per say, but if it's there, it needs to be an array\n !(\"markDefs\" in node) || !node.markDefs || Array.isArray(node.markDefs) &&\n // Every mark definition needs to have an `_key` to be mappable in child spans\n node.markDefs.every(def => typeof def._key == \"string\")) &&\n // `children` is required and needs to be an array\n \"children\" in node && Array.isArray(node.children) &&\n // All children are objects with `_type` (usually spans, but can contain other stuff)\n node.children.every(child => typeof child == \"object\" && \"_type\" in child)\n );\n}\nfunction isPortableTextListItemBlock(block) {\n return isPortableTextBlock(block) && \"listItem\" in block && typeof block.listItem == \"string\" && (typeof block.level > \"u\" || typeof block.level == \"number\");\n}\nfunction isPortableTextToolkitList(block) {\n return block._type === \"@list\";\n}\nfunction isPortableTextToolkitSpan(span) {\n return span._type === \"@span\";\n}\nfunction isPortableTextToolkitTextNode(node) {\n return node._type === \"@text\";\n}\nconst knownDecorators = [\"strong\", \"em\", \"code\", \"underline\", \"strike-through\"];\nfunction sortMarksByOccurences(span, index, blockChildren) {\n if (!isPortableTextSpan(span) || !span.marks) return [];\n if (!span.marks.length) return [];\n const marks = span.marks.slice(),\n occurences = {};\n return marks.forEach(mark => {\n occurences[mark] = 1;\n for (let siblingIndex = index + 1; siblingIndex < blockChildren.length; siblingIndex++) {\n const sibling = blockChildren[siblingIndex];\n if (sibling && isPortableTextSpan(sibling) && Array.isArray(sibling.marks) && sibling.marks.indexOf(mark) !== -1) occurences[mark]++;else break;\n }\n }), marks.sort((markA, markB) => sortMarks(occurences, markA, markB));\n}\nfunction sortMarks(occurences, markA, markB) {\n const aOccurences = occurences[markA],\n bOccurences = occurences[markB];\n if (aOccurences !== bOccurences) return bOccurences - aOccurences;\n const aKnownPos = knownDecorators.indexOf(markA),\n bKnownPos = knownDecorators.indexOf(markB);\n return aKnownPos !== bKnownPos ? aKnownPos - bKnownPos : markA.localeCompare(markB);\n}\nfunction buildMarksTree(block) {\n var _a;\n const {\n children,\n markDefs = []\n } = block;\n if (!children || !children.length) return [];\n const sortedMarks = children.map(sortMarksByOccurences),\n rootNode = {\n _type: \"@span\",\n children: [],\n markType: \"<unknown>\"\n };\n let nodeStack = [rootNode];\n for (let i = 0; i < children.length; i++) {\n const span = children[i];\n if (!span) continue;\n const marksNeeded = sortedMarks[i] || [];\n let pos = 1;\n if (nodeStack.length > 1) for (pos; pos < nodeStack.length; pos++) {\n const mark = ((_a = nodeStack[pos]) == null ? void 0 : _a.markKey) || \"\",\n index = marksNeeded.indexOf(mark);\n if (index === -1) break;\n marksNeeded.splice(index, 1);\n }\n nodeStack = nodeStack.slice(0, pos);\n let currentNode = nodeStack[nodeStack.length - 1];\n if (currentNode) {\n for (const markKey of marksNeeded) {\n const markDef = markDefs.find(def => def._key === markKey),\n markType = markDef ? markDef._type : markKey,\n node = {\n _type: \"@span\",\n _key: span._key,\n children: [],\n markDef,\n markType,\n markKey\n };\n currentNode.children.push(node), nodeStack.push(node), currentNode = node;\n }\n if (isPortableTextSpan(span)) {\n const lines = span.text.split(`\n`);\n for (let line = lines.length; line-- > 1;) lines.splice(line, 0, `\n`);\n currentNode.children = currentNode.children.concat(lines.map(text => ({\n _type: \"@text\",\n text\n })));\n } else currentNode.children = currentNode.children.concat(span);\n }\n }\n return rootNode.children;\n}\nfunction nestLists(blocks, mode) {\n const tree = [];\n let currentList;\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (block) {\n if (!isPortableTextListItemBlock(block)) {\n tree.push(block), currentList = void 0;\n continue;\n }\n if (!currentList) {\n currentList = listFromBlock(block, i, mode), tree.push(currentList);\n continue;\n }\n if (blockMatchesList(block, currentList)) {\n currentList.children.push(block);\n continue;\n }\n if ((block.level || 1) > currentList.level) {\n const newList = listFromBlock(block, i, mode);\n if (mode === \"html\") {\n const lastListItem = currentList.children[currentList.children.length - 1],\n newLastChild = _objectSpread(_objectSpread({}, lastListItem), {}, {\n children: [...lastListItem.children, newList]\n });\n currentList.children[currentList.children.length - 1] = newLastChild;\n } else currentList.children.push(newList);\n currentList = newList;\n continue;\n }\n if ((block.level || 1) < currentList.level) {\n const matchingBranch = tree[tree.length - 1],\n match = matchingBranch && findListMatching(matchingBranch, block);\n if (match) {\n currentList = match, currentList.children.push(block);\n continue;\n }\n currentList = listFromBlock(block, i, mode), tree.push(currentList);\n continue;\n }\n if (block.listItem !== currentList.listItem) {\n const matchingBranch = tree[tree.length - 1],\n match = matchingBranch && findListMatching(matchingBranch, {\n level: block.level || 1\n });\n if (match && match.listItem === block.listItem) {\n currentList = match, currentList.children.push(block);\n continue;\n } else {\n currentList = listFromBlock(block, i, mode), tree.push(currentList);\n continue;\n }\n }\n console.warn(\"Unknown state encountered for block\", block), tree.push(block);\n }\n }\n return tree;\n}\nfunction blockMatchesList(block, list) {\n return (block.level || 1) === list.level && block.listItem === list.listItem;\n}\nfunction listFromBlock(block, index, mode) {\n return {\n _type: \"@list\",\n _key: `${block._key || `${index}`}-parent`,\n mode,\n level: block.level || 1,\n listItem: block.listItem,\n children: [block]\n };\n}\nfunction findListMatching(rootNode, matching) {\n const level = matching.level || 1,\n style = matching.listItem || \"normal\",\n filterOnType = typeof matching.listItem == \"string\";\n if (isPortableTextToolkitList(rootNode) && (rootNode.level || 1) === level && filterOnType && (rootNode.listItem || \"normal\") === style) return rootNode;\n if (!(\"children\" in rootNode)) return;\n const node = rootNode.children[rootNode.children.length - 1];\n return node && !isPortableTextSpan(node) ? findListMatching(node, matching) : void 0;\n}\nfunction spanToPlainText(span) {\n let text = \"\";\n return span.children.forEach(current => {\n isPortableTextToolkitTextNode(current) ? text += current.text : isPortableTextToolkitSpan(current) && (text += spanToPlainText(current));\n }), text;\n}\nconst leadingSpace = /^\\s/,\n trailingSpace = /\\s$/;\nfunction toPlainText(block) {\n const blocks = Array.isArray(block) ? block : [block];\n let text = \"\";\n return blocks.forEach((current, index) => {\n if (!isPortableTextBlock(current)) return;\n let pad = !1;\n current.children.forEach(span => {\n isPortableTextSpan(span) ? (text += pad && text && !trailingSpace.test(text) && !leadingSpace.test(span.text) ? \" \" : \"\", text += span.text, pad = !1) : pad = !0;\n }), index !== blocks.length - 1 && (text += `\n\n`);\n }), text;\n}\nconst LIST_NEST_MODE_HTML = \"html\",\n LIST_NEST_MODE_DIRECT = \"direct\";\nexport { LIST_NEST_MODE_DIRECT, LIST_NEST_MODE_HTML, buildMarksTree, isPortableTextBlock, isPortableTextListItemBlock, isPortableTextSpan, isPortableTextToolkitList, isPortableTextToolkitSpan, isPortableTextToolkitTextNode, nestLists, sortMarksByOccurences, spanToPlainText, toPlainText };\n//# sourceMappingURL=index.js.map\n","import type {PortableTextSpan} from '@sanity/types'\nimport {Node, Path} from 'slate'\nimport type {PortableTextSlateEditor} from '../types/editor'\n\nexport function getPreviousSpan({\n editor,\n blockPath,\n spanPath,\n}: {\n editor: PortableTextSlateEditor\n blockPath: Path\n spanPath: Path\n}): PortableTextSpan | undefined {\n let previousSpan: PortableTextSpan | undefined\n\n for (const [child, childPath] of Node.children(editor, blockPath, {\n reverse: true,\n })) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (Path.isBefore(childPath, spanPath)) {\n previousSpan = child\n break\n }\n }\n\n return previousSpan\n}\n\nexport function getNextSpan({\n editor,\n blockPath,\n spanPath,\n}: {\n editor: PortableTextSlateEditor\n blockPath: Path\n spanPath: Path\n}): PortableTextSpan | undefined {\n let nextSpan: PortableTextSpan | undefined\n\n for (const [child, childPath] of Node.children(editor, blockPath)) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (Path.isAfter(childPath, spanPath)) {\n nextSpan = child\n break\n }\n }\n\n return nextSpan\n}\n","import type {Editor} from 'slate'\nimport {\n IS_PROCESSING_LOCAL_CHANGES,\n IS_PROCESSING_REMOTE_CHANGES,\n} from './weakMaps'\n\nexport function withRemoteChanges(editor: Editor, fn: () => void): void {\n const prev = isChangingRemotely(editor) || false\n IS_PROCESSING_REMOTE_CHANGES.set(editor, true)\n fn()\n IS_PROCESSING_REMOTE_CHANGES.set(editor, prev)\n}\n\nexport function isChangingRemotely(editor: Editor): boolean | undefined {\n return IS_PROCESSING_REMOTE_CHANGES.get(editor)\n}\n\nexport function isChangingLocally(editor: Editor): boolean | undefined {\n return IS_PROCESSING_LOCAL_CHANGES.get(editor)\n}\n","import type {Editor} from 'slate'\n\nconst IS_UDOING: WeakMap<Editor, boolean | undefined> = new WeakMap()\nconst IS_REDOING: WeakMap<Editor, boolean | undefined> = new WeakMap()\n\nexport function withUndoing(editor: Editor, fn: () => void) {\n const prev = isUndoing(editor)\n IS_UDOING.set(editor, true)\n fn()\n IS_UDOING.set(editor, prev)\n}\n\nexport function isUndoing(editor: Editor) {\n return IS_UDOING.get(editor) ?? false\n}\n\nexport function setIsUndoing(editor: Editor, isUndoing: boolean) {\n IS_UDOING.set(editor, isUndoing)\n}\n\nexport function withRedoing(editor: Editor, fn: () => void) {\n const prev = isRedoing(editor)\n IS_REDOING.set(editor, true)\n fn()\n IS_REDOING.set(editor, prev)\n}\n\nexport function isRedoing(editor: Editor) {\n return IS_REDOING.get(editor) ?? false\n}\n\nexport function setIsRedoing(editor: Editor, isRedoing: boolean) {\n IS_REDOING.set(editor, isRedoing)\n}\n","/**\n *\n * This plugin will change Slate's default marks model (every prop is a mark) with the Portable Text model (marks is an array of strings on prop .marks).\n *\n */\n\nimport {isPortableTextBlock, isPortableTextSpan} from '@portabletext/toolkit'\nimport type {PortableTextObject, PortableTextSpan} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {Editor, Element, Node, Path, Range, Text, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {getNextSpan, getPreviousSpan} from '../../utils/sibling-utils'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {BehaviourActionImplementation} from '../behavior/behavior.actions'\nimport type {BehaviorAction, PickFromUnion} from '../behavior/behavior.types'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextMarkModel')\n\nexport function createWithPortableTextMarkModel(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n return function withPortableTextMarkModel(editor: PortableTextSlateEditor) {\n const {apply, normalizeNode} = editor\n const decorators = types.decorators.map((t) => t.value)\n\n // Extend Slate's default normalization. Merge spans with same set of .marks when doing merge_node operations, and clean up markDefs / marks\n editor.normalizeNode = (nodeEntry) => {\n const [node, path] = nodeEntry\n\n if (editor.isTextBlock(node)) {\n const children = Node.children(editor, path)\n\n for (const [child, childPath] of children) {\n const nextNode = node.children[childPath[1] + 1]\n\n if (\n editor.isTextSpan(child) &&\n editor.isTextSpan(nextNode) &&\n child.marks?.every((mark) => nextNode.marks?.includes(mark)) &&\n nextNode.marks?.every((mark) => child.marks?.includes(mark))\n ) {\n debug(\n 'Merging spans',\n JSON.stringify(child, null, 2),\n JSON.stringify(nextNode, null, 2),\n )\n editorActor.send({type: 'normalizing'})\n Transforms.mergeNodes(editor, {\n at: [childPath[0], childPath[1] + 1],\n voids: true,\n })\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n /**\n * Add missing .markDefs to block nodes\n */\n if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {\n debug('Adding .markDefs to block node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {markDefs: []}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n /**\n * Add missing .marks to span nodes\n */\n if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {\n debug('Adding .marks to span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {marks: []}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n /**\n * Remove annotations from empty spans\n */\n if (editor.isTextSpan(node)) {\n const blockPath = Path.parent(path)\n const [block] = Editor.node(editor, blockPath)\n const decorators = types.decorators.map((decorator) => decorator.value)\n const annotations = node.marks?.filter(\n (mark) => !decorators.includes(mark),\n )\n\n if (editor.isTextBlock(block)) {\n if (node.text === '' && annotations && annotations.length > 0) {\n debug('Removing annotations from empty span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {marks: node.marks?.filter((mark) => decorators.includes(mark))},\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n /**\n * Remove orphaned annotations from child spans of block nodes\n */\n if (editor.isTextBlock(node)) {\n const decorators = types.decorators.map((decorator) => decorator.value)\n\n for (const [child, childPath] of Node.children(editor, path)) {\n if (editor.isTextSpan(child)) {\n const marks = child.marks ?? []\n const orphanedAnnotations = marks.filter((mark) => {\n return (\n !decorators.includes(mark) &&\n !node.markDefs?.find((def) => def._key === mark)\n )\n })\n\n if (orphanedAnnotations.length > 0) {\n debug('Removing orphaned annotations from span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {\n marks: marks.filter(\n (mark) => !orphanedAnnotations.includes(mark),\n ),\n },\n {at: childPath},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n }\n\n /**\n * Remove orphaned annotations from span nodes\n */\n if (editor.isTextSpan(node)) {\n const blockPath = Path.parent(path)\n const [block] = Editor.node(editor, blockPath)\n\n if (editor.isTextBlock(block)) {\n const decorators = types.decorators.map(\n (decorator) => decorator.value,\n )\n const marks = node.marks ?? []\n const orphanedAnnotations = marks.filter((mark) => {\n return (\n !decorators.includes(mark) &&\n !block.markDefs?.find((def) => def._key === mark)\n )\n })\n\n if (orphanedAnnotations.length > 0) {\n debug('Removing orphaned annotations from span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {\n marks: marks.filter(\n (mark) => !orphanedAnnotations.includes(mark),\n ),\n },\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n // Remove duplicate markDefs\n if (editor.isTextBlock(node)) {\n const markDefs = node.markDefs ?? []\n const markDefKeys = new Set<string>()\n const newMarkDefs: Array<PortableTextObject> = []\n\n for (const markDef of markDefs) {\n if (!markDefKeys.has(markDef._key)) {\n markDefKeys.add(markDef._key)\n newMarkDefs.push(markDef)\n }\n }\n\n if (markDefs.length !== newMarkDefs.length) {\n debug('Removing duplicate markDefs')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {markDefs: newMarkDefs}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n\n // Check consistency of markDefs (unless we are merging two nodes)\n if (\n editor.isTextBlock(node) &&\n !editor.operations.some(\n (op) =>\n op.type === 'merge_node' &&\n 'markDefs' in op.properties &&\n op.path.length === 1,\n )\n ) {\n const newMarkDefs = (node.markDefs || []).filter((def) => {\n return node.children.find((child) => {\n return (\n Text.isText(child) &&\n Array.isArray(child.marks) &&\n child.marks.includes(def._key)\n )\n })\n })\n if (node.markDefs && !isEqual(newMarkDefs, node.markDefs)) {\n debug('Removing markDef not in use')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {\n markDefs: newMarkDefs,\n },\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n\n normalizeNode(nodeEntry)\n }\n\n editor.apply = (op) => {\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(op)\n return\n }\n\n if (op.type === 'set_selection') {\n const marks = Editor.marks(editor)\n\n if (\n marks &&\n op.properties &&\n op.newProperties &&\n op.properties.anchor &&\n op.properties.focus &&\n op.newProperties.anchor &&\n op.newProperties.focus\n ) {\n const previousSelectionIsCollapsed = Range.isCollapsed({\n anchor: op.properties.anchor,\n focus: op.properties.focus,\n })\n const newSelectionIsCollapsed = Range.isCollapsed({\n anchor: op.newProperties.anchor,\n focus: op.newProperties.focus,\n })\n\n if (previousSelectionIsCollapsed && newSelectionIsCollapsed) {\n const focusSpan: PortableTextSpan | undefined = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: op.properties.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0]?.[0]\n const newFocusSpan: PortableTextSpan | undefined = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: op.newProperties.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0]?.[0]\n const movedToNextSpan =\n focusSpan &&\n newFocusSpan &&\n op.newProperties.focus.path[0] === op.properties.focus.path[0] &&\n op.newProperties.focus.path[1] ===\n op.properties.focus.path[1] + 1 &&\n focusSpan.text.length === op.properties.focus.offset &&\n op.newProperties.focus.offset === 0\n const movedToPreviousSpan =\n focusSpan &&\n newFocusSpan &&\n op.newProperties.focus.path[0] === op.properties.focus.path[0] &&\n op.newProperties.focus.path[1] ===\n op.properties.focus.path[1] - 1 &&\n op.properties.focus.offset === 0 &&\n newFocusSpan.text.length === op.newProperties.focus.offset\n\n // If the editor has marks and we are not visually moving the\n // selection then we just abort. Otherwise the marks would be\n // cleared and we can't use them for the possible subsequent insert\n // operation.\n if (movedToNextSpan || movedToPreviousSpan) {\n return\n }\n }\n }\n }\n\n if (op.type === 'insert_node') {\n const {selection} = editor\n\n if (selection) {\n const [_block, blockPath] = Editor.node(editor, selection, {depth: 1})\n const previousSpan = getPreviousSpan({\n editor,\n blockPath,\n spanPath: op.path,\n })\n const previousSpanAnnotations = previousSpan\n ? previousSpan.marks?.filter((mark) => !decorators.includes(mark))\n : []\n\n const nextSpan = getNextSpan({\n editor,\n blockPath,\n spanPath: [op.path[0], op.path[1] - 1],\n })\n const nextSpanAnnotations = nextSpan\n ? nextSpan.marks?.filter((mark) => !decorators.includes(mark))\n : []\n\n const annotationsEnding =\n previousSpanAnnotations?.filter(\n (annotation) => !nextSpanAnnotations?.includes(annotation),\n ) ?? []\n const atTheEndOfAnnotation = annotationsEnding.length > 0\n\n if (\n atTheEndOfAnnotation &&\n isPortableTextSpan(op.node) &&\n op.node.marks?.some((mark) => annotationsEnding.includes(mark))\n ) {\n Transforms.insertNodes(editor, {\n ...op.node,\n marks:\n op.node.marks?.filter(\n (mark) => !annotationsEnding.includes(mark),\n ) ?? [],\n })\n return\n }\n\n const annotationsStarting =\n nextSpanAnnotations?.filter(\n (annotation) => !previousSpanAnnotations?.includes(annotation),\n ) ?? []\n const atTheStartOfAnnotation = annotationsStarting.length > 0\n\n if (\n atTheStartOfAnnotation &&\n isPortableTextSpan(op.node) &&\n op.node.marks?.some((mark) => annotationsStarting.includes(mark))\n ) {\n Transforms.insertNodes(editor, {\n ...op.node,\n marks:\n op.node.marks?.filter(\n (mark) => !annotationsStarting.includes(mark),\n ) ?? [],\n })\n return\n }\n\n const nextSpanDecorators =\n nextSpan?.marks?.filter((mark) => decorators.includes(mark)) ?? []\n const decoratorStarting = nextSpanDecorators.length > 0\n\n if (\n decoratorStarting &&\n atTheEndOfAnnotation &&\n !atTheStartOfAnnotation &&\n isPortableTextSpan(op.node) &&\n op.node.marks?.length === 0\n ) {\n Transforms.insertNodes(editor, {\n ...op.node,\n marks: nextSpanDecorators,\n })\n return\n }\n }\n }\n\n if (op.type === 'insert_text') {\n const {selection} = editor\n const collapsedSelection = selection\n ? Range.isCollapsed(selection)\n : false\n\n if (selection && collapsedSelection) {\n const [_block, blockPath] = Editor.node(editor, selection, {\n depth: 1,\n })\n\n const [span, spanPath] =\n Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: selection.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0] ?? ([undefined, undefined] as const)\n\n const marks = span.marks ?? []\n const marksWithoutAnnotations = marks.filter((mark) =>\n decorators.includes(mark),\n )\n const spanHasAnnotations =\n marks.length > marksWithoutAnnotations.length\n\n const spanIsEmpty = span.text.length === 0\n\n const atTheBeginningOfSpan = selection.anchor.offset === 0\n const atTheEndOfSpan = selection.anchor.offset === span.text.length\n\n const previousSpan = getPreviousSpan({editor, blockPath, spanPath})\n const nextSpan = getNextSpan({editor, blockPath, spanPath})\n const nextSpanAnnotations =\n nextSpan?.marks?.filter((mark) => !decorators.includes(mark)) ?? []\n const spanAnnotations = marks.filter(\n (mark) => !decorators.includes(mark),\n )\n\n const previousSpanHasAnnotations = previousSpan\n ? previousSpan.marks?.some((mark) => !decorators.includes(mark))\n : false\n const previousSpanHasSameAnnotations = previousSpan\n ? previousSpan.marks\n ?.filter((mark) => !decorators.includes(mark))\n .every((mark) => marks.includes(mark))\n : false\n const previousSpanHasSameAnnotation = previousSpan\n ? previousSpan.marks?.some(\n (mark) => !decorators.includes(mark) && marks.includes(mark),\n )\n : false\n\n const previousSpanHasSameMarks = previousSpan\n ? previousSpan.marks?.every((mark) => marks.includes(mark))\n : false\n const nextSpanSharesSomeAnnotations = spanAnnotations.some((mark) =>\n nextSpanAnnotations?.includes(mark),\n )\n\n if (spanHasAnnotations && !spanIsEmpty) {\n if (atTheBeginningOfSpan) {\n if (previousSpanHasSameMarks) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: previousSpan?.marks ?? [],\n })\n return\n } else if (previousSpanHasSameAnnotations) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: previousSpan?.marks ?? [],\n })\n return\n } else if (previousSpanHasSameAnnotation) {\n apply(op)\n return\n } else if (!previousSpan) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: [],\n })\n return\n }\n }\n\n if (atTheEndOfSpan) {\n if (\n (nextSpan &&\n nextSpanSharesSomeAnnotations &&\n nextSpanAnnotations.length < spanAnnotations.length) ||\n !nextSpanSharesSomeAnnotations\n ) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: nextSpan?.marks ?? [],\n })\n return\n }\n\n if (!nextSpan) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: [],\n })\n return\n }\n }\n }\n\n if (atTheBeginningOfSpan && !spanIsEmpty && !!previousSpan) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: previousSpanHasAnnotations\n ? []\n : (previousSpan.marks ?? []).filter((mark) =>\n decorators.includes(mark),\n ),\n })\n return\n }\n }\n }\n\n if (op.type === 'remove_text') {\n const {selection} = editor\n\n if (selection && Range.isExpanded(selection)) {\n const [block, blockPath] = Editor.node(editor, selection, {\n depth: 1,\n })\n const [span, spanPath] =\n Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: {path: op.path, offset: op.offset},\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0] ?? ([undefined, undefined] as const)\n\n if (span && block && isPortableTextBlock(block)) {\n const markDefs = block.markDefs ?? []\n const marks = span.marks ?? []\n const spanHasAnnotations = marks.some((mark) =>\n markDefs.find((markDef) => markDef._key === mark),\n )\n const deletingFromTheEnd =\n op.offset + op.text.length === span.text.length\n const deletingAllText = op.offset === 0 && deletingFromTheEnd\n\n const previousSpan = getPreviousSpan({editor, blockPath, spanPath})\n const nextSpan = getNextSpan({editor, blockPath, spanPath})\n\n const previousSpanHasSameAnnotation = previousSpan\n ? previousSpan.marks?.some(\n (mark) => !decorators.includes(mark) && marks.includes(mark),\n )\n : false\n const nextSpanHasSameAnnotation = nextSpan\n ? nextSpan.marks?.some(\n (mark) => !decorators.includes(mark) && marks.includes(mark),\n )\n : false\n\n if (\n spanHasAnnotations &&\n deletingAllText &&\n !previousSpanHasSameAnnotation &&\n !nextSpanHasSameAnnotation\n ) {\n const marksWithoutAnnotationMarks: string[] = (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).filter((mark) => decorators.includes(mark))\n\n Editor.withoutNormalizing(editor, () => {\n apply(op)\n Transforms.setNodes(\n editor,\n {marks: marksWithoutAnnotationMarks},\n {at: op.path},\n )\n })\n\n editor.onChange()\n return\n }\n }\n }\n }\n\n /**\n * Copy over markDefs when merging blocks\n */\n if (\n op.type === 'merge_node' &&\n op.path.length === 1 &&\n 'markDefs' in op.properties &&\n op.properties._type === types.block.name &&\n Array.isArray(op.properties.markDefs) &&\n op.properties.markDefs.length > 0 &&\n op.path[0] - 1 >= 0\n ) {\n const [targetBlock, targetPath] = Editor.node(editor, [op.path[0] - 1])\n\n if (editor.isTextBlock(targetBlock)) {\n const oldDefs =\n (Array.isArray(targetBlock.markDefs) && targetBlock.markDefs) || []\n const newMarkDefs = uniq([...oldDefs, ...op.properties.markDefs])\n\n debug(`Copying markDefs over to merged block`, op)\n Transforms.setNodes(\n editor,\n {markDefs: newMarkDefs},\n {at: targetPath, voids: false},\n )\n apply(op)\n return\n }\n }\n\n apply(op)\n }\n\n return editor\n }\n}\n\nexport const addDecoratorActionImplementation: BehaviourActionImplementation<\n PickFromUnion<BehaviorAction, 'type', 'decorator.add'>\n> = ({action}) => {\n const editor = action.editor\n const mark = action.decorator\n\n if (editor.selection) {\n if (Range.isExpanded(editor.selection)) {\n // Split if needed\n Transforms.setNodes(\n editor,\n {},\n {match: Text.isText, split: true, hanging: true},\n )\n // Use new selection\n const splitTextNodes = Range.isRange(editor.selection)\n ? [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: Text.isText,\n }),\n ]\n : []\n const shouldRemoveMark =\n splitTextNodes.length > 1 &&\n splitTextNodes.every((node) => node[0].marks?.includes(mark))\n\n if (shouldRemoveMark) {\n editor.removeMark(mark)\n } else {\n splitTextNodes.forEach(([node, path]) => {\n const marks = [\n ...(Array.isArray(node.marks) ? node.marks : []).filter(\n (eMark: string) => eMark !== mark,\n ),\n mark,\n ]\n Transforms.setNodes(\n editor,\n {marks},\n {at: path, match: Text.isText, split: true, hanging: true},\n )\n })\n }\n } else {\n const [block, blockPath] = Editor.node(editor, editor.selection, {\n depth: 1,\n })\n const lonelyEmptySpan =\n editor.isTextBlock(block) &&\n block.children.length === 1 &&\n editor.isTextSpan(block.children[0]) &&\n block.children[0].text === ''\n ? block.children[0]\n : undefined\n\n if (lonelyEmptySpan) {\n const existingMarks = lonelyEmptySpan.marks ?? []\n const existingMarksWithoutDecorator = existingMarks.filter(\n (existingMark) => existingMark !== mark,\n )\n\n Transforms.setNodes(\n editor,\n {\n marks:\n existingMarks.length === existingMarksWithoutDecorator.length\n ? [...existingMarks, mark]\n : existingMarksWithoutDecorator,\n },\n {\n at: blockPath,\n match: (node) => editor.isTextSpan(node),\n },\n )\n } else {\n const existingMarks: string[] =\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n const marks = {\n ...(Editor.marks(editor) || {}),\n marks: [...existingMarks, mark],\n }\n editor.marks = marks as Text\n }\n }\n editor.onChange()\n }\n}\n\nexport const removeDecoratorActionImplementation: BehaviourActionImplementation<\n PickFromUnion<BehaviorAction, 'type', 'decorator.remove'>\n> = ({action}) => {\n const editor = action.editor\n const mark = action.decorator\n const {selection} = editor\n\n if (selection) {\n if (Range.isExpanded(selection)) {\n // Split if needed\n Transforms.setNodes(\n editor,\n {},\n {match: Text.isText, split: true, hanging: true},\n )\n if (editor.selection) {\n const splitTextNodes = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: Text.isText,\n }),\n ]\n splitTextNodes.forEach(([node, path]) => {\n const block = editor.children[path[0]]\n if (Element.isElement(block) && block.children.includes(node)) {\n Transforms.setNodes(\n editor,\n {\n marks: (Array.isArray(node.marks) ? node.marks : []).filter(\n (eMark: string) => eMark !== mark,\n ),\n _type: 'span',\n },\n {at: path},\n )\n }\n })\n }\n } else {\n const [block, blockPath] = Editor.node(editor, selection, {\n depth: 1,\n })\n const lonelyEmptySpan =\n editor.isTextBlock(block) &&\n block.children.length === 1 &&\n editor.isTextSpan(block.children[0]) &&\n block.children[0].text === ''\n ? block.children[0]\n : undefined\n\n if (lonelyEmptySpan) {\n const existingMarks = lonelyEmptySpan.marks ?? []\n const existingMarksWithoutDecorator = existingMarks.filter(\n (existingMark) => existingMark !== mark,\n )\n\n Transforms.setNodes(\n editor,\n {\n marks: existingMarksWithoutDecorator,\n },\n {\n at: blockPath,\n match: (node) => editor.isTextSpan(node),\n },\n )\n } else {\n const existingMarks: string[] =\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n const marks = {\n ...(Editor.marks(editor) || {}),\n marks: existingMarks.filter((eMark) => eMark !== mark),\n } as Text\n editor.marks = {marks: marks.marks, _type: 'span'} as Text\n }\n }\n }\n}\n\nexport function isDecoratorActive({\n editor,\n decorator,\n}: {\n editor: PortableTextSlateEditor\n decorator: string\n}) {\n if (!editor.selection) {\n return false\n }\n\n const selectedNodes = Array.from(\n Editor.nodes(editor, {match: Text.isText, at: editor.selection}),\n )\n\n if (Range.isExpanded(editor.selection)) {\n return selectedNodes.every((n) => {\n const [node] = n\n\n return node.marks?.includes(decorator)\n })\n }\n\n return (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).includes(decorator)\n}\n\nexport const toggleDecoratorActionImplementation: BehaviourActionImplementation<\n PickFromUnion<BehaviorAction, 'type', 'decorator.toggle'>\n> = ({context, action}) => {\n const isActive = isDecoratorActive({\n editor: action.editor,\n decorator: action.decorator,\n })\n\n if (isActive) {\n removeDecoratorActionImplementation({\n context,\n action: {\n type: 'decorator.remove',\n editor: action.editor,\n decorator: action.decorator,\n },\n })\n } else {\n addDecoratorActionImplementation({\n context,\n action: {\n type: 'decorator.add',\n editor: action.editor,\n decorator: action.decorator,\n },\n })\n }\n}\n","import {\n isPortableTextSpan,\n type Path,\n type PortableTextBlock,\n type PortableTextChild,\n type PortableTextObject,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport {\n Editor,\n Node,\n Range,\n Element as SlateElement,\n Path as SlatePath,\n Text,\n Transforms,\n} from 'slate'\nimport type {DOMNode} from 'slate-dom'\nimport {ReactEditor} from 'slate-react'\nimport type {\n EditableAPI,\n EditableAPIDeleteOptions,\n EditorSelection,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toPortableTextRange, toSlateRange} from '../../utils/ranges'\nimport {\n fromSlateValue,\n isEqualToEmptyEditor,\n toSlateValue,\n} from '../../utils/values'\nimport {\n KEY_TO_VALUE_ELEMENT,\n SLATE_TO_PORTABLE_TEXT_RANGE,\n} from '../../utils/weakMaps'\nimport type {EditorActor} from '../editor-machine'\nimport type {PortableTextEditor} from '../PortableTextEditor'\nimport {isDecoratorActive} from './createWithPortableTextMarkModel'\n\nconst debug = debugWithName('API:editable')\n\nexport function createWithEditableAPI(\n editorActor: EditorActor,\n portableTextEditor: PortableTextEditor,\n types: PortableTextMemberSchemaTypes,\n) {\n return function withEditableAPI(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n portableTextEditor.setEditable({\n focus: (): void => {\n ReactEditor.focus(editor)\n },\n blur: (): void => {\n ReactEditor.blur(editor)\n },\n toggleMark: (mark: string): void => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.toggle',\n decorator: mark,\n },\n editor,\n })\n },\n toggleList: (listStyle: string): void => {\n editor.pteToggleListItem(listStyle)\n },\n toggleBlockStyle: (blockStyle: string): void => {\n editor.pteToggleBlockStyle(blockStyle)\n },\n isMarkActive: (mark: string): boolean => {\n // Try/catch this, as Slate may error because the selection is currently wrong\n // TODO: catch only relevant error from Slate\n try {\n return isDecoratorActive({editor, decorator: mark})\n } catch (err) {\n console.warn(err)\n return false\n }\n },\n marks: (): string[] => {\n return (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n )\n },\n undo: (): void => editor.undo(),\n redo: (): void => editor.redo(),\n select: (selection: EditorSelection): void => {\n const slateSelection = toSlateRange(selection, editor)\n if (slateSelection) {\n Transforms.select(editor, slateSelection)\n } else {\n Transforms.deselect(editor)\n }\n editor.onChange()\n },\n focusBlock: (): PortableTextBlock | undefined => {\n if (editor.selection) {\n const block = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n )\n if (block) {\n return fromSlateValue(\n [block],\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0]\n }\n }\n return undefined\n },\n focusChild: (): PortableTextChild | undefined => {\n if (editor.selection) {\n const block = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n )\n if (block && editor.isTextBlock(block)) {\n const ptBlock = fromSlateValue(\n [block],\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0] as PortableTextTextBlock\n return ptBlock.children[editor.selection.focus.path[1]]\n }\n }\n return undefined\n },\n insertChild: <TSchemaType extends {name: string}>(\n type: TSchemaType,\n value?: {[prop: string]: any},\n ): Path => {\n if (!editor.selection) {\n throw new Error('The editor has no selection')\n }\n const [focusBlock] = Array.from(\n Editor.nodes(editor, {\n at: editor.selection.focus.path.slice(0, 1),\n match: (n) => n._type === types.block.name,\n }),\n )[0] || [undefined]\n if (!focusBlock) {\n throw new Error('No focused text block')\n }\n if (\n type.name !== types.span.name &&\n !types.inlineObjects.some((t) => t.name === type.name)\n ) {\n throw new Error(\n 'This type cannot be inserted as a child to a text block',\n )\n }\n const block = toSlateValue(\n [\n {\n _key: editorActor.getSnapshot().context.keyGenerator(),\n _type: types.block.name,\n children: [\n {\n _key: editorActor.getSnapshot().context.keyGenerator(),\n _type: type.name,\n ...(value ? value : {}),\n },\n ],\n },\n ],\n portableTextEditor,\n )[0] as unknown as SlateElement\n const child = block.children[0]\n const focusChildPath = editor.selection.focus.path.slice(0, 2)\n const isSpanNode = child._type === types.span.name\n const focusNode = Node.get(editor, focusChildPath)\n\n // If we are inserting a span, and currently have focus on an inline object,\n // move the selection to the next span (guaranteed by normalizing rules) before inserting it.\n if (isSpanNode && focusNode._type !== types.span.name) {\n debug(\n 'Inserting span child next to inline object child, moving selection + 1',\n )\n editor.move({distance: 1, unit: 'character'})\n }\n\n Transforms.insertNodes(editor, child, {\n select: true,\n at: editor.selection,\n })\n editor.onChange()\n return (\n toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )?.focus.path || []\n )\n },\n insertBlock: <TSchemaType extends {name: string}>(\n type: TSchemaType,\n value?: {[prop: string]: any},\n ): Path => {\n const block = toSlateValue(\n [\n {\n _key: editorActor.getSnapshot().context.keyGenerator(),\n _type: type.name,\n ...(value ? value : {}),\n },\n ],\n portableTextEditor,\n )[0] as unknown as Node\n\n if (!editor.selection) {\n const lastBlock = Array.from(\n Editor.nodes(editor, {\n match: (n) => !Editor.isEditor(n),\n at: [],\n reverse: true,\n }),\n )[0]\n\n // If there is no selection, let's just insert the new block at the\n // end of the document\n Editor.insertNode(editor, block)\n\n if (lastBlock && isEqualToEmptyEditor([lastBlock[0]], types)) {\n // And if the last block was an empty text block, let's remove\n // that too\n Transforms.removeNodes(editor, {at: lastBlock[1]})\n }\n\n editor.onChange()\n\n return (\n toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )?.focus.path ?? []\n )\n }\n\n const focusBlock = Array.from(\n Editor.nodes(editor, {\n at: editor.selection.focus.path.slice(0, 1),\n match: (n) => n._type === types.block.name,\n }),\n )[0]\n\n Editor.insertNode(editor, block)\n\n if (focusBlock && isEqualToEmptyEditor([focusBlock[0]], types)) {\n Transforms.removeNodes(editor, {at: focusBlock[1]})\n }\n\n editor.onChange()\n\n return (\n toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )?.focus.path || []\n )\n },\n hasBlockStyle: (style: string): boolean => {\n try {\n return editor.pteHasBlockStyle(style)\n } catch {\n // This is fine.\n return false\n }\n },\n hasListStyle: (listStyle: string): boolean => {\n try {\n return editor.pteHasListStyle(listStyle)\n } catch {\n // This is fine.\n return false\n }\n },\n isVoid: (element: PortableTextBlock | PortableTextChild) => {\n return ![types.block.name, types.span.name].includes(element._type)\n },\n findByPath: (\n path: Path,\n ): [\n PortableTextBlock | PortableTextChild | undefined,\n Path | undefined,\n ] => {\n const slatePath = toSlateRange(\n {focus: {path, offset: 0}, anchor: {path, offset: 0}},\n editor,\n )\n if (slatePath) {\n const [block, blockPath] = Editor.node(\n editor,\n slatePath.focus.path.slice(0, 1),\n )\n if (block && blockPath && typeof block._key === 'string') {\n if (path.length === 1 && slatePath.focus.path.length === 1) {\n return [\n fromSlateValue([block], types.block.name)[0],\n [{_key: block._key}],\n ]\n }\n const ptBlock = fromSlateValue(\n [block],\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0]\n if (editor.isTextBlock(ptBlock)) {\n const ptChild = ptBlock.children[slatePath.focus.path[1]]\n if (ptChild) {\n return [\n ptChild,\n [{_key: block._key}, 'children', {_key: ptChild._key}],\n ]\n }\n }\n }\n }\n return [undefined, undefined]\n },\n findDOMNode: (\n element: PortableTextBlock | PortableTextChild,\n ): DOMNode | undefined => {\n let node: DOMNode | undefined\n try {\n const [item] = Array.from(\n Editor.nodes(editor, {\n at: [],\n match: (n) => n._key === element._key,\n }) || [],\n )[0] || [undefined]\n node = ReactEditor.toDOMNode(editor, item)\n } catch {\n // Nothing\n }\n return node\n },\n activeAnnotations: (): PortableTextObject[] => {\n if (!editor.selection || editor.selection.focus.path.length < 2) {\n return []\n }\n try {\n const activeAnnotations: PortableTextObject[] = []\n const spans = Editor.nodes(editor, {\n at: editor.selection,\n match: (node) =>\n Text.isText(node) &&\n node.marks !== undefined &&\n Array.isArray(node.marks) &&\n node.marks.length > 0,\n })\n for (const [span, path] of spans) {\n const [block] = Editor.node(editor, path, {depth: 1})\n if (editor.isTextBlock(block)) {\n block.markDefs?.forEach((def) => {\n if (\n Text.isText(span) &&\n span.marks &&\n Array.isArray(span.marks) &&\n span.marks.includes(def._key)\n ) {\n activeAnnotations.push(def)\n }\n })\n }\n }\n return activeAnnotations\n } catch {\n return []\n }\n },\n isAnnotationActive: (\n annotationType: PortableTextObject['_type'],\n ): boolean => {\n if (!editor.selection || editor.selection.focus.path.length < 2) {\n return false\n }\n\n try {\n const spans = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => Text.isText(node),\n }),\n ]\n\n if (spans.length === 0) {\n return false\n }\n\n if (\n spans.some(\n ([span]) =>\n !isPortableTextSpan(span) ||\n !span.marks ||\n span.marks?.length === 0,\n )\n )\n return false\n\n const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {\n const [block] = Editor.node(editor, path, {depth: 1})\n if (editor.isTextBlock(block) && block.markDefs) {\n return [...accMarkDefs, ...block.markDefs]\n }\n return accMarkDefs\n }, [] as PortableTextObject[])\n\n return spans.every(([span]) => {\n if (!isPortableTextSpan(span)) return false\n\n const spanMarkDefs = span.marks?.map(\n (markKey) =>\n selectionMarkDefs.find((def) => def?._key === markKey)?._type,\n )\n\n return spanMarkDefs?.includes(annotationType)\n })\n } catch {\n return false\n }\n },\n addAnnotation: (type, value) => {\n const {selection: originalSelection} = editor\n let returnValue: ReturnType<EditableAPI['addAnnotation']> | undefined =\n undefined\n\n if (originalSelection) {\n if (Range.isCollapsed(originalSelection)) {\n editor.pteExpandToWord()\n editor.onChange()\n }\n\n // If we still have a selection, add the annotation to the selected text\n if (editor.selection) {\n let spanPath: Path | undefined\n let markDefPath: Path | undefined\n const markDefPaths: Path[] = []\n\n Editor.withoutNormalizing(editor, () => {\n if (!editor.selection) {\n return\n }\n\n const selectedBlocks = Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n reverse: Range.isBackward(editor.selection),\n })\n\n for (const [block, blockPath] of selectedBlocks) {\n if (block.children.length === 0) {\n continue\n }\n\n if (\n block.children.length === 1 &&\n block.children[0].text === ''\n ) {\n continue\n }\n\n const annotationKey = editorActor\n .getSnapshot()\n .context.keyGenerator()\n const markDefs = block.markDefs ?? []\n const existingMarkDef = markDefs.find(\n (markDef) =>\n markDef._type === type.name &&\n markDef._key === annotationKey,\n )\n\n if (existingMarkDef === undefined) {\n Transforms.setNodes(\n editor,\n {\n markDefs: [\n ...markDefs,\n {\n _type: type.name,\n _key: annotationKey,\n ...value,\n },\n ],\n },\n {at: blockPath},\n )\n\n markDefPath = [\n {_key: block._key},\n 'markDefs',\n {_key: annotationKey},\n ]\n if (Range.isBackward(editor.selection)) {\n markDefPaths.unshift(markDefPath)\n } else {\n markDefPaths.push(markDefPath)\n }\n }\n\n Transforms.setNodes(\n editor,\n {},\n {match: Text.isText, split: true},\n )\n\n const children = Node.children(editor, blockPath)\n\n for (const [span, path] of children) {\n if (!editor.isTextSpan(span)) {\n continue\n }\n\n if (!Range.includes(editor.selection, path)) {\n continue\n }\n\n const marks = span.marks ?? []\n const existingSameTypeAnnotations = marks.filter((mark) =>\n markDefs.some(\n (markDef) =>\n markDef._key === mark && markDef._type === type.name,\n ),\n )\n\n Transforms.setNodes(\n editor,\n {\n marks: [\n ...marks.filter(\n (mark) => !existingSameTypeAnnotations.includes(mark),\n ),\n annotationKey,\n ],\n },\n {at: path},\n )\n spanPath = [{_key: block._key}, 'children', {_key: span._key}]\n }\n }\n\n if (markDefPath && spanPath) {\n returnValue = {\n markDefPath,\n markDefPaths,\n spanPath,\n }\n }\n })\n editor.onChange()\n }\n }\n return returnValue\n },\n delete: (\n selection: EditorSelection,\n options?: EditableAPIDeleteOptions,\n ): void => {\n if (selection) {\n const range = toSlateRange(selection, editor)\n const hasRange =\n range && range.anchor.path.length > 0 && range.focus.path.length > 0\n if (!hasRange) {\n throw new Error('Invalid range')\n }\n if (range) {\n if (!options?.mode || options?.mode === 'selected') {\n debug(`Deleting content in selection`)\n Transforms.delete(editor, {\n at: range,\n hanging: true,\n voids: true,\n })\n editor.onChange()\n return\n }\n if (options?.mode === 'blocks') {\n debug(`Deleting blocks touched by selection`)\n Transforms.removeNodes(editor, {\n at: range,\n voids: true,\n match: (node) => {\n return (\n editor.isTextBlock(node) ||\n (!editor.isTextBlock(node) && SlateElement.isElement(node))\n )\n },\n })\n }\n if (options?.mode === 'children') {\n debug(`Deleting children touched by selection`)\n Transforms.removeNodes(editor, {\n at: range,\n voids: true,\n match: (node) => {\n return (\n node._type === types.span.name || // Text children\n (!editor.isTextBlock(node) && SlateElement.isElement(node)) // inline blocks\n )\n },\n })\n }\n // If the editor was emptied, insert a placeholder block\n // directly into the editor's children. We don't want to do this\n // through a Transform (because that would trigger a change event\n // that would insert the placeholder into the actual value\n // which should remain empty)\n if (editor.children.length === 0) {\n editor.children = [editor.pteCreateTextBlock({decorators: []})]\n }\n editor.onChange()\n }\n }\n },\n removeAnnotation: <TSchemaType extends {name: string}>(\n type: TSchemaType,\n ): void => {\n debug('Removing annotation', type)\n\n Editor.withoutNormalizing(editor, () => {\n if (!editor.selection) {\n return\n }\n\n if (Range.isCollapsed(editor.selection)) {\n const [block, blockPath] = Editor.node(editor, editor.selection, {\n depth: 1,\n })\n\n if (!editor.isTextBlock(block)) {\n return\n }\n\n const markDefs = block.markDefs ?? []\n const potentialAnnotations = markDefs.filter(\n (markDef) => markDef._type === type.name,\n )\n\n const [selectedChild, selectedChildPath] = Editor.node(\n editor,\n editor.selection,\n {\n depth: 2,\n },\n )\n\n if (!editor.isTextSpan(selectedChild)) {\n return\n }\n\n const annotationToRemove = selectedChild.marks?.find((mark) =>\n potentialAnnotations.some((markDef) => markDef._key === mark),\n )\n\n if (!annotationToRemove) {\n return\n }\n\n const previousSpansWithSameAnnotation: Array<\n [span: PortableTextSpan, path: SlatePath]\n > = []\n\n for (const [child, childPath] of Node.children(editor, blockPath, {\n reverse: true,\n })) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (!SlatePath.isBefore(childPath, selectedChildPath)) {\n continue\n }\n\n if (child.marks?.includes(annotationToRemove)) {\n previousSpansWithSameAnnotation.push([child, childPath])\n } else {\n break\n }\n }\n\n const nextSpansWithSameAnnotation: Array<\n [span: PortableTextSpan, path: SlatePath]\n > = []\n\n for (const [child, childPath] of Node.children(editor, blockPath)) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (!SlatePath.isAfter(childPath, selectedChildPath)) {\n continue\n }\n\n if (child.marks?.includes(annotationToRemove)) {\n nextSpansWithSameAnnotation.push([child, childPath])\n } else {\n break\n }\n }\n\n for (const [child, childPath] of [\n ...previousSpansWithSameAnnotation,\n [selectedChild, selectedChildPath] as const,\n ...nextSpansWithSameAnnotation,\n ]) {\n Transforms.setNodes(\n editor,\n {\n marks: child.marks?.filter(\n (mark) => mark !== annotationToRemove,\n ),\n },\n {at: childPath},\n )\n }\n } else {\n Transforms.setNodes(\n editor,\n {},\n {\n match: (node) => editor.isTextSpan(node),\n split: true,\n hanging: true,\n },\n )\n\n const blocks = Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n })\n\n for (const [block, blockPath] of blocks) {\n const children = Node.children(editor, blockPath)\n\n for (const [child, childPath] of children) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (!Range.includes(editor.selection, childPath)) {\n continue\n }\n\n const markDefs = block.markDefs ?? []\n const marks = child.marks ?? []\n const marksWithoutAnnotation = marks.filter((mark) => {\n const markDef = markDefs.find(\n (markDef) => markDef._key === mark,\n )\n return markDef?._type !== type.name\n })\n\n if (marksWithoutAnnotation.length !== marks.length) {\n Transforms.setNodes(\n editor,\n {\n marks: marksWithoutAnnotation,\n },\n {at: childPath},\n )\n }\n }\n }\n }\n })\n editor.onChange()\n },\n getSelection: (): EditorSelection | null => {\n let ptRange: EditorSelection = null\n if (editor.selection) {\n const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection)\n if (existing) {\n return existing\n }\n ptRange = toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )\n SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange)\n }\n return ptRange\n },\n getValue: () => {\n return fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )\n },\n isCollapsedSelection: () => {\n return !!editor.selection && Range.isCollapsed(editor.selection)\n },\n isExpandedSelection: () => {\n return !!editor.selection && Range.isExpanded(editor.selection)\n },\n insertBreak: () => {\n editor.insertBreak()\n editor.onChange()\n },\n getFragment: () => {\n return fromSlateValue(editor.getFragment(), types.block.name)\n },\n isSelectionsOverlapping: (\n selectionA: EditorSelection,\n selectionB: EditorSelection,\n ) => {\n // Convert the selections to Slate ranges\n const rangeA = toSlateRange(selectionA, editor)\n const rangeB = toSlateRange(selectionB, editor)\n\n // Make sure the ranges are valid\n const isValidRanges = Range.isRange(rangeA) && Range.isRange(rangeB)\n\n // Check if the ranges are overlapping\n const isOverlapping = isValidRanges && Range.includes(rangeA, rangeB)\n\n return isOverlapping\n },\n })\n return editor\n }\n}\n","import type {PortableTextSlateEditor} from '../../types/editor'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\n\n/**\n * This plugin makes sure that the PTE maxBlocks prop is respected\n *\n */\nexport function createWithMaxBlocks(maxBlocks: number) {\n return function withMaxBlocks(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {apply} = editor\n editor.apply = (operation) => {\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(operation)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(operation)\n return\n }\n\n const rows = maxBlocks\n if (rows > 0 && editor.children.length >= rows) {\n if (\n (operation.type === 'insert_node' ||\n operation.type === 'split_node') &&\n operation.path.length === 1\n ) {\n return\n }\n }\n apply(operation)\n }\n return editor\n }\n}\n","import {Editor, Element, Node, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\n/**\n * This plugin makes sure that every new node in the editor get a new _key prop when created\n *\n */\nexport function createWithObjectKeys(\n editorActor: EditorActor,\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n return function withKeys(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {apply, normalizeNode} = editor\n\n // The default behavior is to always generate a new key here.\n // For example, when undoing and redoing we want to retain the keys, but\n // when we create a new bold span by splitting a non-bold-span we want the produced node to get a new key.\n editor.apply = (operation) => {\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(operation)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(operation)\n return\n }\n\n if (operation.type === 'split_node') {\n apply({\n ...operation,\n properties: {\n ...operation.properties,\n _key: editorActor.getSnapshot().context.keyGenerator(),\n },\n })\n\n return\n }\n\n if (operation.type === 'insert_node') {\n if (!Editor.isEditor(operation.node)) {\n apply({\n ...operation,\n node: {\n ...operation.node,\n _key: editorActor.getSnapshot().context.keyGenerator(),\n },\n })\n\n return\n }\n }\n\n apply(operation)\n }\n\n editor.normalizeNode = (entry) => {\n const [node, path] = entry\n if (Element.isElement(node) && node._type === schemaTypes.block.name) {\n // Set key on block itself\n if (!node._key) {\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {_key: editorActor.getSnapshot().context.keyGenerator()},\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n // Set keys on it's children\n for (const [child, childPath] of Node.children(editor, path)) {\n if (!child._key) {\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {_key: editorActor.getSnapshot().context.keyGenerator()},\n {at: childPath},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n normalizeNode(entry)\n }\n\n return editor\n }\n}\n","function isHighSurrogate(char) {\n const charCode = char.charCodeAt(0);\n return charCode >= 55296 && charCode <= 56319;\n}\nfunction isLowSurrogate(char) {\n const charCode = char.charCodeAt(0);\n return charCode >= 56320 && charCode <= 57343;\n}\nfunction cloneDiff(diff) {\n const [type, patch] = diff;\n return [type, patch];\n}\nfunction getCommonOverlap(textA, textB) {\n let text1 = textA;\n let text2 = textB;\n const text1Length = text1.length;\n const text2Length = text2.length;\n if (text1Length === 0 || text2Length === 0) {\n return 0;\n }\n if (text1Length > text2Length) {\n text1 = text1.substring(text1Length - text2Length);\n } else if (text1Length < text2Length) {\n text2 = text2.substring(0, text1Length);\n }\n const textLength = Math.min(text1Length, text2Length);\n if (text1 === text2) {\n return textLength;\n }\n let best = 0;\n let length = 1;\n for (let found = 0; found !== -1;) {\n const pattern = text1.substring(textLength - length);\n found = text2.indexOf(pattern);\n if (found === -1) {\n return best;\n }\n length += found;\n if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {\n best = length;\n length++;\n }\n }\n return best;\n}\nfunction getCommonPrefix(text1, text2) {\n if (!text1 || !text2 || text1[0] !== text2[0]) {\n return 0;\n }\n let pointerMin = 0;\n let pointerMax = Math.min(text1.length, text2.length);\n let pointerMid = pointerMax;\n let pointerStart = 0;\n while (pointerMin < pointerMid) {\n if (text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid)) {\n pointerMin = pointerMid;\n pointerStart = pointerMin;\n } else {\n pointerMax = pointerMid;\n }\n pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);\n }\n return pointerMid;\n}\nfunction getCommonSuffix(text1, text2) {\n if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1]) {\n return 0;\n }\n let pointerMin = 0;\n let pointerMax = Math.min(text1.length, text2.length);\n let pointerMid = pointerMax;\n let pointerEnd = 0;\n while (pointerMin < pointerMid) {\n if (text1.substring(text1.length - pointerMid, text1.length - pointerEnd) === text2.substring(text2.length - pointerMid, text2.length - pointerEnd)) {\n pointerMin = pointerMid;\n pointerEnd = pointerMin;\n } else {\n pointerMax = pointerMid;\n }\n pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);\n }\n return pointerMid;\n}\nfunction cleanupSemantic(rawDiffs) {\n let diffs = rawDiffs.map(diff => cloneDiff(diff));\n let hasChanges = false;\n const equalities = [];\n let equalitiesLength = 0;\n let lastEquality = null;\n let pointer = 0;\n let lengthInsertions1 = 0;\n let lengthDeletions1 = 0;\n let lengthInsertions2 = 0;\n let lengthDeletions2 = 0;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] === DIFF_EQUAL) {\n equalities[equalitiesLength++] = pointer;\n lengthInsertions1 = lengthInsertions2;\n lengthDeletions1 = lengthDeletions2;\n lengthInsertions2 = 0;\n lengthDeletions2 = 0;\n lastEquality = diffs[pointer][1];\n } else {\n if (diffs[pointer][0] === DIFF_INSERT) {\n lengthInsertions2 += diffs[pointer][1].length;\n } else {\n lengthDeletions2 += diffs[pointer][1].length;\n }\n if (lastEquality && lastEquality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastEquality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {\n diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]);\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n equalitiesLength--;\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n lengthInsertions1 = 0;\n lengthDeletions1 = 0;\n lengthInsertions2 = 0;\n lengthDeletions2 = 0;\n lastEquality = null;\n hasChanges = true;\n }\n }\n pointer++;\n }\n if (hasChanges) {\n diffs = cleanupMerge(diffs);\n }\n diffs = cleanupSemanticLossless(diffs);\n pointer = 1;\n while (pointer < diffs.length) {\n if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {\n const deletion = diffs[pointer - 1][1];\n const insertion = diffs[pointer][1];\n const overlapLength1 = getCommonOverlap(deletion, insertion);\n const overlapLength2 = getCommonOverlap(insertion, deletion);\n if (overlapLength1 >= overlapLength2) {\n if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {\n diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);\n diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);\n diffs[pointer + 1][1] = insertion.substring(overlapLength1);\n pointer++;\n }\n } else if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {\n diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);\n diffs[pointer - 1][0] = DIFF_INSERT;\n diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);\n diffs[pointer + 1][0] = DIFF_DELETE;\n diffs[pointer + 1][1] = deletion.substring(overlapLength2);\n pointer++;\n }\n pointer++;\n }\n pointer++;\n }\n return diffs;\n}\nconst nonAlphaNumericRegex = /[^a-zA-Z0-9]/;\nconst whitespaceRegex = /\\s/;\nconst linebreakRegex = /[\\r\\n]/;\nconst blanklineEndRegex = /\\n\\r?\\n$/;\nconst blanklineStartRegex = /^\\r?\\n\\r?\\n/;\nfunction cleanupSemanticLossless(rawDiffs) {\n const diffs = rawDiffs.map(diff => cloneDiff(diff));\n function diffCleanupSemanticScore(one, two) {\n if (!one || !two) {\n return 6;\n }\n const char1 = one.charAt(one.length - 1);\n const char2 = two.charAt(0);\n const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex);\n const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex);\n const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex);\n const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex);\n const lineBreak1 = whitespace1 && char1.match(linebreakRegex);\n const lineBreak2 = whitespace2 && char2.match(linebreakRegex);\n const blankLine1 = lineBreak1 && one.match(blanklineEndRegex);\n const blankLine2 = lineBreak2 && two.match(blanklineStartRegex);\n if (blankLine1 || blankLine2) {\n return 5;\n } else if (lineBreak1 || lineBreak2) {\n return 4;\n } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n return 3;\n } else if (whitespace1 || whitespace2) {\n return 2;\n } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n return 1;\n }\n return 0;\n }\n let pointer = 1;\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {\n let equality1 = diffs[pointer - 1][1];\n let edit = diffs[pointer][1];\n let equality2 = diffs[pointer + 1][1];\n const commonOffset = getCommonSuffix(equality1, edit);\n if (commonOffset) {\n const commonString = edit.substring(edit.length - commonOffset);\n equality1 = equality1.substring(0, equality1.length - commonOffset);\n edit = commonString + edit.substring(0, edit.length - commonOffset);\n equality2 = commonString + equality2;\n }\n let bestEquality1 = equality1;\n let bestEdit = edit;\n let bestEquality2 = equality2;\n let bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);\n while (edit.charAt(0) === equality2.charAt(0)) {\n equality1 += edit.charAt(0);\n edit = edit.substring(1) + equality2.charAt(0);\n equality2 = equality2.substring(1);\n const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);\n if (score >= bestScore) {\n bestScore = score;\n bestEquality1 = equality1;\n bestEdit = edit;\n bestEquality2 = equality2;\n }\n }\n if (diffs[pointer - 1][1] !== bestEquality1) {\n if (bestEquality1) {\n diffs[pointer - 1][1] = bestEquality1;\n } else {\n diffs.splice(pointer - 1, 1);\n pointer--;\n }\n diffs[pointer][1] = bestEdit;\n if (bestEquality2) {\n diffs[pointer + 1][1] = bestEquality2;\n } else {\n diffs.splice(pointer + 1, 1);\n pointer--;\n }\n }\n }\n pointer++;\n }\n return diffs;\n}\nfunction cleanupMerge(rawDiffs) {\n let diffs = rawDiffs.map(diff => cloneDiff(diff));\n diffs.push([DIFF_EQUAL, \"\"]);\n let pointer = 0;\n let countDelete = 0;\n let countInsert = 0;\n let textDelete = \"\";\n let textInsert = \"\";\n let commonlength;\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n countInsert++;\n textInsert += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_DELETE:\n countDelete++;\n textDelete += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_EQUAL:\n if (countDelete + countInsert > 1) {\n if (countDelete !== 0 && countInsert !== 0) {\n commonlength = getCommonPrefix(textInsert, textDelete);\n if (commonlength !== 0) {\n if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {\n diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);\n } else {\n diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);\n pointer++;\n }\n textInsert = textInsert.substring(commonlength);\n textDelete = textDelete.substring(commonlength);\n }\n commonlength = getCommonSuffix(textInsert, textDelete);\n if (commonlength !== 0) {\n diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];\n textInsert = textInsert.substring(0, textInsert.length - commonlength);\n textDelete = textDelete.substring(0, textDelete.length - commonlength);\n }\n }\n pointer -= countDelete + countInsert;\n diffs.splice(pointer, countDelete + countInsert);\n if (textDelete.length) {\n diffs.splice(pointer, 0, [DIFF_DELETE, textDelete]);\n pointer++;\n }\n if (textInsert.length) {\n diffs.splice(pointer, 0, [DIFF_INSERT, textInsert]);\n pointer++;\n }\n pointer++;\n } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {\n diffs[pointer - 1][1] += diffs[pointer][1];\n diffs.splice(pointer, 1);\n } else {\n pointer++;\n }\n countInsert = 0;\n countDelete = 0;\n textDelete = \"\";\n textInsert = \"\";\n break;\n default:\n throw new Error(\"Unknown diff operation\");\n }\n }\n if (diffs[diffs.length - 1][1] === \"\") {\n diffs.pop();\n }\n let hasChanges = false;\n pointer = 1;\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {\n if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) {\n diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);\n diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n diffs.splice(pointer - 1, 1);\n hasChanges = true;\n } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {\n diffs[pointer - 1][1] += diffs[pointer + 1][1];\n diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];\n diffs.splice(pointer + 1, 1);\n hasChanges = true;\n }\n }\n pointer++;\n }\n if (hasChanges) {\n diffs = cleanupMerge(diffs);\n }\n return diffs;\n}\nfunction trueCount() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return args.reduce((n, bool) => n + (bool ? 1 : 0), 0);\n}\nfunction cleanupEfficiency(rawDiffs) {\n let editCost = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;\n let diffs = rawDiffs.map(diff => cloneDiff(diff));\n let hasChanges = false;\n const equalities = [];\n let equalitiesLength = 0;\n let lastEquality = null;\n let pointer = 0;\n let preIns = false;\n let preDel = false;\n let postIns = false;\n let postDel = false;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] === DIFF_EQUAL) {\n if (diffs[pointer][1].length < editCost && (postIns || postDel)) {\n equalities[equalitiesLength++] = pointer;\n preIns = postIns;\n preDel = postDel;\n lastEquality = diffs[pointer][1];\n } else {\n equalitiesLength = 0;\n lastEquality = null;\n }\n postIns = false;\n postDel = false;\n } else {\n if (diffs[pointer][0] === DIFF_DELETE) {\n postDel = true;\n } else {\n postIns = true;\n }\n if (lastEquality && (preIns && preDel && postIns && postDel || lastEquality.length < editCost / 2 && trueCount(preIns, preDel, postIns, postDel) === 3)) {\n diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]);\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n equalitiesLength--;\n lastEquality = null;\n if (preIns && preDel) {\n postIns = true;\n postDel = true;\n equalitiesLength = 0;\n } else {\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n postIns = false;\n postDel = false;\n }\n hasChanges = true;\n }\n }\n pointer++;\n }\n if (hasChanges) {\n diffs = cleanupMerge(diffs);\n }\n return diffs;\n}\nfunction bisect(text1, text2, deadline) {\n const text1Length = text1.length;\n const text2Length = text2.length;\n const maxD = Math.ceil((text1Length + text2Length) / 2);\n const vOffset = maxD;\n const vLength = 2 * maxD;\n const v1 = new Array(vLength);\n const v2 = new Array(vLength);\n for (let x = 0; x < vLength; x++) {\n v1[x] = -1;\n v2[x] = -1;\n }\n v1[vOffset + 1] = 0;\n v2[vOffset + 1] = 0;\n const delta = text1Length - text2Length;\n const front = delta % 2 !== 0;\n let k1start = 0;\n let k1end = 0;\n let k2start = 0;\n let k2end = 0;\n for (let d = 0; d < maxD; d++) {\n if (Date.now() > deadline) {\n break;\n }\n for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n const k1Offset = vOffset + k1;\n let x1;\n if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {\n x1 = v1[k1Offset + 1];\n } else {\n x1 = v1[k1Offset - 1] + 1;\n }\n let y1 = x1 - k1;\n while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {\n x1++;\n y1++;\n }\n v1[k1Offset] = x1;\n if (x1 > text1Length) {\n k1end += 2;\n } else if (y1 > text2Length) {\n k1start += 2;\n } else if (front) {\n const k2Offset = vOffset + delta - k1;\n if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {\n const x2 = text1Length - v2[k2Offset];\n if (x1 >= x2) {\n return bisectSplit(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n const k2Offset = vOffset + k2;\n let x2;\n if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {\n x2 = v2[k2Offset + 1];\n } else {\n x2 = v2[k2Offset - 1] + 1;\n }\n let y2 = x2 - k2;\n while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {\n x2++;\n y2++;\n }\n v2[k2Offset] = x2;\n if (x2 > text1Length) {\n k2end += 2;\n } else if (y2 > text2Length) {\n k2start += 2;\n } else if (!front) {\n const k1Offset = vOffset + delta - k2;\n if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {\n const x1 = v1[k1Offset];\n const y1 = vOffset + x1 - k1Offset;\n x2 = text1Length - x2;\n if (x1 >= x2) {\n return bisectSplit(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n }\n return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];\n}\nfunction bisectSplit(text1, text2, x, y, deadline) {\n const text1a = text1.substring(0, x);\n const text2a = text2.substring(0, y);\n const text1b = text1.substring(x);\n const text2b = text2.substring(y);\n const diffs = doDiff(text1a, text2a, {\n checkLines: false,\n deadline\n });\n const diffsb = doDiff(text1b, text2b, {\n checkLines: false,\n deadline\n });\n return diffs.concat(diffsb);\n}\nfunction findHalfMatch(text1, text2) {\n let timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n if (timeout <= 0) {\n return null;\n }\n const longText = text1.length > text2.length ? text1 : text2;\n const shortText = text1.length > text2.length ? text2 : text1;\n if (longText.length < 4 || shortText.length * 2 < longText.length) {\n return null;\n }\n const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4));\n const halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));\n let halfMatch;\n if (halfMatch1 && halfMatch2) {\n halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;\n } else if (!halfMatch1 && !halfMatch2) {\n return null;\n } else if (!halfMatch2) {\n halfMatch = halfMatch1;\n } else if (!halfMatch1) {\n halfMatch = halfMatch2;\n }\n if (!halfMatch) {\n throw new Error(\"Unable to find a half match.\");\n }\n let text1A;\n let text1B;\n let text2A;\n let text2B;\n if (text1.length > text2.length) {\n text1A = halfMatch[0];\n text1B = halfMatch[1];\n text2A = halfMatch[2];\n text2B = halfMatch[3];\n } else {\n text2A = halfMatch[0];\n text2B = halfMatch[1];\n text1A = halfMatch[2];\n text1B = halfMatch[3];\n }\n const midCommon = halfMatch[4];\n return [text1A, text1B, text2A, text2B, midCommon];\n}\nfunction halfMatchI(longText, shortText, i) {\n const seed = longText.slice(i, i + Math.floor(longText.length / 4));\n let j = -1;\n let bestCommon = \"\";\n let bestLongTextA;\n let bestLongTextB;\n let bestShortTextA;\n let bestShortTextB;\n while ((j = shortText.indexOf(seed, j + 1)) !== -1) {\n const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j));\n const suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));\n if (bestCommon.length < suffixLength + prefixLength) {\n bestCommon = shortText.slice(j - suffixLength, j) + shortText.slice(j, j + prefixLength);\n bestLongTextA = longText.slice(0, i - suffixLength);\n bestLongTextB = longText.slice(i + prefixLength);\n bestShortTextA = shortText.slice(0, j - suffixLength);\n bestShortTextB = shortText.slice(j + prefixLength);\n }\n }\n if (bestCommon.length * 2 >= longText.length) {\n return [bestLongTextA || \"\", bestLongTextB || \"\", bestShortTextA || \"\", bestShortTextB || \"\", bestCommon || \"\"];\n }\n return null;\n}\nfunction charsToLines(diffs, lineArray) {\n for (let x = 0; x < diffs.length; x++) {\n const chars = diffs[x][1];\n const text = [];\n for (let y = 0; y < chars.length; y++) {\n text[y] = lineArray[chars.charCodeAt(y)];\n }\n diffs[x][1] = text.join(\"\");\n }\n}\nfunction linesToChars(textA, textB) {\n const lineArray = [];\n const lineHash = {};\n lineArray[0] = \"\";\n function diffLinesToMunge(text) {\n let chars = \"\";\n let lineStart = 0;\n let lineEnd = -1;\n let lineArrayLength = lineArray.length;\n while (lineEnd < text.length - 1) {\n lineEnd = text.indexOf(\"\\n\", lineStart);\n if (lineEnd === -1) {\n lineEnd = text.length - 1;\n }\n let line = text.slice(lineStart, lineEnd + 1);\n if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) {\n chars += String.fromCharCode(lineHash[line]);\n } else {\n if (lineArrayLength === maxLines) {\n line = text.slice(lineStart);\n lineEnd = text.length;\n }\n chars += String.fromCharCode(lineArrayLength);\n lineHash[line] = lineArrayLength;\n lineArray[lineArrayLength++] = line;\n }\n lineStart = lineEnd + 1;\n }\n return chars;\n }\n let maxLines = 4e4;\n const chars1 = diffLinesToMunge(textA);\n maxLines = 65535;\n const chars2 = diffLinesToMunge(textB);\n return {\n chars1,\n chars2,\n lineArray\n };\n}\nfunction doLineModeDiff(textA, textB, opts) {\n let text1 = textA;\n let text2 = textB;\n const a = linesToChars(text1, text2);\n text1 = a.chars1;\n text2 = a.chars2;\n const linearray = a.lineArray;\n let diffs = doDiff(text1, text2, {\n checkLines: false,\n deadline: opts.deadline\n });\n charsToLines(diffs, linearray);\n diffs = cleanupSemantic(diffs);\n diffs.push([DIFF_EQUAL, \"\"]);\n let pointer = 0;\n let countDelete = 0;\n let countInsert = 0;\n let textDelete = \"\";\n let textInsert = \"\";\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n countInsert++;\n textInsert += diffs[pointer][1];\n break;\n case DIFF_DELETE:\n countDelete++;\n textDelete += diffs[pointer][1];\n break;\n case DIFF_EQUAL:\n if (countDelete >= 1 && countInsert >= 1) {\n diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);\n pointer = pointer - countDelete - countInsert;\n const aa = doDiff(textDelete, textInsert, {\n checkLines: false,\n deadline: opts.deadline\n });\n for (let j = aa.length - 1; j >= 0; j--) {\n diffs.splice(pointer, 0, aa[j]);\n }\n pointer += aa.length;\n }\n countInsert = 0;\n countDelete = 0;\n textDelete = \"\";\n textInsert = \"\";\n break;\n default:\n throw new Error(\"Unknown diff operation.\");\n }\n pointer++;\n }\n diffs.pop();\n return diffs;\n}\nfunction computeDiff(text1, text2, opts) {\n let diffs;\n if (!text1) {\n return [[DIFF_INSERT, text2]];\n }\n if (!text2) {\n return [[DIFF_DELETE, text1]];\n }\n const longtext = text1.length > text2.length ? text1 : text2;\n const shorttext = text1.length > text2.length ? text2 : text1;\n const i = longtext.indexOf(shorttext);\n if (i !== -1) {\n diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];\n if (text1.length > text2.length) {\n diffs[0][0] = DIFF_DELETE;\n diffs[2][0] = DIFF_DELETE;\n }\n return diffs;\n }\n if (shorttext.length === 1) {\n return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];\n }\n const halfMatch = findHalfMatch(text1, text2);\n if (halfMatch) {\n const text1A = halfMatch[0];\n const text1B = halfMatch[1];\n const text2A = halfMatch[2];\n const text2B = halfMatch[3];\n const midCommon = halfMatch[4];\n const diffsA = doDiff(text1A, text2A, opts);\n const diffsB = doDiff(text1B, text2B, opts);\n return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);\n }\n if (opts.checkLines && text1.length > 100 && text2.length > 100) {\n return doLineModeDiff(text1, text2, opts);\n }\n return bisect(text1, text2, opts.deadline);\n}\nconst DIFF_DELETE = -1;\nconst DIFF_INSERT = 1;\nconst DIFF_EQUAL = 0;\nfunction diff(textA, textB, opts) {\n if (textA === null || textB === null) {\n throw new Error(\"Null input. (diff)\");\n }\n const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));\n adjustDiffForSurrogatePairs(diffs);\n return diffs;\n}\nfunction doDiff(textA, textB, options) {\n let text1 = textA;\n let text2 = textB;\n if (text1 === text2) {\n return text1 ? [[DIFF_EQUAL, text1]] : [];\n }\n let commonlength = getCommonPrefix(text1, text2);\n const commonprefix = text1.substring(0, commonlength);\n text1 = text1.substring(commonlength);\n text2 = text2.substring(commonlength);\n commonlength = getCommonSuffix(text1, text2);\n const commonsuffix = text1.substring(text1.length - commonlength);\n text1 = text1.substring(0, text1.length - commonlength);\n text2 = text2.substring(0, text2.length - commonlength);\n let diffs = computeDiff(text1, text2, options);\n if (commonprefix) {\n diffs.unshift([DIFF_EQUAL, commonprefix]);\n }\n if (commonsuffix) {\n diffs.push([DIFF_EQUAL, commonsuffix]);\n }\n diffs = cleanupMerge(diffs);\n return diffs;\n}\nfunction createDeadLine(timeout) {\n let t = 1;\n if (typeof timeout !== \"undefined\") {\n t = timeout <= 0 ? Number.MAX_VALUE : timeout;\n }\n return Date.now() + t * 1e3;\n}\nfunction createInternalOpts(opts) {\n return {\n checkLines: true,\n deadline: createDeadLine(opts.timeout || 1),\n ...opts\n };\n}\nfunction combineChar(data, char, dir) {\n return dir === 1 ? data + char : char + data;\n}\nfunction splitChar(data, dir) {\n return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];\n}\nfunction hasSharedChar(diffs, i, j, dir) {\n return dir === 1 ? diffs[i][1][diffs[i][1].length - 1] === diffs[j][1][diffs[j][1].length - 1] : diffs[i][1][0] === diffs[j][1][0];\n}\nfunction deisolateChar(diffs, i, dir) {\n const inv = dir === 1 ? -1 : 1;\n let insertIdx = null;\n let deleteIdx = null;\n let j = i + dir;\n for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {\n const [op, text2] = diffs[j];\n if (text2.length === 0) {\n continue;\n }\n if (op === DIFF_INSERT) {\n if (insertIdx === null) {\n insertIdx = j;\n }\n continue;\n } else if (op === DIFF_DELETE) {\n if (deleteIdx === null) {\n deleteIdx = j;\n }\n continue;\n } else if (op === DIFF_EQUAL) {\n if (insertIdx === null && deleteIdx === null) {\n const [rest, char2] = splitChar(diffs[i][1], dir);\n diffs[i][1] = rest;\n diffs[j][1] = combineChar(diffs[j][1], char2, inv);\n return;\n }\n break;\n }\n }\n if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {\n const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv);\n const [deleteText] = splitChar(diffs[deleteIdx][1], inv);\n diffs[insertIdx][1] = insertText;\n diffs[deleteIdx][1] = deleteText;\n diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);\n return;\n }\n const [text, char] = splitChar(diffs[i][1], dir);\n diffs[i][1] = text;\n if (insertIdx === null) {\n diffs.splice(j, 0, [DIFF_INSERT, char]);\n if (deleteIdx !== null && deleteIdx >= j) deleteIdx++;\n } else {\n diffs[insertIdx][1] = combineChar(diffs[insertIdx][1], char, inv);\n }\n if (deleteIdx === null) {\n diffs.splice(j, 0, [DIFF_DELETE, char]);\n } else {\n diffs[deleteIdx][1] = combineChar(diffs[deleteIdx][1], char, inv);\n }\n}\nfunction adjustDiffForSurrogatePairs(diffs) {\n for (let i = 0; i < diffs.length; i++) {\n const [diffType, diffText] = diffs[i];\n if (diffText.length === 0) continue;\n const firstChar = diffText[0];\n const lastChar = diffText[diffText.length - 1];\n if (isHighSurrogate(lastChar) && diffType === DIFF_EQUAL) {\n deisolateChar(diffs, i, 1);\n }\n if (isLowSurrogate(firstChar) && diffType === DIFF_EQUAL) {\n deisolateChar(diffs, i, -1);\n }\n }\n for (let i = 0; i < diffs.length; i++) {\n if (diffs[i][1].length === 0) {\n diffs.splice(i, 1);\n }\n }\n}\nconst DEFAULT_OPTIONS = {\n /**\n * At what point is no match declared (0.0 = perfection, 1.0 = very loose).\n */\n threshold: 0.5,\n /**\n * How far to search for a match (0 = exact location, 1000+ = broad match).\n * A match this many characters away from the expected location will add\n * 1.0 to the score (0.0 is a perfect match).\n */\n distance: 1e3\n};\nfunction applyDefaults(options) {\n return {\n ...DEFAULT_OPTIONS,\n ...options\n };\n}\nconst MAX_BITS$1 = 32;\nfunction bitap(text, pattern, loc) {\n let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n if (pattern.length > MAX_BITS$1) {\n throw new Error(\"Pattern too long for this browser.\");\n }\n const options = applyDefaults(opts);\n const s = getAlphabetFromPattern(pattern);\n function getBitapScore(e, x) {\n const accuracy = e / pattern.length;\n const proximity = Math.abs(loc - x);\n if (!options.distance) {\n return proximity ? 1 : accuracy;\n }\n return accuracy + proximity / options.distance;\n }\n let scoreThreshold = options.threshold;\n let bestLoc = text.indexOf(pattern, loc);\n if (bestLoc !== -1) {\n scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold);\n bestLoc = text.lastIndexOf(pattern, loc + pattern.length);\n if (bestLoc !== -1) {\n scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold);\n }\n }\n const matchmask = 1 << pattern.length - 1;\n bestLoc = -1;\n let binMin;\n let binMid;\n let binMax = pattern.length + text.length;\n let lastRd = [];\n for (let d = 0; d < pattern.length; d++) {\n binMin = 0;\n binMid = binMax;\n while (binMin < binMid) {\n if (getBitapScore(d, loc + binMid) <= scoreThreshold) {\n binMin = binMid;\n } else {\n binMax = binMid;\n }\n binMid = Math.floor((binMax - binMin) / 2 + binMin);\n }\n binMax = binMid;\n let start = Math.max(1, loc - binMid + 1);\n const finish = Math.min(loc + binMid, text.length) + pattern.length;\n const rd = new Array(finish + 2);\n rd[finish + 1] = (1 << d) - 1;\n for (let j = finish; j >= start; j--) {\n const charMatch = s[text.charAt(j - 1)];\n if (d === 0) {\n rd[j] = (rd[j + 1] << 1 | 1) & charMatch;\n } else {\n rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((lastRd[j + 1] | lastRd[j]) << 1 | 1) | lastRd[j + 1];\n }\n if (rd[j] & matchmask) {\n const score = getBitapScore(d, j - 1);\n if (score <= scoreThreshold) {\n scoreThreshold = score;\n bestLoc = j - 1;\n if (bestLoc > loc) {\n start = Math.max(1, 2 * loc - bestLoc);\n } else {\n break;\n }\n }\n }\n }\n if (getBitapScore(d + 1, loc) > scoreThreshold) {\n break;\n }\n lastRd = rd;\n }\n return bestLoc;\n}\nfunction getAlphabetFromPattern(pattern) {\n const s = {};\n for (let i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] = 0;\n }\n for (let i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;\n }\n return s;\n}\nfunction match(text, pattern, searchLocation) {\n if (text === null || pattern === null || searchLocation === null) {\n throw new Error(\"Null input. (match())\");\n }\n const loc = Math.max(0, Math.min(searchLocation, text.length));\n if (text === pattern) {\n return 0;\n } else if (!text.length) {\n return -1;\n } else if (text.substring(loc, loc + pattern.length) === pattern) {\n return loc;\n }\n return bitap(text, pattern, loc);\n}\nfunction createPatchObject(start1, start2) {\n return {\n diffs: [],\n start1,\n start2,\n utf8Start1: start1,\n utf8Start2: start2,\n length1: 0,\n length2: 0,\n utf8Length1: 0,\n utf8Length2: 0\n };\n}\nfunction diffText1(diffs) {\n const text = [];\n for (let x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) {\n text[x] = diffs[x][1];\n }\n }\n return text.join(\"\");\n}\nfunction diffText2(diffs) {\n const text = [];\n for (let x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_DELETE) {\n text[x] = diffs[x][1];\n }\n }\n return text.join(\"\");\n}\nfunction countUtf8Bytes(str) {\n let bytes = 0;\n for (let i = 0; i < str.length; i++) {\n const codePoint = str.codePointAt(i);\n if (typeof codePoint === \"undefined\") {\n throw new Error(\"Failed to get codepoint\");\n }\n bytes += utf8len(codePoint);\n }\n return bytes;\n}\nfunction adjustIndiciesToUcs2(patches, base) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n let byteOffset = 0;\n let idx = 0;\n function advanceTo(target) {\n for (; byteOffset < target;) {\n const codePoint = base.codePointAt(idx);\n if (typeof codePoint === \"undefined\") {\n return idx;\n }\n byteOffset += utf8len(codePoint);\n if (codePoint > 65535) {\n idx += 2;\n } else {\n idx += 1;\n }\n }\n if (!options.allowExceedingIndices && byteOffset !== target) {\n throw new Error(\"Failed to determine byte offset\");\n }\n return idx;\n }\n const adjusted = [];\n for (const patch of patches) {\n adjusted.push({\n diffs: patch.diffs.map(diff => cloneDiff(diff)),\n start1: advanceTo(patch.start1),\n start2: advanceTo(patch.start2),\n utf8Start1: patch.utf8Start1,\n utf8Start2: patch.utf8Start2,\n length1: patch.length1,\n length2: patch.length2,\n utf8Length1: patch.utf8Length1,\n utf8Length2: patch.utf8Length2\n });\n }\n return adjusted;\n}\nfunction utf8len(codePoint) {\n if (codePoint <= 127) return 1;\n if (codePoint <= 2047) return 2;\n if (codePoint <= 65535) return 3;\n return 4;\n}\nconst MAX_BITS = 32;\nconst DEFAULT_MARGIN = 4;\nconst DEFAULT_OPTS = {\n margin: 4\n};\nfunction getDefaultOpts() {\n let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return {\n ...DEFAULT_OPTS,\n ...opts\n };\n}\nfunction make(a, b, options) {\n if (typeof a === \"string\" && typeof b === \"string\") {\n let diffs = diff(a, b, {\n checkLines: true\n });\n if (diffs.length > 2) {\n diffs = cleanupSemantic(diffs);\n diffs = cleanupEfficiency(diffs);\n }\n return _make(a, diffs, getDefaultOpts(options));\n }\n if (a && Array.isArray(a) && typeof b === \"undefined\") {\n return _make(diffText1(a), a, getDefaultOpts(options));\n }\n if (typeof a === \"string\" && b && Array.isArray(b)) {\n return _make(a, b, getDefaultOpts(options));\n }\n throw new Error(\"Unknown call format to make()\");\n}\nfunction _make(textA, diffs, options) {\n if (diffs.length === 0) {\n return [];\n }\n const patches = [];\n let patch = createPatchObject(0, 0);\n let patchDiffLength = 0;\n let charCount1 = 0;\n let charCount2 = 0;\n let utf8Count1 = 0;\n let utf8Count2 = 0;\n let prepatchText = textA;\n let postpatchText = textA;\n for (let x = 0; x < diffs.length; x++) {\n const currentDiff = diffs[x];\n const [diffType, diffText] = currentDiff;\n const diffTextLength = diffText.length;\n const diffByteLength = countUtf8Bytes(diffText);\n if (!patchDiffLength && diffType !== DIFF_EQUAL) {\n patch.start1 = charCount1;\n patch.start2 = charCount2;\n patch.utf8Start1 = utf8Count1;\n patch.utf8Start2 = utf8Count2;\n }\n switch (diffType) {\n case DIFF_INSERT:\n patch.diffs[patchDiffLength++] = currentDiff;\n patch.length2 += diffTextLength;\n patch.utf8Length2 += diffByteLength;\n postpatchText = postpatchText.substring(0, charCount2) + diffText + postpatchText.substring(charCount2);\n break;\n case DIFF_DELETE:\n patch.length1 += diffTextLength;\n patch.utf8Length1 += diffByteLength;\n patch.diffs[patchDiffLength++] = currentDiff;\n postpatchText = postpatchText.substring(0, charCount2) + postpatchText.substring(charCount2 + diffTextLength);\n break;\n case DIFF_EQUAL:\n if (diffTextLength <= 2 * options.margin && patchDiffLength && diffs.length !== x + 1) {\n patch.diffs[patchDiffLength++] = currentDiff;\n patch.length1 += diffTextLength;\n patch.length2 += diffTextLength;\n patch.utf8Length1 += diffByteLength;\n patch.utf8Length2 += diffByteLength;\n } else if (diffTextLength >= 2 * options.margin) {\n if (patchDiffLength) {\n addContext(patch, prepatchText, options);\n patches.push(patch);\n patch = createPatchObject(-1, -1);\n patchDiffLength = 0;\n prepatchText = postpatchText;\n charCount1 = charCount2;\n utf8Count1 = utf8Count2;\n }\n }\n break;\n default:\n throw new Error(\"Unknown diff type\");\n }\n if (diffType !== DIFF_INSERT) {\n charCount1 += diffTextLength;\n utf8Count1 += diffByteLength;\n }\n if (diffType !== DIFF_DELETE) {\n charCount2 += diffTextLength;\n utf8Count2 += diffByteLength;\n }\n }\n if (patchDiffLength) {\n addContext(patch, prepatchText, options);\n patches.push(patch);\n }\n return patches;\n}\nfunction addContext(patch, text, opts) {\n if (text.length === 0) {\n return;\n }\n let pattern = text.substring(patch.start2, patch.start2 + patch.length1);\n let padding = 0;\n while (text.indexOf(pattern) !== text.lastIndexOf(pattern) && pattern.length < MAX_BITS - opts.margin - opts.margin) {\n padding += opts.margin;\n pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding);\n }\n padding += opts.margin;\n let prefixStart = patch.start2 - padding;\n if (prefixStart >= 1 && isLowSurrogate(text[prefixStart])) {\n prefixStart--;\n }\n const prefix = text.substring(prefixStart, patch.start2);\n if (prefix) {\n patch.diffs.unshift([DIFF_EQUAL, prefix]);\n }\n const prefixLength = prefix.length;\n const prefixUtf8Length = countUtf8Bytes(prefix);\n let suffixEnd = patch.start2 + patch.length1 + padding;\n if (suffixEnd < text.length && isLowSurrogate(text[suffixEnd])) {\n suffixEnd++;\n }\n const suffix = text.substring(patch.start2 + patch.length1, suffixEnd);\n if (suffix) {\n patch.diffs.push([DIFF_EQUAL, suffix]);\n }\n const suffixLength = suffix.length;\n const suffixUtf8Length = countUtf8Bytes(suffix);\n patch.start1 -= prefixLength;\n patch.start2 -= prefixLength;\n patch.utf8Start1 -= prefixUtf8Length;\n patch.utf8Start2 -= prefixUtf8Length;\n patch.length1 += prefixLength + suffixLength;\n patch.length2 += prefixLength + suffixLength;\n patch.utf8Length1 += prefixUtf8Length + suffixUtf8Length;\n patch.utf8Length2 += prefixUtf8Length + suffixUtf8Length;\n}\nfunction levenshtein(diffs) {\n let leven = 0;\n let insertions = 0;\n let deletions = 0;\n for (let x = 0; x < diffs.length; x++) {\n const op = diffs[x][0];\n const data = diffs[x][1];\n switch (op) {\n case DIFF_INSERT:\n insertions += data.length;\n break;\n case DIFF_DELETE:\n deletions += data.length;\n break;\n case DIFF_EQUAL:\n leven += Math.max(insertions, deletions);\n insertions = 0;\n deletions = 0;\n break;\n default:\n throw new Error(\"Unknown diff operation.\");\n }\n }\n leven += Math.max(insertions, deletions);\n return leven;\n}\nfunction xIndex(diffs, loc) {\n let chars1 = 0;\n let chars2 = 0;\n let lastChars1 = 0;\n let lastChars2 = 0;\n let x;\n for (x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) {\n chars1 += diffs[x][1].length;\n }\n if (diffs[x][0] !== DIFF_DELETE) {\n chars2 += diffs[x][1].length;\n }\n if (chars1 > loc) {\n break;\n }\n lastChars1 = chars1;\n lastChars2 = chars2;\n }\n if (diffs.length !== x && diffs[x][0] === DIFF_DELETE) {\n return lastChars2;\n }\n return lastChars2 + (loc - lastChars1);\n}\nfunction addPadding(patches) {\n let margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_MARGIN;\n const paddingLength = margin;\n let nullPadding = \"\";\n for (let x = 1; x <= paddingLength; x++) {\n nullPadding += String.fromCharCode(x);\n }\n for (const p of patches) {\n p.start1 += paddingLength;\n p.start2 += paddingLength;\n p.utf8Start1 += paddingLength;\n p.utf8Start2 += paddingLength;\n }\n let patch = patches[0];\n let diffs = patch.diffs;\n if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL) {\n diffs.unshift([DIFF_EQUAL, nullPadding]);\n patch.start1 -= paddingLength;\n patch.start2 -= paddingLength;\n patch.utf8Start1 -= paddingLength;\n patch.utf8Start2 -= paddingLength;\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n patch.utf8Length1 += paddingLength;\n patch.utf8Length2 += paddingLength;\n } else if (paddingLength > diffs[0][1].length) {\n const firstDiffLength = diffs[0][1].length;\n const extraLength = paddingLength - firstDiffLength;\n diffs[0][1] = nullPadding.substring(firstDiffLength) + diffs[0][1];\n patch.start1 -= extraLength;\n patch.start2 -= extraLength;\n patch.utf8Start1 -= extraLength;\n patch.utf8Start2 -= extraLength;\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n patch.utf8Length1 += extraLength;\n patch.utf8Length2 += extraLength;\n }\n patch = patches[patches.length - 1];\n diffs = patch.diffs;\n if (diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL) {\n diffs.push([DIFF_EQUAL, nullPadding]);\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n patch.utf8Length1 += paddingLength;\n patch.utf8Length2 += paddingLength;\n } else if (paddingLength > diffs[diffs.length - 1][1].length) {\n const extraLength = paddingLength - diffs[diffs.length - 1][1].length;\n diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n patch.utf8Length1 += extraLength;\n patch.utf8Length2 += extraLength;\n }\n return nullPadding;\n}\nfunction splitMax(patches) {\n let margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_MARGIN;\n const patchSize = MAX_BITS;\n for (let x = 0; x < patches.length; x++) {\n if (patches[x].length1 <= patchSize) {\n continue;\n }\n const bigpatch = patches[x];\n patches.splice(x--, 1);\n let start1 = bigpatch.start1;\n let start2 = bigpatch.start2;\n let preContext = \"\";\n while (bigpatch.diffs.length !== 0) {\n const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);\n let empty = true;\n if (preContext !== \"\") {\n const precontextByteCount = countUtf8Bytes(preContext);\n patch.length1 = preContext.length;\n patch.utf8Length1 = precontextByteCount;\n patch.length2 = preContext.length;\n patch.utf8Length2 = precontextByteCount;\n patch.diffs.push([DIFF_EQUAL, preContext]);\n }\n while (bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin) {\n const diffType = bigpatch.diffs[0][0];\n let diffText = bigpatch.diffs[0][1];\n let diffTextByteCount = countUtf8Bytes(diffText);\n if (diffType === DIFF_INSERT) {\n patch.length2 += diffText.length;\n patch.utf8Length2 += diffTextByteCount;\n start2 += diffText.length;\n const diff = bigpatch.diffs.shift();\n if (diff) {\n patch.diffs.push(diff);\n }\n empty = false;\n } else if (diffType === DIFF_DELETE && patch.diffs.length === 1 && patch.diffs[0][0] === DIFF_EQUAL && diffText.length > 2 * patchSize) {\n patch.length1 += diffText.length;\n patch.utf8Length1 += diffTextByteCount;\n start1 += diffText.length;\n empty = false;\n patch.diffs.push([diffType, diffText]);\n bigpatch.diffs.shift();\n } else {\n diffText = diffText.substring(0, patchSize - patch.length1 - margin);\n diffTextByteCount = countUtf8Bytes(diffText);\n patch.length1 += diffText.length;\n patch.utf8Length1 += diffTextByteCount;\n start1 += diffText.length;\n if (diffType === DIFF_EQUAL) {\n patch.length2 += diffText.length;\n patch.utf8Length2 += diffTextByteCount;\n start2 += diffText.length;\n } else {\n empty = false;\n }\n patch.diffs.push([diffType, diffText]);\n if (diffText === bigpatch.diffs[0][1]) {\n bigpatch.diffs.shift();\n } else {\n bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diffText.length);\n }\n }\n }\n preContext = diffText2(patch.diffs);\n preContext = preContext.substring(preContext.length - margin);\n const postContext = diffText1(bigpatch.diffs).substring(0, margin);\n const postContextByteCount = countUtf8Bytes(postContext);\n if (postContext !== \"\") {\n patch.length1 += postContext.length;\n patch.length2 += postContext.length;\n patch.utf8Length1 += postContextByteCount;\n patch.utf8Length2 += postContextByteCount;\n if (patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {\n patch.diffs[patch.diffs.length - 1][1] += postContext;\n } else {\n patch.diffs.push([DIFF_EQUAL, postContext]);\n }\n }\n if (!empty) {\n patches.splice(++x, 0, patch);\n }\n }\n }\n}\nfunction apply(patches, originalText) {\n let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (typeof patches === \"string\") {\n throw new Error(\"Patches must be an array - pass the patch to `parsePatch()` first\");\n }\n let text = originalText;\n if (patches.length === 0) {\n return [text, []];\n }\n const parsed = adjustIndiciesToUcs2(patches, text, {\n allowExceedingIndices: opts.allowExceedingIndices\n });\n const margin = opts.margin || DEFAULT_MARGIN;\n const deleteThreshold = opts.deleteThreshold || 0.4;\n const nullPadding = addPadding(parsed, margin);\n text = nullPadding + text + nullPadding;\n splitMax(parsed, margin);\n let delta = 0;\n const results = [];\n for (let x = 0; x < parsed.length; x++) {\n const expectedLoc = parsed[x].start2 + delta;\n const text1 = diffText1(parsed[x].diffs);\n let startLoc;\n let endLoc = -1;\n if (text1.length > MAX_BITS) {\n startLoc = match(text, text1.substring(0, MAX_BITS), expectedLoc);\n if (startLoc !== -1) {\n endLoc = match(text, text1.substring(text1.length - MAX_BITS), expectedLoc + text1.length - MAX_BITS);\n if (endLoc === -1 || startLoc >= endLoc) {\n startLoc = -1;\n }\n }\n } else {\n startLoc = match(text, text1, expectedLoc);\n }\n if (startLoc === -1) {\n results[x] = false;\n delta -= parsed[x].length2 - parsed[x].length1;\n } else {\n results[x] = true;\n delta = startLoc - expectedLoc;\n let text2;\n if (endLoc === -1) {\n text2 = text.substring(startLoc, startLoc + text1.length);\n } else {\n text2 = text.substring(startLoc, endLoc + MAX_BITS);\n }\n if (text1 === text2) {\n text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);\n } else {\n let diffs = diff(text1, text2, {\n checkLines: false\n });\n if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold) {\n results[x] = false;\n } else {\n diffs = cleanupSemanticLossless(diffs);\n let index1 = 0;\n let index2 = 0;\n for (let y = 0; y < parsed[x].diffs.length; y++) {\n const mod = parsed[x].diffs[y];\n if (mod[0] !== DIFF_EQUAL) {\n index2 = xIndex(diffs, index1);\n }\n if (mod[0] === DIFF_INSERT) {\n text = text.substring(0, startLoc + index2) + mod[1] + text.substring(startLoc + index2);\n } else if (mod[0] === DIFF_DELETE) {\n text = text.substring(0, startLoc + index2) + text.substring(startLoc + xIndex(diffs, index1 + mod[1].length));\n }\n if (mod[0] !== DIFF_DELETE) {\n index1 += mod[1].length;\n }\n }\n }\n }\n }\n }\n text = text.substring(nullPadding.length, text.length - nullPadding.length);\n return [text, results];\n}\nfunction stringify(patches) {\n return patches.map(stringifyPatch).join(\"\");\n}\nfunction stringifyPatch(patch) {\n const {\n utf8Length1,\n utf8Length2,\n utf8Start1,\n utf8Start2,\n diffs\n } = patch;\n let coords1;\n if (utf8Length1 === 0) {\n coords1 = \"\".concat(utf8Start1, \",0\");\n } else if (utf8Length1 === 1) {\n coords1 = \"\".concat(utf8Start1 + 1);\n } else {\n coords1 = \"\".concat(utf8Start1 + 1, \",\").concat(utf8Length1);\n }\n let coords2;\n if (utf8Length2 === 0) {\n coords2 = \"\".concat(utf8Start2, \",0\");\n } else if (utf8Length2 === 1) {\n coords2 = \"\".concat(utf8Start2 + 1);\n } else {\n coords2 = \"\".concat(utf8Start2 + 1, \",\").concat(utf8Length2);\n }\n const text = [\"@@ -\".concat(coords1, \" +\").concat(coords2, \" @@\\n\")];\n let op;\n for (let x = 0; x < diffs.length; x++) {\n switch (diffs[x][0]) {\n case DIFF_INSERT:\n op = \"+\";\n break;\n case DIFF_DELETE:\n op = \"-\";\n break;\n case DIFF_EQUAL:\n op = \" \";\n break;\n default:\n throw new Error(\"Unknown patch operation.\");\n }\n text[x + 1] = \"\".concat(op + encodeURI(diffs[x][1]), \"\\n\");\n }\n return text.join(\"\").replace(/%20/g, \" \");\n}\nconst patchHeader = /^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$/;\nfunction parse(textline) {\n if (!textline) {\n return [];\n }\n const patches = [];\n const lines = textline.split(\"\\n\");\n let textPointer = 0;\n while (textPointer < lines.length) {\n const m = lines[textPointer].match(patchHeader);\n if (!m) {\n throw new Error(\"Invalid patch string: \".concat(lines[textPointer]));\n }\n const patch = createPatchObject(toInt(m[1]), toInt(m[3]));\n patches.push(patch);\n if (m[2] === \"\") {\n patch.start1--;\n patch.utf8Start1--;\n patch.length1 = 1;\n patch.utf8Length1 = 1;\n } else if (m[2] === \"0\") {\n patch.length1 = 0;\n patch.utf8Length1 = 0;\n } else {\n patch.start1--;\n patch.utf8Start1--;\n patch.utf8Length1 = toInt(m[2]);\n patch.length1 = patch.utf8Length1;\n }\n if (m[4] === \"\") {\n patch.start2--;\n patch.utf8Start2--;\n patch.length2 = 1;\n patch.utf8Length2 = 1;\n } else if (m[4] === \"0\") {\n patch.length2 = 0;\n patch.utf8Length2 = 0;\n } else {\n patch.start2--;\n patch.utf8Start2--;\n patch.utf8Length2 = toInt(m[4]);\n patch.length2 = patch.utf8Length2;\n }\n textPointer++;\n while (textPointer < lines.length) {\n const currentLine = lines[textPointer];\n const sign = currentLine.charAt(0);\n if (sign === \"@\") {\n break;\n }\n if (sign === \"\") {\n textPointer++;\n continue;\n }\n let line;\n try {\n line = decodeURI(currentLine.slice(1));\n } catch (ex) {\n throw new Error(\"Illegal escape in parse: \".concat(currentLine));\n }\n const utf8Diff = countUtf8Bytes(line) - line.length;\n if (sign === \"-\") {\n patch.diffs.push([DIFF_DELETE, line]);\n patch.length1 -= utf8Diff;\n } else if (sign === \"+\") {\n patch.diffs.push([DIFF_INSERT, line]);\n patch.length2 -= utf8Diff;\n } else if (sign === \" \") {\n patch.diffs.push([DIFF_EQUAL, line]);\n patch.length1 -= utf8Diff;\n patch.length2 -= utf8Diff;\n } else {\n throw new Error(\"Invalid patch mode \\\"\".concat(sign, \"\\\" in: \").concat(line));\n }\n textPointer++;\n }\n }\n return patches;\n}\nfunction toInt(num) {\n return parseInt(num, 10);\n}\nexport { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, adjustIndiciesToUcs2, apply as applyPatches, cleanupEfficiency, cleanupSemantic, diff as makeDiff, make as makePatches, match, parse as parsePatch, stringifyPatch, stringify as stringifyPatches };\n//# sourceMappingURL=index.js.map\n","import {\n applyAll,\n type DiffMatchPatch,\n type InsertPatch,\n type Patch,\n type SetPatch,\n type UnsetPatch,\n} from '@portabletext/patches'\nimport {\n cleanupEfficiency,\n DIFF_DELETE,\n DIFF_EQUAL,\n DIFF_INSERT,\n applyPatches as diffMatchPatchApplyPatches,\n makeDiff,\n parsePatch,\n} from '@sanity/diff-match-patch'\nimport type {\n KeyedSegment,\n Path,\n PathSegment,\n PortableTextBlock,\n PortableTextChild,\n} from '@sanity/types'\nimport {\n Element,\n Text,\n Transforms,\n type Descendant,\n type Node,\n type Path as SlatePath,\n} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../types/editor'\nimport {debugWithName} from './debug'\nimport {toSlateValue} from './values'\nimport {KEY_TO_SLATE_ELEMENT} from './weakMaps'\n\nconst debug = debugWithName('applyPatches')\nconst debugVerbose = debug.enabled && true\n\n/**\n * Creates a function that can apply a patch onto a PortableTextSlateEditor.\n */\nexport function createApplyPatch(\n schemaTypes: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor, patch: Patch) => boolean {\n return (editor: PortableTextSlateEditor, patch: Patch): boolean => {\n let changed = false\n\n // Save some CPU cycles by not stringifying unless enabled\n if (debugVerbose) {\n debug(\n '\\n\\nNEW PATCH =============================================================',\n )\n debug(JSON.stringify(patch, null, 2))\n }\n\n try {\n switch (patch.type) {\n case 'insert':\n changed = insertPatch(editor, patch, schemaTypes)\n break\n case 'unset':\n changed = unsetPatch(editor, patch)\n break\n case 'set':\n changed = setPatch(editor, patch)\n break\n case 'diffMatchPatch':\n changed = diffMatchPatch(editor, patch)\n break\n default:\n debug('Unhandled patch', patch.type)\n }\n } catch (err) {\n console.error(err)\n }\n\n return changed\n }\n}\n\n/**\n * Apply a remote diff match patch to the current PTE instance.\n * Note meant for external consumption, only exported for testing purposes.\n *\n * @param editor - Portable text slate editor instance\n * @param patch - The PTE diff match patch operation to apply\n * @returns true if the patch was applied, false otherwise\n * @internal\n */\nexport function diffMatchPatch(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection' | 'onChange'\n >,\n patch: DiffMatchPatch,\n): boolean {\n const {block, child, childPath} = findBlockAndChildFromPath(\n editor,\n patch.path,\n )\n if (!block) {\n debug('Block not found')\n return false\n }\n if (!child || !childPath) {\n debug('Child not found')\n return false\n }\n const isSpanTextDiffMatchPatch =\n block &&\n editor.isTextBlock(block) &&\n patch.path.length === 4 &&\n patch.path[1] === 'children' &&\n patch.path[3] === 'text'\n\n if (!isSpanTextDiffMatchPatch || !Text.isText(child)) {\n return false\n }\n\n const patches = parsePatch(patch.value)\n const [newValue] = diffMatchPatchApplyPatches(patches, child.text, {\n allowExceedingIndices: true,\n })\n const diff = cleanupEfficiency(makeDiff(child.text, newValue), 5)\n\n debugState(editor, 'before')\n let offset = 0\n for (const [op, text] of diff) {\n if (op === DIFF_INSERT) {\n editor.apply({type: 'insert_text', path: childPath, offset, text})\n offset += text.length\n } else if (op === DIFF_DELETE) {\n editor.apply({type: 'remove_text', path: childPath, offset: offset, text})\n } else if (op === DIFF_EQUAL) {\n offset += text.length\n }\n }\n debugState(editor, 'after')\n\n return true\n}\n\nfunction insertPatch(\n editor: PortableTextSlateEditor,\n patch: InsertPatch,\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n const {\n block: targetBlock,\n child: targetChild,\n blockPath: targetBlockPath,\n childPath: targetChildPath,\n } = findBlockAndChildFromPath(editor, patch.path)\n if (!targetBlock || !targetBlockPath) {\n debug('Block not found')\n return false\n }\n if (patch.path.length > 1 && patch.path[1] !== 'children') {\n debug('Ignoring patch targeting void value')\n return false\n }\n // Insert blocks\n if (patch.path.length === 1) {\n const {items, position} = patch\n const blocksToInsert = toSlateValue(\n items as PortableTextBlock[],\n {schemaTypes},\n KEY_TO_SLATE_ELEMENT.get(editor),\n ) as Descendant[]\n const targetBlockIndex = targetBlockPath[0]\n const normalizedIdx =\n position === 'after' ? targetBlockIndex + 1 : targetBlockIndex\n debug(`Inserting blocks at path [${normalizedIdx}]`)\n debugState(editor, 'before')\n Transforms.insertNodes(editor, blocksToInsert, {at: [normalizedIdx]})\n debugState(editor, 'after')\n return true\n }\n // Insert children\n const {items, position} = patch\n if (!targetChild || !targetChildPath) {\n debug('Child not found')\n return false\n }\n const childrenToInsert =\n targetBlock &&\n toSlateValue(\n [{...targetBlock, children: items as PortableTextChild[]}],\n {schemaTypes},\n KEY_TO_SLATE_ELEMENT.get(editor),\n )\n const targetChildIndex = targetChildPath[1]\n const normalizedIdx =\n position === 'after' ? targetChildIndex + 1 : targetChildIndex\n const childInsertPath = [targetChildPath[0], normalizedIdx]\n debug(`Inserting children at path ${childInsertPath}`)\n debugState(editor, 'before')\n if (childrenToInsert && Element.isElement(childrenToInsert[0])) {\n Transforms.insertNodes(editor, childrenToInsert[0].children, {\n at: childInsertPath,\n })\n }\n debugState(editor, 'after')\n return true\n}\n\nfunction setPatch(editor: PortableTextSlateEditor, patch: SetPatch) {\n let value = patch.value\n if (typeof patch.path[3] === 'string') {\n value = {}\n value[patch.path[3]] = patch.value\n }\n const {block, blockPath, child, childPath} = findBlockAndChildFromPath(\n editor,\n patch.path,\n )\n\n if (!block) {\n debug('Block not found')\n return false\n }\n const isTextBlock = editor.isTextBlock(block)\n\n // Ignore patches targeting nested void data, like 'markDefs'\n if (isTextBlock && patch.path.length > 1 && patch.path[1] !== 'children') {\n debug('Ignoring setting void value')\n return false\n }\n\n debugState(editor, 'before')\n\n // If this is targeting a text block child\n if (isTextBlock && child && childPath) {\n if (Text.isText(value) && Text.isText(child)) {\n const newText = child.text\n const oldText = value.text\n if (oldText !== newText) {\n debug('Setting text property')\n editor.apply({\n type: 'remove_text',\n path: childPath,\n offset: 0,\n text: newText,\n })\n editor.apply({\n type: 'insert_text',\n path: childPath,\n offset: 0,\n text: value.text,\n })\n // call OnChange here to emit the new selection\n // the user's selection might be interfering with\n editor.onChange()\n }\n } else {\n debug('Setting non-text property')\n editor.apply({\n type: 'set_node',\n path: childPath,\n properties: {},\n newProperties: value as Partial<Node>,\n })\n }\n return true\n } else if (Element.isElement(block) && patch.path.length === 1 && blockPath) {\n debug('Setting block property')\n const {children, ...nextRest} = value as unknown as PortableTextBlock\n const {children: prevChildren, ...prevRest} = block || {children: undefined}\n // Set any block properties\n editor.apply({\n type: 'set_node',\n path: blockPath,\n properties: {...prevRest},\n newProperties: nextRest,\n })\n // Replace the children in the block\n // Note that children must be explicitly inserted, and can't be set with set_node\n debug('Setting children')\n block.children.forEach((c, cIndex) => {\n editor.apply({\n type: 'remove_node',\n path: blockPath.concat(block.children.length - 1 - cIndex),\n node: c,\n })\n })\n if (Array.isArray(children)) {\n children.forEach((c, cIndex) => {\n editor.apply({\n type: 'insert_node',\n path: blockPath.concat(cIndex),\n node: c,\n })\n })\n }\n } else if (block && 'value' in block) {\n const newVal = applyAll([block.value], [patch])[0]\n Transforms.setNodes(editor, {...block, value: newVal}, {at: blockPath})\n return true\n }\n debugState(editor, 'after')\n return true\n}\n\nfunction unsetPatch(editor: PortableTextSlateEditor, patch: UnsetPatch) {\n // Value\n if (patch.path.length === 0) {\n debug('Removing everything')\n debugState(editor, 'before')\n const previousSelection = editor.selection\n Transforms.deselect(editor)\n editor.children.forEach((_child, i) => {\n Transforms.removeNodes(editor, {at: [i]})\n })\n Transforms.insertNodes(editor, editor.pteCreateTextBlock({decorators: []}))\n if (previousSelection) {\n Transforms.select(editor, {\n anchor: {path: [0, 0], offset: 0},\n focus: {path: [0, 0], offset: 0},\n })\n }\n // call OnChange here to emit the new selection\n editor.onChange()\n debugState(editor, 'after')\n return true\n }\n const {block, blockPath, child, childPath} = findBlockAndChildFromPath(\n editor,\n patch.path,\n )\n\n // Single blocks\n if (patch.path.length === 1) {\n if (!block || !blockPath) {\n debug('Block not found')\n return false\n }\n const blockIndex = blockPath[0]\n debug(`Removing block at path [${blockIndex}]`)\n debugState(editor, 'before')\n\n Transforms.removeNodes(editor, {at: [blockIndex]})\n debugState(editor, 'after')\n return true\n }\n\n // Unset on text block children\n if (\n editor.isTextBlock(block) &&\n patch.path[1] === 'children' &&\n patch.path.length === 3\n ) {\n if (!child || !childPath) {\n debug('Child not found')\n return false\n }\n debug(`Unsetting child at path ${JSON.stringify(childPath)}`)\n debugState(editor, 'before')\n if (debugVerbose) {\n debug(`Removing child at path ${JSON.stringify(childPath)}`)\n }\n Transforms.removeNodes(editor, {at: childPath})\n debugState(editor, 'after')\n return true\n }\n return false\n}\n\nfunction isKeyedSegment(segment: PathSegment): segment is KeyedSegment {\n return typeof segment === 'object' && '_key' in segment\n}\n\nfunction debugState(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection'\n >,\n stateName: string,\n) {\n if (!debugVerbose) {\n return\n }\n\n debug(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2))\n debug(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2))\n}\n\nfunction findBlockFromPath(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection' | 'onChange'\n >,\n path: Path,\n): {block?: Descendant; path?: SlatePath} {\n let blockIndex = -1\n const block = editor.children.find((node: Descendant, index: number) => {\n const isMatch = isKeyedSegment(path[0])\n ? node._key === path[0]._key\n : index === path[0]\n if (isMatch) {\n blockIndex = index\n }\n return isMatch\n })\n if (!block) {\n return {}\n }\n return {block, path: [blockIndex] as SlatePath}\n}\n\nfunction findBlockAndChildFromPath(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection' | 'onChange'\n >,\n path: Path,\n): {\n child?: Descendant\n childPath?: SlatePath\n block?: Descendant\n blockPath?: SlatePath\n} {\n const {block, path: blockPath} = findBlockFromPath(editor, path)\n if (!(Element.isElement(block) && path[1] === 'children')) {\n return {block, blockPath, child: undefined, childPath: undefined}\n }\n let childIndex = -1\n const child = block.children.find((node, index: number) => {\n const isMatch = isKeyedSegment(path[2])\n ? node._key === path[2]._key\n : index === path[2]\n if (isMatch) {\n childIndex = index\n }\n return isMatch\n })\n if (!child) {\n return {block, blockPath, child: undefined, childPath: undefined}\n }\n return {\n block,\n child,\n blockPath,\n childPath: blockPath?.concat(childIndex) as SlatePath,\n }\n}\n","import type {Editor} from 'slate'\n\nexport const PATCHING: WeakMap<Editor, boolean | undefined> = new WeakMap()\n\nexport function withoutPatching(editor: Editor, fn: () => void): void {\n const prev = isPatching(editor)\n PATCHING.set(editor, false)\n fn()\n PATCHING.set(editor, prev)\n}\n\nexport function isPatching(editor: Editor): boolean | undefined {\n return PATCHING.get(editor)\n}\n","/**\n * This plugin will make the editor support undo/redo on the local state only.\n * The undo/redo steps are rebased against incoming patches since the step occurred.\n */\n\nimport type {Patch} from '@portabletext/patches'\nimport {\n DIFF_DELETE,\n DIFF_EQUAL,\n DIFF_INSERT,\n parsePatch,\n} from '@sanity/diff-match-patch'\nimport type {ObjectSchemaType, PortableTextBlock} from '@sanity/types'\nimport {flatten, isEqual} from 'lodash'\nimport {\n Editor,\n Operation,\n Path,\n Transforms,\n type Descendant,\n type SelectionOperation,\n} from 'slate'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue} from '../../utils/values'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {\n isRedoing,\n isUndoing,\n setIsRedoing,\n setIsUndoing,\n withRedoing,\n withUndoing,\n} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withUndoRedo')\nconst debugVerbose = debug.enabled && false\n\nconst SAVING = new WeakMap<Editor, boolean | undefined>()\nconst REMOTE_PATCHES = new WeakMap<\n Editor,\n {\n patch: Patch\n time: Date\n snapshot: PortableTextBlock[] | undefined\n previousSnapshot: PortableTextBlock[] | undefined\n }[]\n>()\nconst UNDO_STEP_LIMIT = 1000\n\nconst isSaving = (editor: Editor): boolean | undefined => {\n const state = SAVING.get(editor)\n return state === undefined ? true : state\n}\n\nexport interface Options {\n editorActor: EditorActor\n readOnly: boolean\n blockSchemaType: ObjectSchemaType\n}\n\nconst getRemotePatches = (editor: Editor) => {\n if (!REMOTE_PATCHES.get(editor)) {\n REMOTE_PATCHES.set(editor, [])\n }\n return REMOTE_PATCHES.get(editor) || []\n}\n\nexport function createWithUndoRedo(\n options: Options,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n const {editorActor, readOnly, blockSchemaType} = options\n\n return (editor: PortableTextSlateEditor) => {\n let previousSnapshot: PortableTextBlock[] | undefined = fromSlateValue(\n editor.children,\n blockSchemaType.name,\n )\n const remotePatches = getRemotePatches(editor)\n\n editor.subscriptions.push(() => {\n debug('Subscribing to patches')\n const sub = editorActor.on('patches', ({patches, snapshot}) => {\n let reset = false\n patches.forEach((patch) => {\n if (!reset && patch.origin !== 'local' && remotePatches) {\n if (patch.type === 'unset' && patch.path.length === 0) {\n debug(\n 'Someone else cleared the content, resetting undo/redo history',\n )\n editor.history = {undos: [], redos: []}\n remotePatches.splice(0, remotePatches.length)\n SAVING.set(editor, true)\n reset = true\n return\n }\n remotePatches.push({\n patch,\n time: new Date(),\n snapshot,\n previousSnapshot,\n })\n }\n })\n previousSnapshot = snapshot\n })\n return () => {\n debug('Unsubscribing to patches')\n sub.unsubscribe()\n }\n })\n\n editor.history = {undos: [], redos: []}\n const {apply} = editor\n editor.apply = (op: Operation) => {\n if (readOnly) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(op)\n return\n }\n\n const {operations, history} = editor\n const {undos} = history\n const step = undos[undos.length - 1]\n const lastOp =\n step && step.operations && step.operations[step.operations.length - 1]\n const overwrite = shouldOverwrite(op, lastOp)\n const save = isSaving(editor)\n\n let merge = true\n if (save) {\n if (!step) {\n merge = false\n } else if (operations.length === 0) {\n merge = shouldMerge(op, lastOp) || overwrite\n }\n\n if (step && merge) {\n step.operations.push(op)\n } else {\n const newStep = {\n operations: [\n ...(editor.selection === null\n ? []\n : [createSelectOperation(editor)]),\n op,\n ],\n timestamp: new Date(),\n }\n undos.push(newStep)\n debug('Created new undo step', step)\n }\n\n while (undos.length > UNDO_STEP_LIMIT) {\n undos.shift()\n }\n\n if (shouldClear(op)) {\n history.redos = []\n }\n }\n apply(op)\n }\n\n editor.undo = () => {\n if (readOnly) {\n return\n }\n const {undos} = editor.history\n if (undos.length > 0) {\n const step = undos[undos.length - 1]\n debug('Undoing', step)\n if (step.operations.length > 0) {\n const otherPatches = remotePatches.filter(\n (item) => item.time >= step.timestamp,\n )\n let transformedOperations = step.operations\n otherPatches.forEach((item) => {\n transformedOperations = flatten(\n transformedOperations.map((op) =>\n transformOperation(\n editor,\n item.patch,\n op,\n item.snapshot,\n item.previousSnapshot,\n ),\n ),\n )\n })\n const reversedOperations = transformedOperations\n .map(Operation.inverse)\n .reverse()\n\n try {\n Editor.withoutNormalizing(editor, () => {\n withUndoing(editor, () => {\n withoutSaving(editor, () => {\n reversedOperations.forEach((op) => {\n editor.apply(op)\n })\n })\n })\n })\n editor.normalize()\n editor.onChange()\n } catch (err) {\n debug('Could not perform undo step', err)\n remotePatches.splice(0, remotePatches.length)\n Transforms.deselect(editor)\n editor.history = {undos: [], redos: []}\n SAVING.set(editor, true)\n setIsUndoing(editor, false)\n editor.onChange()\n return\n }\n editor.history.redos.push(step)\n editor.history.undos.pop()\n }\n }\n }\n\n editor.redo = () => {\n if (readOnly) {\n return\n }\n const {redos} = editor.history\n if (redos.length > 0) {\n const step = redos[redos.length - 1]\n debug('Redoing', step)\n if (step.operations.length > 0) {\n const otherPatches = remotePatches.filter(\n (item) => item.time >= step.timestamp,\n )\n let transformedOperations = step.operations\n otherPatches.forEach((item) => {\n transformedOperations = flatten(\n transformedOperations.map((op) =>\n transformOperation(\n editor,\n item.patch,\n op,\n item.snapshot,\n item.previousSnapshot,\n ),\n ),\n )\n })\n try {\n Editor.withoutNormalizing(editor, () => {\n withRedoing(editor, () => {\n withoutSaving(editor, () => {\n transformedOperations.forEach((op) => {\n editor.apply(op)\n })\n })\n })\n })\n editor.normalize()\n editor.onChange()\n } catch (err) {\n debug('Could not perform redo step', err)\n remotePatches.splice(0, remotePatches.length)\n Transforms.deselect(editor)\n editor.history = {undos: [], redos: []}\n SAVING.set(editor, true)\n setIsRedoing(editor, false)\n editor.onChange()\n return\n }\n editor.history.undos.push(step)\n editor.history.redos.pop()\n }\n }\n }\n\n // Plugin return\n return editor\n }\n}\n\n/**\n * This will adjust the operation paths and offsets according to the\n * remote patches by other editors since the step operations was performed.\n */\nfunction transformOperation(\n editor: PortableTextSlateEditor,\n patch: Patch,\n operation: Operation,\n snapshot: PortableTextBlock[] | undefined,\n previousSnapshot: PortableTextBlock[] | undefined,\n): Operation[] {\n if (debugVerbose) {\n debug(\n `Adjusting '${operation.type}' operation paths for '${patch.type}' patch`,\n )\n debug(`Operation ${JSON.stringify(operation)}`)\n debug(`Patch ${JSON.stringify(patch)}`)\n }\n\n const transformedOperation = {...operation}\n\n if (patch.type === 'insert' && patch.path.length === 1) {\n const insertBlockIndex = (snapshot || []).findIndex((blk) =>\n isEqual({_key: blk._key}, patch.path[0]),\n )\n debug(\n `Adjusting block path (+${patch.items.length}) for '${transformedOperation.type}' operation and patch '${patch.type}'`,\n )\n return [\n adjustBlockPath(\n transformedOperation,\n patch.items.length,\n insertBlockIndex,\n ),\n ]\n }\n\n if (patch.type === 'unset' && patch.path.length === 1) {\n const unsetBlockIndex = (previousSnapshot || []).findIndex((blk) =>\n isEqual({_key: blk._key}, patch.path[0]),\n )\n // If this operation is targeting the same block that got removed, return empty\n if (\n 'path' in transformedOperation &&\n Array.isArray(transformedOperation.path) &&\n transformedOperation.path[0] === unsetBlockIndex\n ) {\n debug('Skipping transformation that targeted removed block')\n return []\n }\n if (debugVerbose) {\n debug(`Selection ${JSON.stringify(editor.selection)}`)\n debug(\n `Adjusting block path (-1) for '${transformedOperation.type}' operation and patch '${patch.type}'`,\n )\n }\n return [adjustBlockPath(transformedOperation, -1, unsetBlockIndex)]\n }\n\n // Someone reset the whole value\n if (patch.type === 'unset' && patch.path.length === 0) {\n debug(\n `Adjusting selection for unset everything patch and ${operation.type} operation`,\n )\n return []\n }\n\n if (patch.type === 'diffMatchPatch') {\n const operationTargetBlock = findOperationTargetBlock(\n editor,\n transformedOperation,\n )\n if (\n !operationTargetBlock ||\n !isEqual({_key: operationTargetBlock._key}, patch.path[0])\n ) {\n return [transformedOperation]\n }\n const diffPatches = parsePatch(patch.value)\n diffPatches.forEach((diffPatch) => {\n let adjustOffsetBy = 0\n let changedOffset = diffPatch.utf8Start1\n const {diffs} = diffPatch\n diffs.forEach((diff, index) => {\n const [diffType, text] = diff\n if (diffType === DIFF_INSERT) {\n adjustOffsetBy += text.length\n changedOffset += text.length\n } else if (diffType === DIFF_DELETE) {\n adjustOffsetBy -= text.length\n changedOffset -= text.length\n } else if (diffType === DIFF_EQUAL) {\n // Only up to the point where there are no other changes\n if (!diffs.slice(index).every(([dType]) => dType === DIFF_EQUAL)) {\n changedOffset += text.length\n }\n }\n })\n // Adjust accordingly if someone inserted text in the same node before us\n if (transformedOperation.type === 'insert_text') {\n if (changedOffset < transformedOperation.offset) {\n transformedOperation.offset += adjustOffsetBy\n }\n }\n // Adjust accordingly if someone removed text in the same node before us\n if (transformedOperation.type === 'remove_text') {\n if (\n changedOffset <=\n transformedOperation.offset - transformedOperation.text.length\n ) {\n transformedOperation.offset += adjustOffsetBy\n }\n }\n // Adjust set_selection operation's points to new offset\n if (transformedOperation.type === 'set_selection') {\n const currentFocus = transformedOperation.properties?.focus\n ? {...transformedOperation.properties.focus}\n : undefined\n const currentAnchor = transformedOperation?.properties?.anchor\n ? {...transformedOperation.properties.anchor}\n : undefined\n const newFocus = transformedOperation?.newProperties?.focus\n ? {...transformedOperation.newProperties.focus}\n : undefined\n const newAnchor = transformedOperation?.newProperties?.anchor\n ? {...transformedOperation.newProperties.anchor}\n : undefined\n if ((currentFocus && currentAnchor) || (newFocus && newAnchor)) {\n const points = [currentFocus, currentAnchor, newFocus, newAnchor]\n points.forEach((point) => {\n if (point && changedOffset < point.offset) {\n point.offset += adjustOffsetBy\n }\n })\n if (currentFocus && currentAnchor) {\n transformedOperation.properties = {\n focus: currentFocus,\n anchor: currentAnchor,\n }\n }\n if (newFocus && newAnchor) {\n transformedOperation.newProperties = {\n focus: newFocus,\n anchor: newAnchor,\n }\n }\n }\n }\n })\n return [transformedOperation]\n }\n return [transformedOperation]\n}\n/**\n * Adjust the block path for a operation\n */\nfunction adjustBlockPath(\n operation: Operation,\n level: number,\n blockIndex: number,\n): Operation {\n const transformedOperation = {...operation}\n if (\n blockIndex >= 0 &&\n transformedOperation.type !== 'set_selection' &&\n Array.isArray(transformedOperation.path) &&\n transformedOperation.path[0] >= blockIndex + level &&\n transformedOperation.path[0] + level > -1\n ) {\n const newPath = [\n transformedOperation.path[0] + level,\n ...transformedOperation.path.slice(1),\n ]\n transformedOperation.path = newPath\n }\n if (transformedOperation.type === 'set_selection') {\n const currentFocus = transformedOperation.properties?.focus\n ? {...transformedOperation.properties.focus}\n : undefined\n const currentAnchor = transformedOperation?.properties?.anchor\n ? {...transformedOperation.properties.anchor}\n : undefined\n const newFocus = transformedOperation?.newProperties?.focus\n ? {...transformedOperation.newProperties.focus}\n : undefined\n const newAnchor = transformedOperation?.newProperties?.anchor\n ? {...transformedOperation.newProperties.anchor}\n : undefined\n if ((currentFocus && currentAnchor) || (newFocus && newAnchor)) {\n const points = [currentFocus, currentAnchor, newFocus, newAnchor]\n points.forEach((point) => {\n if (\n point &&\n point.path[0] >= blockIndex + level &&\n point.path[0] + level > -1\n ) {\n point.path = [point.path[0] + level, ...point.path.slice(1)]\n }\n })\n if (currentFocus && currentAnchor) {\n transformedOperation.properties = {\n focus: currentFocus,\n anchor: currentAnchor,\n }\n }\n if (newFocus && newAnchor) {\n transformedOperation.newProperties = {\n focus: newFocus,\n anchor: newAnchor,\n }\n }\n }\n }\n // // Assign fresh point objects (we don't want to mutate the original ones)\n return transformedOperation\n}\n\n// Helper functions for editor.apply above\n\nconst shouldMerge = (op: Operation, prev: Operation | undefined): boolean => {\n if (op.type === 'set_selection') {\n return true\n }\n\n // Text input\n if (\n prev &&\n op.type === 'insert_text' &&\n prev.type === 'insert_text' &&\n op.offset === prev.offset + prev.text.length &&\n Path.equals(op.path, prev.path) &&\n op.text !== ' ' // Tokenize between words\n ) {\n return true\n }\n\n // Text deletion\n if (\n prev &&\n op.type === 'remove_text' &&\n prev.type === 'remove_text' &&\n op.offset + op.text.length === prev.offset &&\n Path.equals(op.path, prev.path)\n ) {\n return true\n }\n\n // Don't merge\n return false\n}\n\nconst shouldOverwrite = (\n op: Operation,\n prev: Operation | undefined,\n): boolean => {\n if (prev && op.type === 'set_selection' && prev.type === 'set_selection') {\n return true\n }\n\n return false\n}\n\nconst shouldClear = (op: Operation): boolean => {\n if (op.type === 'set_selection') {\n return false\n }\n\n return true\n}\n\nexport function withoutSaving(editor: Editor, fn: () => void): void {\n const prev = isSaving(editor)\n SAVING.set(editor, false)\n fn()\n SAVING.set(editor, prev)\n}\n\nfunction createSelectOperation(editor: Editor): SelectionOperation {\n return {\n type: 'set_selection',\n properties: {...editor.selection},\n newProperties: {...editor.selection},\n }\n}\n\nfunction findOperationTargetBlock(\n editor: PortableTextSlateEditor,\n operation: Operation,\n): Descendant | undefined {\n let block: Descendant | undefined\n if (operation.type === 'set_selection' && editor.selection) {\n block = editor.children[editor.selection.focus.path[0]]\n } else if ('path' in operation) {\n block = editor.children[operation.path[0]]\n }\n return block\n}\n","import {insert, setIfMissing, unset, type Patch} from '@portabletext/patches'\nimport {\n Editor,\n type Descendant,\n type InsertNodeOperation,\n type InsertTextOperation,\n type MergeNodeOperation,\n type MoveNodeOperation,\n type Operation,\n type RemoveNodeOperation,\n type RemoveTextOperation,\n type SetNodeOperation,\n type SplitNodeOperation,\n} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {createApplyPatch} from '../../utils/applyPatch'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue, isEqualToEmptyEditor} from '../../utils/values'\nimport {\n IS_PROCESSING_REMOTE_CHANGES,\n KEY_TO_VALUE_ELEMENT,\n} from '../../utils/weakMaps'\nimport {withRemoteChanges} from '../../utils/withChanges'\nimport {\n isPatching,\n PATCHING,\n withoutPatching,\n} from '../../utils/withoutPatching'\nimport type {EditorActor} from '../editor-machine'\nimport {withoutSaving} from './createWithUndoRedo'\n\nconst debug = debugWithName('plugin:withPatches')\nconst debugVerbose = false\n\nexport interface PatchFunctions {\n insertNodePatch: (\n editor: PortableTextSlateEditor,\n operation: InsertNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n insertTextPatch: (\n editor: PortableTextSlateEditor,\n operation: InsertTextOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n mergeNodePatch: (\n editor: PortableTextSlateEditor,\n operation: MergeNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n moveNodePatch: (\n editor: PortableTextSlateEditor,\n operation: MoveNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n removeNodePatch: (\n editor: PortableTextSlateEditor,\n operation: RemoveNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n removeTextPatch: (\n editor: PortableTextSlateEditor,\n operation: RemoveTextOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n setNodePatch: (\n editor: PortableTextSlateEditor,\n operation: SetNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n splitNodePatch: (\n editor: PortableTextSlateEditor,\n operation: SplitNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n}\n\ninterface Options {\n editorActor: EditorActor\n patchFunctions: PatchFunctions\n readOnly: boolean\n schemaTypes: PortableTextMemberSchemaTypes\n}\n\nexport function createWithPatches({\n editorActor,\n patchFunctions,\n readOnly,\n schemaTypes,\n}: Options): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n // The previous editor children are needed to figure out the _key of deleted nodes\n // The editor.children would no longer contain that information if the node is already deleted.\n let previousChildren: Descendant[]\n\n const applyPatch = createApplyPatch(schemaTypes)\n\n return function withPatches(editor: PortableTextSlateEditor) {\n IS_PROCESSING_REMOTE_CHANGES.set(editor, false)\n PATCHING.set(editor, true)\n previousChildren = [...editor.children]\n\n const {apply} = editor\n let bufferedPatches: Patch[] = []\n\n const handleBufferedRemotePatches = () => {\n if (bufferedPatches.length === 0) {\n return\n }\n const patches = bufferedPatches\n bufferedPatches = []\n let changed = false\n withRemoteChanges(editor, () => {\n Editor.withoutNormalizing(editor, () => {\n withoutPatching(editor, () => {\n withoutSaving(editor, () => {\n patches.forEach((patch) => {\n if (debug.enabled)\n debug(`Handling remote patch ${JSON.stringify(patch)}`)\n changed = applyPatch(editor, patch)\n })\n })\n })\n })\n if (changed) {\n editor.normalize()\n editor.onChange()\n }\n })\n }\n\n const handlePatches = ({patches}: {patches: Patch[]}) => {\n const remotePatches = patches.filter((p) => p.origin !== 'local')\n if (remotePatches.length === 0) {\n return\n }\n bufferedPatches = bufferedPatches.concat(remotePatches)\n handleBufferedRemotePatches()\n }\n\n editor.subscriptions.push(() => {\n debug('Subscribing to remote patches')\n const sub = editorActor.on('patches', handlePatches)\n return () => {\n debug('Unsubscribing to remote patches')\n sub.unsubscribe()\n }\n })\n\n editor.apply = (operation: Operation): void | Editor => {\n if (readOnly) {\n apply(operation)\n return editor\n }\n let patches: Patch[] = []\n\n // Update previous children here before we apply\n previousChildren = editor.children\n\n const editorWasEmpty = isEqualToEmptyEditor(previousChildren, schemaTypes)\n\n // Apply the operation\n apply(operation)\n\n const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes)\n\n if (!isPatching(editor)) {\n if (debugVerbose && debug.enabled)\n debug(\n `Editor is not producing patch for operation ${operation.type}`,\n operation,\n )\n return editor\n }\n\n // If the editor was empty and now isn't, insert the placeholder into it.\n if (\n editorWasEmpty &&\n !editorIsEmpty &&\n operation.type !== 'set_selection'\n ) {\n patches.push(insert(previousChildren, 'before', [0]))\n }\n\n switch (operation.type) {\n case 'insert_text':\n patches = [\n ...patches,\n ...patchFunctions.insertTextPatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'remove_text':\n patches = [\n ...patches,\n ...patchFunctions.removeTextPatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'remove_node':\n patches = [\n ...patches,\n ...patchFunctions.removeNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'split_node':\n patches = [\n ...patches,\n ...patchFunctions.splitNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'insert_node':\n patches = [\n ...patches,\n ...patchFunctions.insertNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'set_node':\n patches = [\n ...patches,\n ...patchFunctions.setNodePatch(editor, operation, previousChildren),\n ]\n break\n case 'merge_node':\n patches = [\n ...patches,\n ...patchFunctions.mergeNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'move_node':\n patches = [\n ...patches,\n ...patchFunctions.moveNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n default:\n // Do nothing\n }\n\n // Unset the value if a operation made the editor empty\n if (\n !editorWasEmpty &&\n editorIsEmpty &&\n ['merge_node', 'set_node', 'remove_text', 'remove_node'].includes(\n operation.type,\n )\n ) {\n patches = [...patches, unset([])]\n editorActor.send({\n type: 'unset',\n previousValue: fromSlateValue(\n previousChildren,\n schemaTypes.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n })\n }\n\n // Prepend patches with setIfMissing if going from empty editor to something involving a patch.\n if (editorWasEmpty && patches.length > 0) {\n patches = [setIfMissing([], []), ...patches]\n }\n\n // Emit all patches\n if (patches.length > 0) {\n patches.forEach((patch) => {\n editorActor.send({\n type: 'patch',\n patch: {...patch, origin: 'local'},\n })\n })\n }\n return editor\n }\n return editor\n }\n}\n","import {Editor, Path} from 'slate'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport {debugWithName} from '../../utils/debug'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\n\nconst debug = debugWithName('plugin:withPlaceholderBlock')\n\n/**\n * Keep a \"placeholder\" block present when the editor is empty\n *\n */\nexport function createWithPlaceholderBlock(): (\n editor: PortableTextSlateEditor,\n) => PortableTextSlateEditor {\n return function withPlaceholderBlock(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {apply} = editor\n\n editor.apply = (op) => {\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(op)\n return\n }\n\n if (op.type === 'remove_node') {\n const node = op.node as SlateTextBlock | VoidElement\n if (op.path[0] === 0 && Editor.isVoid(editor, node)) {\n // Check next path, if it exists, do nothing\n const nextPath = Path.next(op.path)\n // Is removing the first block which is a void (not a text block), add a new empty text block in it, if there is no other element in the next path\n if (!editor.children[nextPath[0]]) {\n debug('Adding placeholder block')\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n )\n }\n }\n }\n apply(op)\n }\n return editor\n }\n}\n","import {Editor, Path, Text as SlateText, Transforms, type Node} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextBlockStyle')\n\nexport function createWithPortableTextBlockStyle(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n const defaultStyle = types.styles[0].value\n return function withPortableTextBlockStyle(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n // Extend Slate's default normalization to reset split node to normal style\n // if there is no text at the right end of the split.\n const {normalizeNode} = editor\n\n editor.normalizeNode = (nodeEntry) => {\n const [, path] = nodeEntry\n\n for (const op of editor.operations) {\n if (\n op.type === 'split_node' &&\n op.path.length === 1 &&\n editor.isTextBlock(op.properties) &&\n op.properties.style !== defaultStyle &&\n op.path[0] === path[0] &&\n !Path.equals(path, op.path)\n ) {\n const [child] = Editor.node(editor, [op.path[0] + 1, 0])\n if (SlateText.isText(child) && child.text === '') {\n debug(`Normalizing split node to ${defaultStyle} style`, op)\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {style: defaultStyle},\n {at: [op.path[0] + 1], voids: false},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n normalizeNode(nodeEntry)\n }\n\n editor.pteHasBlockStyle = (style: string): boolean => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node) && node.style === style,\n }),\n ]\n if (selectedBlocks.length > 0) {\n return true\n }\n return false\n }\n\n editor.pteToggleBlockStyle = (blockStyle: string): void => {\n if (!editor.selection) {\n return\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n }),\n ]\n selectedBlocks.forEach(([node, path]) => {\n if (editor.isTextBlock(node) && node.style === blockStyle) {\n debug(`Unsetting block style '${blockStyle}'`)\n Transforms.setNodes(\n editor,\n {...node, style: defaultStyle} as Partial<Node>,\n {\n at: path,\n },\n )\n } else {\n if (blockStyle) {\n debug(`Setting style '${blockStyle}'`)\n } else {\n debug('Setting default style', defaultStyle)\n }\n Transforms.setNodes(\n editor,\n {\n ...node,\n style: blockStyle || defaultStyle,\n } as Partial<Node>,\n {at: path},\n )\n }\n })\n editor.onChange()\n }\n return editor\n }\n}\n","import {Editor, Element, Text, Transforms, type Node} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\n\nconst debug = debugWithName('plugin:withPortableTextLists')\nconst MAX_LIST_LEVEL = 10\n\nexport function createWithPortableTextLists(\n types: PortableTextMemberSchemaTypes,\n) {\n return function withPortableTextLists(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n editor.pteToggleListItem = (listItemStyle: string) => {\n const isActive = editor.pteHasListStyle(listItemStyle)\n if (isActive) {\n debug(`Remove list item '${listItemStyle}'`)\n editor.pteUnsetListItem(listItemStyle)\n } else {\n debug(`Add list item '${listItemStyle}'`)\n editor.pteSetListItem(listItemStyle)\n }\n }\n\n editor.pteUnsetListItem = (listItemStyle: string) => {\n if (!editor.selection) {\n return\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) =>\n Element.isElement(node) && node._type === types.block.name,\n }),\n ]\n selectedBlocks.forEach(([node, path]) => {\n if (editor.isListBlock(node)) {\n const {listItem, level, ...rest} = node\n const newNode = {\n ...rest,\n listItem: undefined,\n level: undefined,\n } as Partial<Node>\n debug(`Unsetting list '${listItemStyle}'`)\n Transforms.setNodes(editor, newNode, {at: path})\n }\n })\n }\n\n editor.pteSetListItem = (listItemStyle: string) => {\n if (!editor.selection) {\n return\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n }),\n ]\n selectedBlocks.forEach(([node, path]) => {\n debug(`Setting list '${listItemStyle}'`)\n Transforms.setNodes(\n editor,\n {\n ...node,\n level: 1,\n listItem: listItemStyle || (types.lists[0] && types.lists[0].value),\n } as Partial<Node>,\n {at: path},\n )\n })\n }\n\n editor.pteEndList = () => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) =>\n Element.isElement(node) &&\n editor.isListBlock(node) &&\n node.children.length === 1 &&\n Text.isText(node.children[0]) &&\n node.children[0].text === '',\n }),\n ]\n if (selectedBlocks.length === 0) {\n return false\n }\n selectedBlocks.forEach(([node, path]) => {\n if (Element.isElement(node)) {\n debug('Unset list')\n Transforms.setNodes(\n editor,\n {\n ...node,\n level: undefined,\n listItem: undefined,\n },\n {at: path},\n )\n }\n })\n return true // Note: we are exiting the plugin chain by not returning editor (or hotkey plugin 'enter' will fire)\n }\n\n editor.pteIncrementBlockLevels = (reverse?: boolean): boolean => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => !!editor.isListBlock(node),\n }),\n ]\n if (selectedBlocks.length === 0) {\n return false\n }\n selectedBlocks.forEach(([node, path]) => {\n if (editor.isListBlock(node)) {\n let level = node.level || 1\n if (reverse) {\n level--\n debug(\n 'Decrementing list level',\n Math.min(MAX_LIST_LEVEL, Math.max(1, level)),\n )\n } else {\n level++\n debug(\n 'Incrementing list level',\n Math.min(MAX_LIST_LEVEL, Math.max(1, level)),\n )\n }\n Transforms.setNodes(\n editor,\n {level: Math.min(MAX_LIST_LEVEL, Math.max(1, level))},\n {at: path},\n )\n }\n })\n return true\n }\n\n editor.pteHasListStyle = (listStyle: string): boolean => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n }),\n ]\n\n if (selectedBlocks.length > 0) {\n return selectedBlocks.every(\n ([node]) => editor.isListBlock(node) && node.listItem === listStyle,\n )\n }\n return false\n }\n\n return editor\n }\n}\n","import type {BaseRange} from 'slate'\nimport type {\n EditorSelection,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {\n toPortableTextRange,\n type ObjectWithKeyAndType,\n} from '../../utils/ranges'\nimport {SLATE_TO_PORTABLE_TEXT_RANGE} from '../../utils/weakMaps'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextSelections')\nconst debugVerbose = debug.enabled && false\n\n// This plugin will make sure that we emit a PT selection whenever the editor has changed.\nexport function createWithPortableTextSelections(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n let prevSelection: BaseRange | null = null\n return function withPortableTextSelections(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const emitPortableTextSelection = () => {\n if (prevSelection !== editor.selection) {\n let ptRange: EditorSelection = null\n if (editor.selection) {\n const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection)\n if (existing) {\n ptRange = existing\n } else {\n const value = editor.children satisfies ObjectWithKeyAndType[]\n ptRange = toPortableTextRange(value, editor.selection, types)\n SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange)\n }\n }\n if (debugVerbose) {\n debug(\n `Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(\n editor.selection,\n )})`,\n )\n }\n if (ptRange) {\n editorActor.send({type: 'selection', selection: ptRange})\n } else {\n editorActor.send({type: 'selection', selection: null})\n }\n }\n prevSelection = editor.selection\n }\n\n const {onChange} = editor\n editor.onChange = () => {\n const hasChanges = editor.operations.length > 0\n onChange()\n if (hasChanges) {\n emitPortableTextSelection()\n }\n }\n return editor\n }\n}\n","import {\n isPortableTextListBlock,\n isPortableTextSpan,\n isPortableTextTextBlock,\n type PortableTextListBlock,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport {Transforms, type Element} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withSchemaTypes')\n/**\n * This plugin makes sure that schema types are recognized properly by Slate as blocks, voids, inlines\n *\n */\nexport function createWithSchemaTypes({\n editorActor,\n schemaTypes,\n}: {\n editorActor: EditorActor\n schemaTypes: PortableTextMemberSchemaTypes\n}) {\n return function withSchemaTypes(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n editor.isTextBlock = (value: unknown): value is PortableTextTextBlock => {\n return (\n isPortableTextTextBlock(value) && value._type === schemaTypes.block.name\n )\n }\n editor.isTextSpan = (value: unknown): value is PortableTextSpan => {\n return isPortableTextSpan(value) && value._type === schemaTypes.span.name\n }\n editor.isListBlock = (value: unknown): value is PortableTextListBlock => {\n return (\n isPortableTextListBlock(value) && value._type === schemaTypes.block.name\n )\n }\n editor.isVoid = (element: Element): boolean => {\n return (\n schemaTypes.block.name !== element._type &&\n (schemaTypes.blockObjects\n .map((obj) => obj.name)\n .includes(element._type) ||\n schemaTypes.inlineObjects\n .map((obj) => obj.name)\n .includes(element._type))\n )\n }\n editor.isInline = (element: Element): boolean => {\n const inlineSchemaTypes = schemaTypes.inlineObjects.map((obj) => obj.name)\n return (\n inlineSchemaTypes.includes(element._type) &&\n '__inline' in element &&\n element.__inline === true\n )\n }\n\n // Extend Slate's default normalization\n const {normalizeNode} = editor\n editor.normalizeNode = (entry) => {\n const [node, path] = entry\n\n // If text block children node is missing _type, set it to the span type\n if (node._type === undefined && path.length === 2) {\n debug('Setting span type on text node without a type')\n const span = node as PortableTextSpan\n const key =\n span._key || editorActor.getSnapshot().context.keyGenerator()\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {...span, _type: schemaTypes.span.name, _key: key},\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n // catches cases when the children are missing keys but excludes it when the normalize is running the node as the editor object\n if (node._key === undefined && (path.length === 1 || path.length === 2)) {\n debug('Setting missing key on child node without a key')\n const key = editorActor.getSnapshot().context.keyGenerator()\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {_key: key}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n normalizeNode(entry)\n }\n return editor\n }\n}\n","import {Editor, Range, Text, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toSlateValue} from '../../utils/values'\nimport type {EditorActor} from '../editor-machine'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('plugin:withUtils')\n\ninterface Options {\n editorActor: EditorActor\n schemaTypes: PortableTextMemberSchemaTypes\n portableTextEditor: PortableTextEditor\n}\n/**\n * This plugin makes various util commands available in the editor\n *\n */\nexport function createWithUtils({\n editorActor,\n schemaTypes,\n portableTextEditor,\n}: Options) {\n return function withUtils(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n // Expands the the selection to wrap around the word the focus is at\n editor.pteExpandToWord = () => {\n const {selection} = editor\n if (selection && !Range.isExpanded(selection)) {\n const [textNode] = Editor.node(editor, selection.focus, {depth: 2})\n if (!textNode || !Text.isText(textNode) || textNode.text.length === 0) {\n debug(`pteExpandToWord: Can't expand to word here`)\n return\n }\n const {focus} = selection\n const focusOffset = focus.offset\n const charsBefore = textNode.text.slice(0, focusOffset)\n const charsAfter = textNode.text.slice(focusOffset, -1)\n const isEmpty = (str: string) => str.match(/\\s/g)\n const whiteSpaceBeforeIndex = charsBefore\n .split('')\n .reverse()\n .findIndex((str) => isEmpty(str))\n const newStartOffset =\n whiteSpaceBeforeIndex > -1\n ? charsBefore.length - whiteSpaceBeforeIndex\n : 0\n const whiteSpaceAfterIndex = charsAfter\n .split('')\n .findIndex((obj) => isEmpty(obj))\n const newEndOffset =\n charsBefore.length +\n (whiteSpaceAfterIndex > -1\n ? whiteSpaceAfterIndex\n : charsAfter.length + 1)\n if (\n !(\n newStartOffset === newEndOffset ||\n Number.isNaN(newStartOffset) ||\n Number.isNaN(newEndOffset)\n )\n ) {\n debug('pteExpandToWord: Expanding to focused word')\n Transforms.setSelection(editor, {\n anchor: {...selection.anchor, offset: newStartOffset},\n focus: {...selection.focus, offset: newEndOffset},\n })\n return\n }\n debug(`pteExpandToWord: Can't expand to word here`)\n }\n }\n\n editor.pteCreateTextBlock = (options: {\n decorators: Array<string>\n listItem?: string\n level?: number\n }) => {\n const block = toSlateValue(\n [\n {\n _type: schemaTypes.block.name,\n _key: editorActor.getSnapshot().context.keyGenerator(),\n style: schemaTypes.styles[0].value || 'normal',\n ...(options.listItem ? {listItem: options.listItem} : {}),\n ...(options.level ? {level: options.level} : {}),\n markDefs: [],\n children: [\n {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: '',\n marks: options.decorators.filter((decorator) =>\n schemaTypes.decorators.find(({value}) => value === decorator),\n ),\n },\n ],\n },\n ],\n portableTextEditor,\n )[0]\n return block\n }\n return editor\n }\n}\n","import {isPortableTextSpan, isPortableTextTextBlock} from '@sanity/types'\nimport {isHotkey} from 'is-hotkey-esm'\nimport type {KeyboardEvent} from 'react'\nimport {Editor, Node, Path, Range, Transforms} from 'slate'\nimport type {ReactEditor} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport type {HotkeyOptions} from '../../types/options'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('plugin:withHotKeys')\n\nconst DEFAULT_HOTKEYS: HotkeyOptions = {\n marks: {\n 'mod+b': 'strong',\n 'mod+i': 'em',\n 'mod+u': 'underline',\n \"mod+'\": 'code',\n },\n custom: {},\n}\n\n/**\n * This plugin takes care of all hotkeys in the editor\n *\n */\nexport function createWithHotkeys(\n editorActor: EditorActor,\n portableTextEditor: PortableTextEditor,\n hotkeysFromOptions?: HotkeyOptions,\n): (editor: PortableTextSlateEditor & ReactEditor) => any {\n const reservedHotkeys = ['enter', 'tab', 'shift', 'delete', 'end']\n const activeHotkeys = hotkeysFromOptions || DEFAULT_HOTKEYS // TODO: Merge where possible? A union?\n return function withHotKeys(editor: PortableTextSlateEditor & ReactEditor) {\n editor.pteWithHotKeys = (event: KeyboardEvent<HTMLDivElement>): void => {\n // Wire up custom marks hotkeys\n Object.keys(activeHotkeys).forEach((cat) => {\n if (cat === 'marks') {\n for (const hotkey in activeHotkeys[cat]) {\n if (reservedHotkeys.includes(hotkey)) {\n throw new Error(`The hotkey ${hotkey} is reserved!`)\n }\n if (isHotkey(hotkey, event.nativeEvent)) {\n event.preventDefault()\n const possibleMark = activeHotkeys[cat]\n if (possibleMark) {\n const mark = possibleMark[hotkey]\n debug(`HotKey ${hotkey} to toggle ${mark}`)\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.toggle',\n decorator: mark,\n },\n editor,\n })\n }\n }\n }\n }\n if (cat === 'custom') {\n for (const hotkey in activeHotkeys[cat]) {\n if (reservedHotkeys.includes(hotkey)) {\n throw new Error(`The hotkey ${hotkey} is reserved!`)\n }\n if (isHotkey(hotkey, event.nativeEvent)) {\n const possibleCommand = activeHotkeys[cat]\n if (possibleCommand) {\n const command = possibleCommand[hotkey]\n command(event, portableTextEditor)\n }\n }\n }\n }\n })\n\n const isEnter = isHotkey('enter', event.nativeEvent)\n const isTab = isHotkey('tab', event.nativeEvent)\n const isShiftEnter = isHotkey('shift+enter', event.nativeEvent)\n const isShiftTab = isHotkey('shift+tab', event.nativeEvent)\n const isArrowDown = isHotkey('down', event.nativeEvent)\n const isArrowUp = isHotkey('up', event.nativeEvent)\n\n // Check if the user is in a void block, in that case, add an empty text block below if there is no next block\n if (isArrowDown && editor.selection) {\n const focusBlock = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n ) as SlateTextBlock | VoidElement\n\n if (focusBlock && Editor.isVoid(editor, focusBlock)) {\n const nextPath = Path.next(editor.selection.focus.path.slice(0, 1))\n const nextBlock = Node.has(editor, nextPath)\n if (!nextBlock) {\n Transforms.insertNodes(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n {\n at: nextPath,\n },\n )\n Transforms.select(editor, {path: [...nextPath, 0], offset: 0})\n editor.onChange()\n return\n }\n }\n }\n if (isArrowUp && editor.selection) {\n const isFirstBlock = editor.selection.focus.path[0] === 0\n const focusBlock = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n ) as SlateTextBlock | VoidElement\n\n if (isFirstBlock && focusBlock && Editor.isVoid(editor, focusBlock)) {\n Transforms.insertNodes(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n {\n at: [0],\n },\n )\n Transforms.select(editor, {path: [0, 0], offset: 0})\n editor.onChange()\n return\n }\n }\n\n // Tab for lists\n // Only steal tab when we are on a plain text span or we are at the start of the line (fallback if the whole block is annotated or contains a single inline object)\n // Otherwise tab is reserved for accessability for buttons etc.\n if ((isTab || isShiftTab) && editor.selection) {\n const [focusChild] = Editor.node(editor, editor.selection.focus, {\n depth: 2,\n })\n const [focusBlock] = isPortableTextSpan(focusChild)\n ? Editor.node(editor, editor.selection.focus, {depth: 1})\n : []\n const hasAnnotationFocus =\n focusChild &&\n isPortableTextTextBlock(focusBlock) &&\n isPortableTextSpan(focusChild) &&\n (focusChild.marks || ([] as string[])).filter((m) =>\n (focusBlock.markDefs || []).map((def) => def._key).includes(m),\n ).length > 0\n const [start] = Range.edges(editor.selection)\n const atStartOfNode = Editor.isStart(editor, start, start.path)\n\n if (\n focusChild &&\n isPortableTextSpan(focusChild) &&\n (!hasAnnotationFocus || atStartOfNode) &&\n editor.pteIncrementBlockLevels(isShiftTab)\n ) {\n event.preventDefault()\n }\n }\n\n // Deal with enter key combos\n if (isEnter && !isShiftEnter && editor.selection) {\n const focusBlockPath = editor.selection.focus.path.slice(0, 1)\n const focusBlock = Node.descendant(editor, focusBlockPath) as\n | SlateTextBlock\n | VoidElement\n\n // List item enter key\n if (editor.isListBlock(focusBlock)) {\n if (editor.pteEndList()) {\n event.preventDefault()\n }\n return\n }\n }\n }\n return editor\n }\n}\n","import {insert, set, setIfMissing, unset} from '@portabletext/patches'\nimport {\n isPortableTextTextBlock,\n type PortableTextBlock,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport {flatten, isPlainObject, uniq} from 'lodash'\nimport type {\n InvalidValueResolution,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\n\nexport interface Validation {\n valid: boolean\n resolution: InvalidValueResolution | null\n value: PortableTextBlock[] | undefined\n}\n\nexport function validateValue(\n value: PortableTextBlock[] | undefined,\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\n): Validation {\n let resolution: InvalidValueResolution | null = null\n let valid = true\n const validChildTypes = [\n types.span.name,\n ...types.inlineObjects.map((t) => t.name),\n ]\n const validBlockTypes = [\n types.block.name,\n ...types.blockObjects.map((t) => t.name),\n ]\n\n // Undefined is allowed\n if (value === undefined) {\n return {valid: true, resolution: null, value}\n }\n // Only lengthy arrays are allowed in the editor.\n if (!Array.isArray(value) || value.length === 0) {\n return {\n valid: false,\n resolution: {\n patches: [unset([])],\n description:\n 'Editor value must be an array of Portable Text blocks, or undefined.',\n action: 'Unset the value',\n item: value,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.not-an-array.description',\n action: 'inputs.portable-text.invalid-value.not-an-array.action',\n },\n },\n value,\n }\n }\n if (\n value.some((blk: PortableTextBlock, index: number): boolean => {\n // Is the block an object?\n if (!isPlainObject(blk)) {\n resolution = {\n patches: [unset([index])],\n description: `Block must be an object, got ${String(blk)}`,\n action: `Unset invalid item`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.not-an-object.description',\n action: 'inputs.portable-text.invalid-value.not-an-object.action',\n values: {index},\n },\n }\n return true\n }\n // Test that every block has a _key prop\n if (!blk._key || typeof blk._key !== 'string') {\n resolution = {\n patches: [set({...blk, _key: keyGenerator()}, [index])],\n description: `Block at index ${index} is missing required _key.`,\n action: 'Set the block with a random _key value',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-key.description',\n action: 'inputs.portable-text.invalid-value.missing-key.action',\n values: {index},\n },\n }\n return true\n }\n // Test that every block has valid _type\n if (!blk._type || !validBlockTypes.includes(blk._type)) {\n // Special case where block type is set to default 'block', but the block type is named something else according to the schema.\n if (blk._type === 'block') {\n const currentBlockTypeName = types.block.name\n resolution = {\n patches: [\n set({...blk, _type: currentBlockTypeName}, [{_key: blk._key}]),\n ],\n description: `Block with _key '${blk._key}' has invalid type name '${blk._type}'. According to the schema, the block type name is '${currentBlockTypeName}'`,\n action: `Use type '${currentBlockTypeName}'`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.incorrect-block-type.description',\n action:\n 'inputs.portable-text.invalid-value.incorrect-block-type.action',\n values: {key: blk._key, expectedTypeName: currentBlockTypeName},\n },\n }\n return true\n }\n\n // If the block has no `_type`, but aside from that is a valid Portable Text block\n if (\n !blk._type &&\n isPortableTextTextBlock({...blk, _type: types.block.name})\n ) {\n resolution = {\n patches: [\n set({...blk, _type: types.block.name}, [{_key: blk._key}]),\n ],\n description: `Block with _key '${blk._key}' is missing a type name. According to the schema, the block type name is '${types.block.name}'`,\n action: `Use type '${types.block.name}'`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-block-type.description',\n action:\n 'inputs.portable-text.invalid-value.missing-block-type.action',\n values: {key: blk._key, expectedTypeName: types.block.name},\n },\n }\n return true\n }\n\n if (!blk._type) {\n resolution = {\n patches: [unset([{_key: blk._key}])],\n description: `Block with _key '${blk._key}' is missing an _type property`,\n action: 'Remove the block',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-type.description',\n action: 'inputs.portable-text.invalid-value.missing-type.action',\n values: {key: blk._key},\n },\n }\n return true\n }\n\n resolution = {\n patches: [unset([{_key: blk._key}])],\n description: `Block with _key '${blk._key}' has invalid _type '${blk._type}'`,\n action: 'Remove the block',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.disallowed-type.description',\n action: 'inputs.portable-text.invalid-value.disallowed-type.action',\n values: {key: blk._key, typeName: blk._type},\n },\n }\n return true\n }\n\n // Test regular text blocks\n if (blk._type === types.block.name) {\n const textBlock = blk as PortableTextTextBlock\n // Test that it has a valid children property (array)\n if (textBlock.children && !Array.isArray(textBlock.children)) {\n resolution = {\n patches: [set({children: []}, [{_key: textBlock._key}])],\n description: `Text block with _key '${textBlock._key}' has a invalid required property 'children'.`,\n action: 'Reset the children property',\n item: textBlock,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-or-invalid-children.description',\n action:\n 'inputs.portable-text.invalid-value.missing-or-invalid-children.action',\n values: {key: textBlock._key},\n },\n }\n return true\n }\n // Test that children is set and lengthy\n if (\n textBlock.children === undefined ||\n (Array.isArray(textBlock.children) && textBlock.children.length === 0)\n ) {\n const newSpan = {\n _type: types.span.name,\n _key: keyGenerator(),\n text: '',\n marks: [],\n }\n resolution = {\n autoResolve: true,\n patches: [\n setIfMissing([], [{_key: blk._key}, 'children']),\n insert([newSpan], 'after', [{_key: blk._key}, 'children', 0]),\n ],\n description: `Children for text block with _key '${blk._key}' is empty.`,\n action: 'Insert an empty text',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.empty-children.description',\n action:\n 'inputs.portable-text.invalid-value.empty-children.action',\n values: {key: blk._key},\n },\n }\n return true\n }\n\n const allUsedMarks = uniq(\n flatten(\n textBlock.children\n .filter((cld) => cld._type === types.span.name)\n .map((cld) => cld.marks || []),\n ) as string[],\n )\n\n // Test that all markDefs are in use (remove orphaned markDefs)\n if (Array.isArray(blk.markDefs) && blk.markDefs.length > 0) {\n const unusedMarkDefs: string[] = uniq(\n blk.markDefs\n .map((def) => def._key)\n .filter((key) => !allUsedMarks.includes(key)),\n )\n if (unusedMarkDefs.length > 0) {\n resolution = {\n autoResolve: true,\n patches: unusedMarkDefs.map((markDefKey) =>\n unset([{_key: blk._key}, 'markDefs', {_key: markDefKey}]),\n ),\n description: `Block contains orphaned data (unused mark definitions): ${unusedMarkDefs.join(\n ', ',\n )}.`,\n action: 'Remove unused mark definition item',\n item: blk,\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.orphaned-mark-defs.description',\n action:\n 'inputs.portable-text.invalid-value.orphaned-mark-defs.action',\n values: {\n key: blk._key,\n unusedMarkDefs: unusedMarkDefs.map((m) => m.toString()),\n },\n },\n }\n return true\n }\n }\n\n // Test that every annotation mark used has a definition\n const annotationMarks = allUsedMarks.filter(\n (mark) => !types.decorators.map((dec) => dec.value).includes(mark),\n )\n const orphanedMarks = annotationMarks.filter(\n (mark) =>\n textBlock.markDefs === undefined ||\n !textBlock.markDefs.find((def) => def._key === mark),\n )\n if (orphanedMarks.length > 0) {\n const spanChildren = textBlock.children.filter(\n (cld) =>\n cld._type === types.span.name &&\n Array.isArray(cld.marks) &&\n cld.marks.some((mark) => orphanedMarks.includes(mark)),\n ) as PortableTextSpan[]\n if (spanChildren) {\n const orphaned = orphanedMarks.join(', ')\n resolution = {\n autoResolve: true,\n patches: spanChildren.map((child) => {\n return set(\n (child.marks || []).filter(\n (cMrk) => !orphanedMarks.includes(cMrk),\n ),\n [{_key: blk._key}, 'children', {_key: child._key}, 'marks'],\n )\n }),\n description: `Block with _key '${blk._key}' contains marks (${orphaned}) not supported by the current content model.`,\n action: 'Remove invalid marks',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.orphaned-marks.description',\n action:\n 'inputs.portable-text.invalid-value.orphaned-marks.action',\n values: {\n key: blk._key,\n orphanedMarks: orphanedMarks.map((m) => m.toString()),\n },\n },\n }\n return true\n }\n }\n\n // Test every child\n if (\n textBlock.children.some((child, cIndex: number) => {\n if (!isPlainObject(child)) {\n resolution = {\n patches: [unset([{_key: blk._key}, 'children', cIndex])],\n description: `Child at index '${cIndex}' in block with key '${blk._key}' is not an object.`,\n action: 'Remove the item',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.non-object-child.description',\n action:\n 'inputs.portable-text.invalid-value.non-object-child.action',\n values: {key: blk._key, index: cIndex},\n },\n }\n return true\n }\n\n if (!child._key || typeof child._key !== 'string') {\n const newChild = {...child, _key: keyGenerator()}\n resolution = {\n autoResolve: true,\n patches: [\n set(newChild, [{_key: blk._key}, 'children', cIndex]),\n ],\n description: `Child at index ${cIndex} is missing required _key in block with _key ${blk._key}.`,\n action: 'Set a new random _key on the object',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-child-key.description',\n action:\n 'inputs.portable-text.invalid-value.missing-child-key.action',\n values: {key: blk._key, index: cIndex},\n },\n }\n return true\n }\n\n // Verify that children have valid types\n if (!child._type) {\n resolution = {\n patches: [\n unset([{_key: blk._key}, 'children', {_key: child._key}]),\n ],\n description: `Child with _key '${child._key}' in block with key '${blk._key}' is missing '_type' property.`,\n action: 'Remove the object',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-child-type.description',\n action:\n 'inputs.portable-text.invalid-value.missing-child-type.action',\n values: {key: blk._key, childKey: child._key},\n },\n }\n return true\n }\n\n if (!validChildTypes.includes(child._type)) {\n resolution = {\n patches: [\n unset([{_key: blk._key}, 'children', {_key: child._key}]),\n ],\n description: `Child with _key '${child._key}' in block with key '${blk._key}' has invalid '_type' property (${child._type}).`,\n action: 'Remove the object',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.disallowed-child-type.description',\n action:\n 'inputs.portable-text.invalid-value.disallowed-child-type.action',\n values: {\n key: blk._key,\n childKey: child._key,\n childType: child._type,\n },\n },\n }\n return true\n }\n\n // Verify that spans have .text property that is a string\n if (\n child._type === types.span.name &&\n typeof child.text !== 'string'\n ) {\n resolution = {\n patches: [\n set({...child, text: ''}, [\n {_key: blk._key},\n 'children',\n {_key: child._key},\n ]),\n ],\n description: `Child with _key '${child._key}' in block with key '${blk._key}' has missing or invalid text property!`,\n action: `Write an empty text property to the object`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.invalid-span-text.description',\n action:\n 'inputs.portable-text.invalid-value.invalid-span-text.action',\n values: {key: blk._key, childKey: child._key},\n },\n }\n return true\n }\n return false\n })\n ) {\n valid = false\n }\n }\n return false\n })\n ) {\n valid = false\n }\n return {valid, resolution, value}\n}\n","import {htmlToBlocks, normalizeBlock} from '@sanity/block-tools'\nimport type {PortableTextBlock, PortableTextChild} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {Editor, Range, Transforms, type Descendant, type Node} from 'slate'\nimport {ReactEditor} from 'slate-react'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {validateValue} from '../../utils/validateValue'\nimport {\n fromSlateValue,\n isEqualToEmptyEditor,\n toSlateValue,\n} from '../../utils/values'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withInsertData')\n\n/**\n * This plugin handles copy/paste in the editor\n *\n */\nexport function createWithInsertData(\n editorActor: EditorActor,\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n return function withInsertData(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const blockTypeName = schemaTypes.block.name\n const spanTypeName = schemaTypes.span.name\n const whitespaceOnPasteMode =\n schemaTypes.block.options.unstable_whitespaceOnPasteMode\n\n const toPlainText = (blocks: PortableTextBlock[]) => {\n return blocks\n .map((block) => {\n if (editor.isTextBlock(block)) {\n return block.children\n .map((child: PortableTextChild) => {\n if (child._type === spanTypeName) {\n return child.text\n }\n return `[${\n schemaTypes.inlineObjects.find((t) => t.name === child._type)\n ?.title || 'Object'\n }]`\n })\n .join('')\n }\n return `[${\n schemaTypes.blockObjects.find((t) => t.name === block._type)\n ?.title || 'Object'\n }]`\n })\n .join('\\n\\n')\n }\n\n editor.setFragmentData = (data: DataTransfer, originEvent) => {\n const {selection} = editor\n\n if (!selection) {\n return\n }\n\n const [start, end] = Range.edges(selection)\n const startVoid = Editor.void(editor, {at: start.path})\n const endVoid = Editor.void(editor, {at: end.path})\n\n if (Range.isCollapsed(selection) && !startVoid) {\n return\n }\n\n // Create a fake selection so that we can add a Base64-encoded copy of the\n // fragment to the HTML, to decode on future pastes.\n const domRange = ReactEditor.toDOMRange(editor, selection)\n let contents = domRange.cloneContents()\n // COMPAT: If the end node is a void node, we need to move the end of the\n // range from the void node's spacer span, to the end of the void node's\n // content, since the spacer is before void's content in the DOM.\n if (endVoid) {\n const [voidNode] = endVoid\n const r = domRange.cloneRange()\n const domNode = ReactEditor.toDOMNode(editor, voidNode)\n r.setEndAfter(domNode)\n contents = r.cloneContents()\n }\n // Remove any zero-width space spans from the cloned DOM so that they don't\n // show up elsewhere when pasted.\n Array.from(contents.querySelectorAll('[data-slate-zero-width]')).forEach(\n (zw) => {\n const isNewline = zw.getAttribute('data-slate-zero-width') === 'n'\n zw.textContent = isNewline ? '\\n' : ''\n },\n )\n // Clean up the clipboard HTML for editor spesific attributes\n Array.from(contents.querySelectorAll('*')).forEach((elm) => {\n elm.removeAttribute('contentEditable')\n elm.removeAttribute('data-slate-inline')\n elm.removeAttribute('data-slate-leaf')\n elm.removeAttribute('data-slate-node')\n elm.removeAttribute('data-slate-spacer')\n elm.removeAttribute('data-slate-string')\n elm.removeAttribute('data-slate-zero-width')\n elm.removeAttribute('draggable')\n for (const key in elm.attributes) {\n if (elm.hasAttribute(key)) {\n elm.removeAttribute(key)\n }\n }\n })\n const div = contents.ownerDocument.createElement('div')\n div.appendChild(contents)\n div.setAttribute('hidden', 'true')\n contents.ownerDocument.body.appendChild(div)\n const asHTML = div.innerHTML\n contents.ownerDocument.body.removeChild(div)\n const fragment = editor.getFragment()\n const portableText = fromSlateValue(fragment, blockTypeName)\n\n const asJSON = JSON.stringify(portableText)\n const asPlainText = toPlainText(portableText)\n data.clearData()\n data.setData('text/plain', asPlainText)\n data.setData('text/html', asHTML)\n data.setData('application/json', asJSON)\n data.setData('application/x-portable-text', asJSON)\n debug('text', asPlainText)\n data.setData(\n 'application/x-portable-text-event-origin',\n originEvent || 'external',\n )\n debug('Set fragment data', asJSON, asHTML)\n }\n\n editor.insertPortableTextData = (data: DataTransfer): boolean => {\n if (!editor.selection) {\n return false\n }\n const pText = data.getData('application/x-portable-text')\n const origin = data.getData('application/x-portable-text-event-origin')\n debug(`Inserting portable text from ${origin} event`, pText)\n if (pText) {\n const parsed = JSON.parse(pText) as PortableTextBlock[]\n if (Array.isArray(parsed) && parsed.length > 0) {\n const slateValue = _regenerateKeys(\n editor,\n toSlateValue(parsed, {schemaTypes}),\n editorActor.getSnapshot().context.keyGenerator,\n spanTypeName,\n schemaTypes,\n )\n // Validate the result\n const validation = validateValue(\n parsed,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n // Bail out if it's not valid\n if (!validation.valid && !validation.resolution?.autoResolve) {\n const errorDescription = `${validation.resolution?.description}`\n editorActor.send({\n type: 'error',\n name: 'pasteError',\n description: errorDescription,\n data: validation,\n })\n debug('Invalid insert result', validation)\n return false\n }\n _insertFragment(editor, slateValue, schemaTypes)\n return true\n }\n }\n return false\n }\n\n editor.insertTextOrHTMLData = (data: DataTransfer): boolean => {\n if (!editor.selection) {\n debug('No selection, not inserting')\n return false\n }\n const html = data.getData('text/html')\n const text = data.getData('text/plain')\n\n if (html || text) {\n debug('Inserting data', data)\n let portableText: PortableTextBlock[]\n let fragment: Node[]\n let insertedType: string | undefined\n\n if (html) {\n portableText = htmlToBlocks(html, schemaTypes.portableText, {\n unstable_whitespaceOnPasteMode: whitespaceOnPasteMode,\n }).map((block) =>\n normalizeBlock(block, {blockTypeName}),\n ) as PortableTextBlock[]\n fragment = toSlateValue(portableText, {schemaTypes})\n insertedType = 'HTML'\n\n if (portableText.length === 0) {\n return false\n }\n } else {\n // plain text\n const blocks = escapeHtml(text)\n .split(/\\n{2,}/)\n .map((line) =>\n line\n ? `<p>${line.replace(/(?:\\r\\n|\\r|\\n)/g, '<br/>')}</p>`\n : '<p></p>',\n )\n .join('')\n const textToHtml = `<html><body>${blocks}</body></html>`\n portableText = htmlToBlocks(textToHtml, schemaTypes.portableText).map(\n (block) => normalizeBlock(block, {blockTypeName}),\n ) as PortableTextBlock[]\n fragment = toSlateValue(portableText, {\n schemaTypes,\n })\n insertedType = 'text'\n }\n\n // Validate the result\n const validation = validateValue(\n portableText,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n\n // Bail out if it's not valid\n if (!validation.valid) {\n const errorDescription = `Could not validate the resulting portable text to insert.\\n${validation.resolution?.description}\\nTry to insert as plain text (shift-paste) instead.`\n editorActor.send({\n type: 'error',\n name: 'pasteError',\n description: errorDescription,\n data: validation,\n })\n debug('Invalid insert result', validation)\n return false\n }\n debug(\n `Inserting ${insertedType} fragment at ${JSON.stringify(editor.selection)}`,\n )\n _insertFragment(editor, fragment, schemaTypes)\n return true\n }\n return false\n }\n\n editor.insertData = (data: DataTransfer) => {\n if (!editor.insertPortableTextData(data)) {\n editor.insertTextOrHTMLData(data)\n }\n }\n\n editor.insertFragmentData = (data: DataTransfer): boolean => {\n const fragment = data.getData('application/x-portable-text')\n if (fragment) {\n const parsed = JSON.parse(fragment)\n editor.insertFragment(parsed)\n return true\n }\n return false\n }\n\n return editor\n }\n}\n\nconst entityMap: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;',\n}\nfunction escapeHtml(str: string) {\n return String(str).replace(/[&<>\"'`=/]/g, (s: string) => entityMap[s])\n}\n\n/**\n * Shared helper function to regenerate the keys on a fragment.\n *\n * @internal\n */\nfunction _regenerateKeys(\n editor: Pick<PortableTextSlateEditor, 'isTextBlock' | 'isTextSpan'>,\n fragment: Descendant[],\n keyGenerator: () => string,\n spanTypeName: string,\n editorTypes: Pick<PortableTextMemberSchemaTypes, 'annotations'>,\n): Descendant[] {\n return fragment.map((node) => {\n const newNode: Descendant = {...node}\n // Ensure the copy has new keys\n if (editor.isTextBlock(newNode)) {\n const annotations = editorTypes.annotations.map((t) => t.name)\n\n // Ensure that if there are no annotations, we remove the markDefs\n if (annotations.length === 0) {\n const {markDefs, ...NewNodeNoDefs} = newNode\n\n return {...NewNodeNoDefs, _key: keyGenerator()}\n }\n\n // Ensure that all annotations are allowed\n const hasForbiddenAnnotations = (newNode.markDefs || []).some((def) => {\n return !annotations.includes(def._type)\n })\n\n // if they have forbidden annotations, we remove them and keep the rest\n if (hasForbiddenAnnotations) {\n const allowedAnnotations = (newNode.markDefs || []).filter((def) => {\n return annotations.includes(def._type)\n })\n\n return {...newNode, markDefs: allowedAnnotations, _key: keyGenerator()}\n }\n\n newNode.markDefs = (newNode.markDefs || []).map((def) => {\n const oldKey = def._key\n const newKey = keyGenerator()\n newNode.children = newNode.children.map((child) =>\n child._type === spanTypeName && editor.isTextSpan(child)\n ? {\n ...child,\n marks:\n child.marks && child.marks.includes(oldKey)\n ? [...child.marks]\n .filter((mark) => mark !== oldKey)\n .concat(newKey)\n : child.marks,\n }\n : child,\n )\n return {...def, _key: newKey}\n })\n }\n const nodeWithNewKeys = {...newNode, _key: keyGenerator()}\n if (editor.isTextBlock(nodeWithNewKeys)) {\n nodeWithNewKeys.children = nodeWithNewKeys.children.map((child) => ({\n ...child,\n _key: keyGenerator(),\n }))\n }\n return nodeWithNewKeys as Descendant\n })\n}\n\n/**\n * Shared helper function to insert the final fragment into the editor\n *\n * @internal\n */\nfunction _insertFragment(\n editor: PortableTextSlateEditor,\n fragment: Descendant[],\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n editor.withoutNormalizing(() => {\n if (!editor.selection) {\n return\n }\n // Ensure that markDefs for any annotations inside this fragment are copied over to the focused text block.\n const [focusBlock, focusPath] = Editor.node(editor, editor.selection, {\n depth: 1,\n })\n if (editor.isTextBlock(focusBlock) && editor.isTextBlock(fragment[0])) {\n const {markDefs} = focusBlock\n debug(\n 'Mixing markDefs of focusBlock and fragments[0] block',\n markDefs,\n fragment[0].markDefs,\n )\n if (!isEqual(markDefs, fragment[0].markDefs)) {\n Transforms.setNodes(\n editor,\n {\n markDefs: uniq([\n ...(fragment[0].markDefs || []),\n ...(markDefs || []),\n ]),\n },\n {at: focusPath, mode: 'lowest', voids: false},\n )\n }\n }\n\n const isPasteToEmptyEditor = isEqualToEmptyEditor(\n editor.children,\n schemaTypes,\n )\n\n if (isPasteToEmptyEditor) {\n // Special case for pasting directly into an empty editor (a placeholder block).\n // When pasting content starting with multiple empty blocks,\n // `editor.insertFragment` can potentially duplicate the keys of\n // the placeholder block because of operations that happen\n // inside `editor.insertFragment` (involves an `insert_node` operation).\n // However by splitting the placeholder block first in this situation we are good.\n Transforms.splitNodes(editor, {at: [0, 0]})\n editor.insertFragment(fragment)\n Transforms.removeNodes(editor, {at: [0]})\n } else {\n // All other inserts\n editor.insertFragment(fragment)\n }\n })\n\n editor.onChange()\n}\n\n/**\n * functions we don't want to export but want to test\n * @internal\n */\nexport const exportedForTesting = {\n _regenerateKeys,\n}\n","import {noop} from 'lodash'\nimport type {BaseOperation, Editor, Node, NodeEntry} from 'slate'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport type {createEditorOptions} from '../../types/options'\nimport {createOperationToPatches} from '../../utils/operationToPatches'\nimport {createWithEventListeners} from './create-with-event-listeners'\nimport {createWithEditableAPI} from './createWithEditableAPI'\nimport {createWithMaxBlocks} from './createWithMaxBlocks'\nimport {createWithObjectKeys} from './createWithObjectKeys'\nimport {createWithPatches} from './createWithPatches'\nimport {createWithPlaceholderBlock} from './createWithPlaceholderBlock'\nimport {createWithPortableTextBlockStyle} from './createWithPortableTextBlockStyle'\nimport {createWithPortableTextLists} from './createWithPortableTextLists'\nimport {createWithPortableTextMarkModel} from './createWithPortableTextMarkModel'\nimport {createWithPortableTextSelections} from './createWithPortableTextSelections'\nimport {createWithSchemaTypes} from './createWithSchemaTypes'\nimport {createWithUndoRedo} from './createWithUndoRedo'\nimport {createWithUtils} from './createWithUtils'\n\nexport {createWithEditableAPI} from './createWithEditableAPI'\nexport {createWithHotkeys} from './createWithHotKeys'\nexport {createWithInsertData} from './createWithInsertData'\nexport {createWithMaxBlocks} from './createWithMaxBlocks'\nexport {createWithObjectKeys} from './createWithObjectKeys'\nexport {createWithPatches} from './createWithPatches'\nexport {createWithPortableTextBlockStyle} from './createWithPortableTextBlockStyle'\nexport {createWithPortableTextLists} from './createWithPortableTextLists'\nexport {createWithPortableTextMarkModel} from './createWithPortableTextMarkModel'\nexport {createWithPortableTextSelections} from './createWithPortableTextSelections'\nexport {createWithSchemaTypes} from './createWithSchemaTypes'\nexport {createWithUndoRedo} from './createWithUndoRedo'\nexport {createWithUtils} from './createWithUtils'\n\nexport interface OriginalEditorFunctions {\n apply: (operation: BaseOperation) => void\n onChange: () => void\n normalizeNode: (entry: NodeEntry<Node>) => void\n}\n\nconst originalFnMap = new WeakMap<\n PortableTextSlateEditor,\n OriginalEditorFunctions\n>()\n\nexport const withPlugins = <T extends Editor>(\n editor: T,\n options: createEditorOptions,\n): {editor: PortableTextSlateEditor; subscribe: () => () => void} => {\n const e = editor as T & PortableTextSlateEditor\n const {editorActor, portableTextEditor, readOnly, maxBlocks} = options\n const {schemaTypes} = portableTextEditor\n e.subscriptions = []\n if (e.destroy) {\n e.destroy()\n } else {\n // Save a copy of the original editor functions here before they were changed by plugins.\n // We will put them back when .destroy is called (see below).\n originalFnMap.set(e, {\n apply: e.apply,\n onChange: e.onChange,\n normalizeNode: e.normalizeNode,\n })\n }\n const operationToPatches = createOperationToPatches(schemaTypes)\n const withObjectKeys = createWithObjectKeys(editorActor, schemaTypes)\n const withSchemaTypes = createWithSchemaTypes({\n editorActor,\n schemaTypes,\n })\n const withEditableAPI = createWithEditableAPI(\n editorActor,\n portableTextEditor,\n schemaTypes,\n )\n const withPatches = createWithPatches({\n editorActor,\n patchFunctions: operationToPatches,\n readOnly,\n schemaTypes,\n })\n const withMaxBlocks = createWithMaxBlocks(maxBlocks || -1)\n const withPortableTextLists = createWithPortableTextLists(schemaTypes)\n const withUndoRedo = createWithUndoRedo({\n editorActor,\n readOnly,\n blockSchemaType: schemaTypes.block,\n })\n const withPortableTextMarkModel = createWithPortableTextMarkModel(\n editorActor,\n schemaTypes,\n )\n const withPortableTextBlockStyle = createWithPortableTextBlockStyle(\n editorActor,\n schemaTypes,\n )\n\n const withPlaceholderBlock = createWithPlaceholderBlock()\n\n const withUtils = createWithUtils({\n editorActor,\n schemaTypes,\n portableTextEditor,\n })\n const withPortableTextSelections = createWithPortableTextSelections(\n editorActor,\n schemaTypes,\n )\n const withEventListeners = createWithEventListeners(editorActor)\n\n e.destroy = () => {\n const originalFunctions = originalFnMap.get(e)\n if (!originalFunctions) {\n throw new Error('Could not find pristine versions of editor functions')\n }\n e.apply = originalFunctions.apply\n e.history = {undos: [], redos: []}\n e.normalizeNode = originalFunctions.normalizeNode\n e.onChange = originalFunctions.onChange\n }\n if (readOnly) {\n return {\n editor: withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withUtils(\n withPlaceholderBlock(\n withPortableTextLists(\n withPortableTextSelections(withEditableAPI(e)),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n subscribe: () => noop,\n }\n }\n\n // Ordering is important here, selection dealing last, data manipulation in the middle and core model stuff first.\n return {\n editor: withEventListeners(\n withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withPortableTextLists(\n withPlaceholderBlock(\n withUtils(\n withMaxBlocks(\n withUndoRedo(\n withPatches(\n withPortableTextSelections(withEditableAPI(e)),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n subscribe: () => {\n const unsubscribes: (() => void)[] = []\n editor.subscriptions.forEach((subscribeFn) => {\n unsubscribes.push(subscribeFn())\n })\n return () => {\n unsubscribes.forEach((unsubscribeFn) => {\n unsubscribeFn()\n })\n }\n },\n }\n}\n","import {useEffect, useMemo, useState, type PropsWithChildren} from 'react'\nimport {createEditor} from 'slate'\nimport {Slate, withReact} from 'slate-react'\nimport {debugWithName} from '../../utils/debug'\nimport {KEY_TO_SLATE_ELEMENT, KEY_TO_VALUE_ELEMENT} from '../../utils/weakMaps'\nimport type {EditorActor} from '../editor-machine'\nimport {withPlugins} from '../plugins'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('component:PortableTextEditor:SlateContainer')\n\n/**\n * @internal\n */\nexport interface SlateContainerProps extends PropsWithChildren {\n editorActor: EditorActor\n maxBlocks: number | undefined\n portableTextEditor: PortableTextEditor\n readOnly: boolean\n}\n\n/**\n * Sets up and encapsulates the Slate instance\n * @internal\n */\nexport function SlateContainer(props: SlateContainerProps) {\n const {editorActor, portableTextEditor, readOnly, maxBlocks} = props\n\n // Create the slate instance, using `useState` ensures setup is only run once, initially\n const [[slateEditor, subscribe]] = useState(() => {\n debug('Creating new Slate editor instance')\n const {editor, subscribe: _sub} = withPlugins(withReact(createEditor()), {\n editorActor,\n maxBlocks,\n portableTextEditor,\n readOnly,\n })\n KEY_TO_VALUE_ELEMENT.set(editor, {})\n KEY_TO_SLATE_ELEMENT.set(editor, {})\n return [editor, _sub] as const\n })\n\n useEffect(() => {\n const unsubscribe = subscribe()\n return () => {\n unsubscribe()\n }\n }, [subscribe])\n\n // Update the slate instance when plugin dependent props change.\n useEffect(() => {\n debug('Re-initializing plugin chain')\n withPlugins(slateEditor, {\n editorActor,\n maxBlocks,\n portableTextEditor,\n readOnly,\n })\n }, [editorActor, portableTextEditor, maxBlocks, readOnly, slateEditor])\n\n const initialValue = useMemo(() => {\n return [slateEditor.pteCreateTextBlock({decorators: []})]\n }, [slateEditor])\n\n useEffect(() => {\n return () => {\n debug('Destroying Slate editor')\n slateEditor.destroy()\n }\n }, [slateEditor])\n\n return (\n <Slate editor={slateEditor} initialValue={initialValue}>\n {props.children}\n </Slate>\n )\n}\n\nSlateContainer.displayName = 'SlateContainer'\n","import {createContext, useContext} from 'react'\n\n/**\n * A React context for sharing the editor's readOnly status.\n */\nexport const PortableTextEditorReadOnlyContext = createContext<boolean>(false)\n\n/**\n * Get the current editor selection from the React context.\n */\nexport const usePortableTextEditorReadOnlyStatus = (): boolean => {\n const readOnly = useContext(PortableTextEditorReadOnlyContext)\n\n if (readOnly === undefined) {\n throw new Error(\n `The \\`usePortableTextEditorReadOnly\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n return readOnly\n}\n","import type {PortableTextBlock} from '@sanity/types'\nimport {debounce, isEqual} from 'lodash'\nimport {useCallback, useMemo, useRef} from 'react'\nimport {Editor, Text, Transforms, type Descendant, type Node} from 'slate'\nimport {useSlate} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {validateValue} from '../../utils/validateValue'\nimport {toSlateValue, VOID_CHILD_KEY} from '../../utils/values'\nimport {\n isChangingLocally,\n isChangingRemotely,\n withRemoteChanges,\n} from '../../utils/withChanges'\nimport {withoutPatching} from '../../utils/withoutPatching'\nimport type {EditorActor} from '../editor-machine'\nimport {withoutSaving} from '../plugins/createWithUndoRedo'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('hook:useSyncValue')\n\n/**\n * @internal\n */\nexport interface UseSyncValueProps {\n editorActor: EditorActor\n portableTextEditor: PortableTextEditor\n readOnly: boolean\n}\n\nconst CURRENT_VALUE = new WeakMap<\n PortableTextEditor,\n PortableTextBlock[] | undefined\n>()\n\n/**\n * Sync value with the editor state\n *\n * Normally nothing here should apply, and the editor and the real world are perfectly aligned.\n *\n * Inconsistencies could happen though, so we need to check the editor state when the value changes.\n *\n * For performance reasons, it makes sense to also do the content validation here, as we already\n * iterate over the value and can validate only the new content that is actually changed.\n *\n * @internal\n */\nexport function useSyncValue(\n props: UseSyncValueProps,\n): (\n value: PortableTextBlock[] | undefined,\n userCallbackFn?: () => void,\n) => void {\n const {editorActor, portableTextEditor, readOnly} = props\n const schemaTypes = editorActor.getSnapshot().context.schema\n const previousValue = useRef<PortableTextBlock[] | undefined>()\n const slateEditor = useSlate()\n const updateValueFunctionRef =\n useRef<(value: PortableTextBlock[] | undefined) => void>()\n\n const updateFromCurrentValue = useCallback(() => {\n const currentValue = CURRENT_VALUE.get(portableTextEditor)\n if (previousValue.current === currentValue) {\n debug('Value is the same object as previous, not need to sync')\n return\n }\n if (updateValueFunctionRef.current && currentValue) {\n debug('Updating the value debounced')\n updateValueFunctionRef.current(currentValue)\n }\n }, [portableTextEditor])\n const updateValueDebounced = useMemo(\n () =>\n debounce(updateFromCurrentValue, 1000, {trailing: true, leading: false}),\n [updateFromCurrentValue],\n )\n\n return useMemo(() => {\n const updateFunction = (value: PortableTextBlock[] | undefined) => {\n CURRENT_VALUE.set(portableTextEditor, value)\n const isProcessingLocalChanges = isChangingLocally(slateEditor)\n const isProcessingRemoteChanges = isChangingRemotely(slateEditor)\n if (!readOnly) {\n if (isProcessingLocalChanges) {\n debug('Has local changes, not syncing value right now')\n updateValueDebounced()\n return\n }\n if (isProcessingRemoteChanges) {\n debug('Has remote changes, not syncing value right now')\n updateValueDebounced()\n return\n }\n }\n\n let isChanged = false\n let isValid = true\n\n const hadSelection = !!slateEditor.selection\n\n // If empty value, remove everything in the editor and insert a placeholder block\n if (!value || value.length === 0) {\n debug('Value is empty')\n Editor.withoutNormalizing(slateEditor, () => {\n withoutSaving(slateEditor, () => {\n withoutPatching(slateEditor, () => {\n if (hadSelection) {\n Transforms.deselect(slateEditor)\n }\n const childrenLength = slateEditor.children.length\n slateEditor.children.forEach((_, index) => {\n Transforms.removeNodes(slateEditor, {\n at: [childrenLength - 1 - index],\n })\n })\n Transforms.insertNodes(\n slateEditor,\n slateEditor.pteCreateTextBlock({decorators: []}),\n {at: [0]},\n )\n // Add a new selection in the top of the document\n if (hadSelection) {\n Transforms.select(slateEditor, [0, 0])\n }\n })\n })\n })\n isChanged = true\n }\n // Remove, replace or add nodes according to what is changed.\n if (value && value.length > 0) {\n const slateValueFromProps = toSlateValue(value, {\n schemaTypes,\n })\n Editor.withoutNormalizing(slateEditor, () => {\n withRemoteChanges(slateEditor, () => {\n withoutSaving(slateEditor, () => {\n withoutPatching(slateEditor, () => {\n const childrenLength = slateEditor.children.length\n // Remove blocks that have become superfluous\n if (slateValueFromProps.length < childrenLength) {\n for (\n let i = childrenLength - 1;\n i > slateValueFromProps.length - 1;\n i--\n ) {\n Transforms.removeNodes(slateEditor, {\n at: [i],\n })\n }\n isChanged = true\n }\n // Go through all of the blocks and see if they need to be updated\n slateValueFromProps.forEach(\n (currentBlock, currentBlockIndex) => {\n const oldBlock = slateEditor.children[currentBlockIndex]\n const hasChanges =\n oldBlock && !isEqual(currentBlock, oldBlock)\n if (hasChanges && isValid) {\n const validationValue = [value[currentBlockIndex]]\n const validation = validateValue(\n validationValue,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n // Resolve validations that can be resolved automatically, without involving the user (but only if the value was changed)\n if (\n !validation.valid &&\n validation.resolution?.autoResolve &&\n validation.resolution?.patches.length > 0\n ) {\n // Only apply auto resolution if the value has been populated before and is different from the last one.\n if (\n !readOnly &&\n previousValue.current &&\n previousValue.current !== value\n ) {\n // Give a console warning about the fact that it did an auto resolution\n console.warn(\n `${validation.resolution.action} for block with _key '${validationValue[0]._key}'. ${validation.resolution?.description}`,\n )\n validation.resolution.patches.forEach((patch) => {\n editorActor.send({type: 'patch', patch})\n })\n }\n }\n if (\n validation.valid ||\n validation.resolution?.autoResolve\n ) {\n if (oldBlock._key === currentBlock._key) {\n if (debug.enabled)\n debug('Updating block', oldBlock, currentBlock)\n _updateBlock(\n slateEditor,\n currentBlock,\n oldBlock,\n currentBlockIndex,\n )\n } else {\n if (debug.enabled)\n debug('Replacing block', oldBlock, currentBlock)\n _replaceBlock(\n slateEditor,\n currentBlock,\n currentBlockIndex,\n )\n }\n isChanged = true\n } else {\n editorActor.send({\n type: 'invalid value',\n resolution: validation.resolution,\n value,\n })\n isValid = false\n }\n }\n if (!oldBlock && isValid) {\n const validationValue = [value[currentBlockIndex]]\n const validation = validateValue(\n validationValue,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n if (debug.enabled)\n debug(\n 'Validating and inserting new block in the end of the value',\n currentBlock,\n )\n if (\n validation.valid ||\n validation.resolution?.autoResolve\n ) {\n Transforms.insertNodes(slateEditor, currentBlock, {\n at: [currentBlockIndex],\n })\n } else {\n debug('Invalid', validation)\n editorActor.send({\n type: 'invalid value',\n resolution: validation.resolution,\n value,\n })\n isValid = false\n }\n }\n },\n )\n })\n })\n })\n })\n }\n\n if (!isValid) {\n debug('Invalid value, returning')\n return\n }\n if (isChanged) {\n debug('Server value changed, syncing editor')\n try {\n slateEditor.onChange()\n } catch (err) {\n console.error(err)\n editorActor.send({\n type: 'invalid value',\n resolution: null,\n value,\n })\n return\n }\n if (hadSelection && !slateEditor.selection) {\n Transforms.select(slateEditor, {\n anchor: {path: [0, 0], offset: 0},\n focus: {path: [0, 0], offset: 0},\n })\n slateEditor.onChange()\n }\n editorActor.send({type: 'value changed', value})\n } else {\n debug('Server value and editor value is equal, no need to sync.')\n }\n previousValue.current = value\n }\n updateValueFunctionRef.current = updateFunction\n return updateFunction\n }, [\n editorActor,\n portableTextEditor,\n readOnly,\n schemaTypes,\n slateEditor,\n updateValueDebounced,\n ])\n}\n\n/**\n * This code is moved out of the above algorithm to keep complexity down.\n * @internal\n */\nfunction _replaceBlock(\n slateEditor: PortableTextSlateEditor,\n currentBlock: Descendant,\n currentBlockIndex: number,\n) {\n // While replacing the block and the current selection focus is on the replaced block,\n // temporarily deselect the editor then optimistically try to restore the selection afterwards.\n const currentSelection = slateEditor.selection\n const selectionFocusOnBlock =\n currentSelection && currentSelection.focus.path[0] === currentBlockIndex\n if (selectionFocusOnBlock) {\n Transforms.deselect(slateEditor)\n }\n Transforms.removeNodes(slateEditor, {at: [currentBlockIndex]})\n Transforms.insertNodes(slateEditor, currentBlock, {at: [currentBlockIndex]})\n slateEditor.onChange()\n if (selectionFocusOnBlock) {\n Transforms.select(slateEditor, currentSelection)\n }\n}\n\n/**\n * This code is moved out of the above algorithm to keep complexity down.\n * @internal\n */\nfunction _updateBlock(\n slateEditor: PortableTextSlateEditor,\n currentBlock: Descendant,\n oldBlock: Descendant,\n currentBlockIndex: number,\n) {\n // Update the root props on the block\n Transforms.setNodes(slateEditor, currentBlock as Partial<Node>, {\n at: [currentBlockIndex],\n })\n // Text block's need to have their children updated as well (setNode does not target a node's children)\n if (\n slateEditor.isTextBlock(currentBlock) &&\n slateEditor.isTextBlock(oldBlock)\n ) {\n const oldBlockChildrenLength = oldBlock.children.length\n if (currentBlock.children.length < oldBlockChildrenLength) {\n // Remove any children that have become superfluous\n Array.from(\n Array(oldBlockChildrenLength - currentBlock.children.length),\n ).forEach((_, index) => {\n const childIndex = oldBlockChildrenLength - 1 - index\n if (childIndex > 0) {\n debug('Removing child')\n Transforms.removeNodes(slateEditor, {\n at: [currentBlockIndex, childIndex],\n })\n }\n })\n }\n currentBlock.children.forEach(\n (currentBlockChild, currentBlockChildIndex) => {\n const oldBlockChild = oldBlock.children[currentBlockChildIndex]\n const isChildChanged = !isEqual(currentBlockChild, oldBlockChild)\n const isTextChanged = !isEqual(\n currentBlockChild.text,\n oldBlockChild?.text,\n )\n const path = [currentBlockIndex, currentBlockChildIndex]\n if (isChildChanged) {\n // Update if this is the same child\n if (currentBlockChild._key === oldBlockChild?._key) {\n debug('Updating changed child', currentBlockChild, oldBlockChild)\n Transforms.setNodes(\n slateEditor,\n currentBlockChild as Partial<Node>,\n {\n at: path,\n },\n )\n const isSpanNode =\n Text.isText(currentBlockChild) &&\n currentBlockChild._type === 'span' &&\n Text.isText(oldBlockChild) &&\n oldBlockChild._type === 'span'\n if (isSpanNode && isTextChanged) {\n Transforms.delete(slateEditor, {\n at: {\n focus: {path, offset: 0},\n anchor: {path, offset: oldBlockChild.text.length},\n },\n })\n Transforms.insertText(slateEditor, currentBlockChild.text, {\n at: path,\n })\n slateEditor.onChange()\n } else if (!isSpanNode) {\n // If it's a inline block, also update the void text node key\n debug('Updating changed inline object child', currentBlockChild)\n Transforms.setNodes(\n slateEditor,\n {_key: VOID_CHILD_KEY},\n {\n at: [...path, 0],\n voids: true,\n },\n )\n }\n // Replace the child if _key's are different\n } else if (oldBlockChild) {\n debug('Replacing child', currentBlockChild)\n Transforms.removeNodes(slateEditor, {\n at: [currentBlockIndex, currentBlockChildIndex],\n })\n Transforms.insertNodes(slateEditor, currentBlockChild as Node, {\n at: [currentBlockIndex, currentBlockChildIndex],\n })\n slateEditor.onChange()\n // Insert it if it didn't exist before\n } else if (!oldBlockChild) {\n debug('Inserting new child', currentBlockChild)\n Transforms.insertNodes(slateEditor, currentBlockChild as Node, {\n at: [currentBlockIndex, currentBlockChildIndex],\n })\n slateEditor.onChange()\n }\n }\n },\n )\n }\n}\n","import type {Patch} from '@portabletext/patches'\nimport type {PortableTextBlock} from '@sanity/types'\nimport {throttle} from 'lodash'\nimport {useCallback, useEffect, useRef} from 'react'\nimport {Editor} from 'slate'\nimport {useSlate} from 'slate-react'\nimport {useEffectEvent} from 'use-effect-event'\nimport type {EditorChange} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {IS_PROCESSING_LOCAL_CHANGES} from '../../utils/weakMaps'\nimport type {EditorActor} from '../editor-machine'\nimport {usePortableTextEditor} from '../hooks/usePortableTextEditor'\nimport {usePortableTextEditorReadOnlyStatus} from '../hooks/usePortableTextReadOnly'\nimport {useSyncValue} from '../hooks/useSyncValue'\n\nconst debug = debugWithName('component:PortableTextEditor:Synchronizer')\nconst debugVerbose = debug.enabled && false\n\n// The editor will commit changes in a throttled fashion in order\n// not to overload the network and degrade performance while typing.\nconst FLUSH_PATCHES_THROTTLED_MS = process.env.NODE_ENV === 'test' ? 500 : 1000\n\n/**\n * @internal\n */\nexport interface SynchronizerProps {\n editorActor: EditorActor\n getValue: () => Array<PortableTextBlock> | undefined\n onChange: (change: EditorChange) => void\n value: Array<PortableTextBlock> | undefined\n}\n\n/**\n * Synchronizes the server value with the editor, and provides various contexts for the editor state.\n * @internal\n */\nexport function Synchronizer(props: SynchronizerProps) {\n const portableTextEditor = usePortableTextEditor()\n const readOnly = usePortableTextEditorReadOnlyStatus()\n const {editorActor, getValue, onChange, value} = props\n const pendingPatches = useRef<Patch[]>([])\n\n const syncValue = useSyncValue({\n editorActor,\n portableTextEditor,\n readOnly,\n })\n\n const slateEditor = useSlate()\n\n useEffect(() => {\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, false)\n }, [slateEditor])\n\n const onFlushPendingPatches = useCallback(() => {\n if (pendingPatches.current.length > 0) {\n debug('Flushing pending patches')\n if (debugVerbose) {\n debug(`Patches:\\n${JSON.stringify(pendingPatches.current, null, 2)}`)\n }\n const snapshot = getValue()\n editorActor.send({\n type: 'mutation',\n patches: pendingPatches.current,\n snapshot,\n })\n pendingPatches.current = []\n }\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, false)\n }, [editorActor, slateEditor, getValue])\n\n // Flush pending patches immediately on unmount\n useEffect(() => {\n return () => {\n onFlushPendingPatches()\n }\n }, [onFlushPendingPatches])\n\n // We want to ensure that _when_ `props.onChange` is called, it uses the current value.\n // But we don't want to have the `useEffect` run setup + teardown + setup every time the prop might change, as that's unnecessary.\n // So we use our own polyfill that lets us use an upcoming React hook that solves this exact problem.\n // https://19.react.dev/learn/separating-events-from-effects#declaring-an-effect-event\n const handleChange = useEffectEvent((change: EditorChange) =>\n onChange(change),\n )\n\n // Subscribe to, and handle changes from the editor\n useEffect(() => {\n const onFlushPendingPatchesThrottled = throttle(\n () => {\n // If the editor is normalizing (each operation) it means that it's not in the middle of a bigger transform,\n // and we can flush these changes immediately.\n if (Editor.isNormalizing(slateEditor)) {\n onFlushPendingPatches()\n return\n }\n // If it's in the middle of something, try again.\n onFlushPendingPatchesThrottled()\n },\n FLUSH_PATCHES_THROTTLED_MS,\n {\n leading: false,\n trailing: true,\n },\n )\n\n debug('Subscribing to editor changes')\n const sub = editorActor.on('*', (event) => {\n switch (event.type) {\n case 'patch':\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, true)\n pendingPatches.current.push(event.patch)\n onFlushPendingPatchesThrottled()\n handleChange(event)\n break\n case 'loading': {\n handleChange({type: 'loading', isLoading: true})\n break\n }\n case 'done loading': {\n handleChange({type: 'loading', isLoading: false})\n break\n }\n case 'offline': {\n handleChange({type: 'connection', value: 'offline'})\n break\n }\n case 'online': {\n handleChange({type: 'connection', value: 'online'})\n break\n }\n case 'value changed': {\n handleChange({type: 'value', value: event.value})\n break\n }\n case 'invalid value': {\n handleChange({\n type: 'invalidValue',\n resolution: event.resolution,\n value: event.value,\n })\n break\n }\n case 'error': {\n handleChange({\n ...event,\n level: 'warning',\n })\n break\n }\n case 'patches': {\n break\n }\n default:\n handleChange(event)\n }\n })\n return () => {\n debug('Unsubscribing to changes')\n sub.unsubscribe()\n }\n }, [editorActor, handleChange, onFlushPendingPatches, slateEditor])\n\n // Sync the value when going online\n const handleOnline = useCallback(() => {\n debug('Editor is online, syncing from props.value')\n syncValue(value)\n }, [syncValue, value])\n\n // Notify about window online and offline status changes\n useEffect(() => {\n const subscription = editorActor.on('online', handleOnline)\n\n return () => {\n subscription.unsubscribe()\n }\n }, [handleOnline, editorActor])\n\n // This hook must be set up after setting up the subscription above, or it will not pick up validation errors from the useSyncValue hook.\n // This will cause the editor to not be able to signal a validation error and offer invalid value resolution of the initial value.\n const isInitialValueFromProps = useRef(true)\n useEffect(() => {\n debug('Value from props changed, syncing new value')\n syncValue(value)\n // Signal that we have our first value, and are ready to roll.\n if (isInitialValueFromProps.current) {\n editorActor.send({type: 'ready'})\n isInitialValueFromProps.current = false\n }\n }, [editorActor, syncValue, value])\n\n return null\n}\n\nSynchronizer.displayName = 'Synchronizer'\n","import {createContext} from 'react'\nimport type {EditorActor} from './editor-machine'\n\nexport const EditorActorContext = createContext<EditorActor>({} as EditorActor)\n","import {isEqual} from 'lodash'\nimport {Editor, Node, Path, Range, Transforms} from 'slate'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport type {BehaviourActionImplementation} from './behavior.actions'\nimport type {BehaviorAction, PickFromUnion} from './behavior.types'\n\nexport const insertBreakActionImplementation: BehaviourActionImplementation<\n PickFromUnion<BehaviorAction, 'type', 'insert break' | 'insert soft break'>\n> = ({context, action}) => {\n const keyGenerator = context.keyGenerator\n const schema = context.schema\n const editor = action.editor\n\n if (!editor.selection) {\n return\n }\n\n const [focusSpan] = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: editor.selection.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0] ?? [undefined]\n const focusDecorators =\n focusSpan.marks?.filter((mark) =>\n schema.decorators.some((decorator) => decorator.value === mark),\n ) ?? []\n const focusAnnotations =\n focusSpan.marks?.filter(\n (mark) =>\n !schema.decorators.some((decorator) => decorator.value === mark),\n ) ?? []\n\n const focusBlockPath = editor.selection.focus.path.slice(0, 1)\n const focusBlock = Node.descendant(editor, focusBlockPath) as\n | SlateTextBlock\n | VoidElement\n\n if (editor.isTextBlock(focusBlock)) {\n const [start, end] = Range.edges(editor.selection)\n const atTheStartOfBlock = isEqual(end, {\n path: [...focusBlockPath, 0],\n offset: 0,\n })\n\n if (atTheStartOfBlock && Range.isCollapsed(editor.selection)) {\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({\n decorators: focusAnnotations.length === 0 ? focusDecorators : [],\n listItem: focusBlock.listItem,\n level: focusBlock.level,\n }),\n )\n\n const [nextBlockPath] = Path.next(focusBlockPath)\n\n Transforms.select(editor, {\n anchor: {path: [nextBlockPath, 0], offset: 0},\n focus: {path: [nextBlockPath, 0], offset: 0},\n })\n\n return\n }\n\n const lastFocusBlockChild =\n focusBlock.children[focusBlock.children.length - 1]\n const atTheEndOfBlock = isEqual(start, {\n path: [...focusBlockPath, focusBlock.children.length - 1],\n offset: editor.isTextSpan(lastFocusBlockChild)\n ? lastFocusBlockChild.text.length\n : 0,\n })\n\n if (atTheEndOfBlock && Range.isCollapsed(editor.selection)) {\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({\n decorators: [],\n listItem: focusBlock.listItem,\n level: focusBlock.level,\n }),\n )\n\n const [nextBlockPath] = Path.next(focusBlockPath)\n\n Transforms.setSelection(editor, {\n anchor: {path: [nextBlockPath, 0], offset: 0},\n focus: {path: [nextBlockPath, 0], offset: 0},\n })\n\n return\n }\n\n const isInTheMiddleOfNode = !atTheStartOfBlock && !atTheEndOfBlock\n\n if (isInTheMiddleOfNode) {\n Editor.withoutNormalizing(editor, () => {\n if (!editor.selection) {\n return\n }\n\n Transforms.splitNodes(editor, {\n at: editor.selection,\n })\n\n const [nextNode, nextNodePath] = Editor.node(\n editor,\n Path.next(focusBlockPath),\n {depth: 1},\n )\n\n Transforms.setSelection(editor, {\n anchor: {path: [...nextNodePath, 0], offset: 0},\n focus: {path: [...nextNodePath, 0], offset: 0},\n })\n\n /**\n * Assign new keys to markDefs that are now split across two blocks\n */\n if (\n editor.isTextBlock(nextNode) &&\n nextNode.markDefs &&\n nextNode.markDefs.length > 0\n ) {\n const newMarkDefKeys = new Map<string, string>()\n\n const prevNodeSpans = Array.from(\n Node.children(editor, focusBlockPath),\n )\n .map((entry) => entry[0])\n .filter((node) => editor.isTextSpan(node))\n const children = Node.children(editor, nextNodePath)\n\n for (const [child, childPath] of children) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n const marks = child.marks ?? []\n\n // Go through the marks of the span and figure out if any of\n // them refer to annotations that are also present in the\n // previous block\n for (const mark of marks) {\n if (\n schema.decorators.some((decorator) => decorator.value === mark)\n ) {\n continue\n }\n\n if (\n prevNodeSpans.some((prevNodeSpan) =>\n prevNodeSpan.marks?.includes(mark),\n ) &&\n !newMarkDefKeys.has(mark)\n ) {\n // This annotation is both present in the previous block\n // and this block, so let's assign a new key to it\n newMarkDefKeys.set(mark, keyGenerator())\n }\n }\n\n const newMarks = marks.map(\n (mark) => newMarkDefKeys.get(mark) ?? mark,\n )\n\n // No need to update the marks if they are the same\n if (!isEqual(marks, newMarks)) {\n Transforms.setNodes(\n editor,\n {marks: newMarks},\n {\n at: childPath,\n },\n )\n }\n }\n\n // Time to update all the markDefs that need a new key because\n // they've been split across blocks\n const newMarkDefs = nextNode.markDefs.map((markDef) => ({\n ...markDef,\n _key: newMarkDefKeys.get(markDef._key) ?? markDef._key,\n }))\n\n // No need to update the markDefs if they are the same\n if (!isEqual(nextNode.markDefs, newMarkDefs)) {\n Transforms.setNodes(\n editor,\n {markDefs: newMarkDefs},\n {\n at: nextNodePath,\n match: (node) => editor.isTextBlock(node),\n },\n )\n }\n }\n })\n editor.onChange()\n return\n }\n }\n}\n","import {\n deleteBackward,\n deleteForward,\n Editor,\n insertText,\n Transforms,\n} from 'slate'\nimport type {PortableTextMemberSchemaTypes} from '../../types/editor'\nimport {toSlateRange} from '../../utils/ranges'\nimport {\n addDecoratorActionImplementation,\n removeDecoratorActionImplementation,\n toggleDecoratorActionImplementation,\n} from '../plugins/createWithPortableTextMarkModel'\nimport {insertBreakActionImplementation} from './behavior.action.insert-break'\nimport type {\n BehaviorAction,\n BehaviorEvent,\n PickFromUnion,\n} from './behavior.types'\n\nexport type BehaviorActionContext = {\n keyGenerator: () => string\n schema: PortableTextMemberSchemaTypes\n}\n\nexport type BehaviourActionImplementation<\n TBehaviorAction extends BehaviorAction,\n> = ({\n context,\n action,\n}: {\n context: BehaviorActionContext\n action: TBehaviorAction\n}) => void\n\ntype BehaviourActionImplementations = {\n [TBehaviorActionType in BehaviorAction['type']]: BehaviourActionImplementation<\n PickFromUnion<BehaviorAction, 'type', TBehaviorActionType>\n >\n}\n\nconst behaviorActionImplementations: BehaviourActionImplementations = {\n 'decorator.add': addDecoratorActionImplementation,\n 'decorator.remove': removeDecoratorActionImplementation,\n 'decorator.toggle': toggleDecoratorActionImplementation,\n 'set block': ({action}) => {\n for (const path of action.paths) {\n const at = toSlateRange(\n {anchor: {path, offset: 0}, focus: {path, offset: 0}},\n action.editor,\n )!\n\n Transforms.setNodes(\n action.editor,\n {\n ...(action.style ? {style: action.style} : {}),\n ...(action.listItem ? {listItem: action.listItem} : {}),\n ...(action.level ? {level: action.level} : {}),\n },\n {at},\n )\n }\n },\n 'unset block': ({action}) => {\n for (const path of action.paths) {\n const at = toSlateRange(\n {anchor: {path, offset: 0}, focus: {path, offset: 0}},\n action.editor,\n )!\n\n Transforms.unsetNodes(action.editor, action.props, {at})\n }\n },\n 'delete backward': ({action}) => {\n deleteBackward(action.editor, action.unit)\n },\n 'delete forward': ({action}) => {\n deleteForward(action.editor, action.unit)\n },\n 'delete': ({action}) => {\n const location = toSlateRange(action.selection, action.editor)\n\n if (!location) {\n console.error(\n `Could not find Slate location from selection ${action.selection}`,\n )\n return\n }\n\n if (location.anchor.path.length === 1 && location.focus.path.length === 1) {\n Transforms.removeNodes(action.editor, {\n at: location,\n })\n } else {\n Transforms.delete(action.editor, {\n at: location,\n })\n }\n },\n 'insert break': insertBreakActionImplementation,\n // This mimics Slate's internal which also just does a regular insert break\n // when on soft break\n 'insert soft break': insertBreakActionImplementation,\n 'insert text': ({action}) => {\n insertText(action.editor, action.text)\n },\n 'insert text block': ({context, action}) => {\n Editor.insertNode(action.editor, {\n _key: context.keyGenerator(),\n _type: context.schema.block.name,\n style: context.schema.styles[0].value ?? 'normal',\n markDefs: [],\n children: [\n {\n _key: context.keyGenerator(),\n _type: 'span',\n text: '',\n },\n ],\n })\n },\n 'effect': ({action}) => {\n action.effect()\n },\n 'select': ({action}) => {\n const newSelection = toSlateRange(action.selection, action.editor)\n\n if (newSelection) {\n Transforms.select(action.editor, newSelection)\n } else {\n Transforms.deselect(action.editor)\n }\n },\n 'reselect': ({action}) => {\n const selection = action.editor.selection\n\n if (selection) {\n Transforms.select(action.editor, {...selection})\n action.editor.selection = {...selection}\n }\n },\n}\n\nexport function performAction({\n context,\n action,\n}: {\n context: BehaviorActionContext\n action: BehaviorAction\n}) {\n switch (action.type) {\n case 'delete': {\n behaviorActionImplementations.delete({\n context,\n action,\n })\n break\n }\n case 'insert text block': {\n behaviorActionImplementations['insert text block']({\n context,\n action,\n })\n break\n }\n case 'set block': {\n behaviorActionImplementations['set block']({\n context,\n action,\n })\n break\n }\n case 'unset block': {\n behaviorActionImplementations['unset block']({\n context,\n action,\n })\n break\n }\n case 'effect': {\n behaviorActionImplementations.effect({\n context,\n action,\n })\n break\n }\n case 'select': {\n behaviorActionImplementations.select({\n context,\n action,\n })\n break\n }\n case 'reselect': {\n behaviorActionImplementations.reselect({\n context,\n action,\n })\n break\n }\n default: {\n performDefaultAction({context, action})\n }\n }\n}\n\nexport function performDefaultAction({\n context,\n action,\n}: {\n context: BehaviorActionContext\n action: PickFromUnion<BehaviorAction, 'type', BehaviorEvent['type']>\n}) {\n switch (action.type) {\n case 'decorator.add': {\n behaviorActionImplementations['decorator.add']({\n context,\n action,\n })\n break\n }\n case 'decorator.remove': {\n behaviorActionImplementations['decorator.remove']({\n context,\n action,\n })\n break\n }\n case 'decorator.toggle': {\n behaviorActionImplementations['decorator.toggle']({\n context,\n action,\n })\n break\n }\n case 'delete backward': {\n behaviorActionImplementations['delete backward']({\n context,\n action,\n })\n break\n }\n case 'delete forward': {\n behaviorActionImplementations['delete forward']({\n context,\n action,\n })\n break\n }\n case 'insert break': {\n behaviorActionImplementations['insert break']({\n context,\n action,\n })\n break\n }\n case 'insert soft break': {\n behaviorActionImplementations['insert soft break']({\n context,\n action,\n })\n break\n }\n default: {\n behaviorActionImplementations['insert text']({\n context,\n action,\n })\n }\n }\n}\n","import type {Patch} from '@portabletext/patches'\nimport type {PortableTextBlock} from '@sanity/types'\nimport type {FocusEvent} from 'react'\nimport {Editor} from 'slate'\nimport {\n assertEvent,\n assign,\n emit,\n enqueueActions,\n fromCallback,\n setup,\n type ActorRefFrom,\n} from 'xstate'\nimport type {\n EditorSelection,\n InvalidValueResolution,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../types/editor'\nimport {toPortableTextRange} from '../utils/ranges'\nimport {fromSlateValue} from '../utils/values'\nimport {KEY_TO_VALUE_ELEMENT} from '../utils/weakMaps'\nimport {performAction} from './behavior/behavior.actions'\nimport {coreBehaviors} from './behavior/behavior.core'\nimport type {\n Behavior,\n BehaviorAction,\n BehaviorActionIntend,\n BehaviorContext,\n BehaviorEvent,\n} from './behavior/behavior.types'\n\n/**\n * @internal\n */\nexport type EditorActor = ActorRefFrom<typeof editorMachine>\n\nconst networkLogic = fromCallback(({sendBack}) => {\n const onlineHandler = () => {\n sendBack({type: 'online'})\n }\n const offlineHandler = () => {\n sendBack({type: 'offline'})\n }\n\n window.addEventListener('online', onlineHandler)\n window.addEventListener('offline', offlineHandler)\n\n return () => {\n window.removeEventListener('online', onlineHandler)\n window.removeEventListener('offline', offlineHandler)\n }\n})\n\n/**\n * @internal\n */\nexport type PatchEvent = {type: 'patch'; patch: Patch}\n\n/**\n * @internal\n */\nexport type PatchesEvent = {\n type: 'patches'\n patches: Array<Patch>\n snapshot: Array<PortableTextBlock> | undefined\n}\n\n/**\n * @internal\n */\nexport type MutationEvent = {\n type: 'mutation'\n patches: Array<Patch>\n snapshot: Array<PortableTextBlock> | undefined\n}\n\ntype EditorEvent =\n | {type: 'normalizing'}\n | {type: 'done normalizing'}\n | {\n type: 'behavior event'\n behaviorEvent: BehaviorEvent\n editor: PortableTextSlateEditor\n }\n | {\n type: 'behavior action intends'\n editor: PortableTextSlateEditor\n actionIntends: Array<BehaviorActionIntend>\n }\n | {\n type: 'update schema'\n schema: PortableTextMemberSchemaTypes\n }\n | {\n type: 'update behaviors'\n behaviors: Array<Behavior>\n }\n | EditorEmittedEvent\n\ntype EditorEmittedEvent =\n | {type: 'ready'}\n | PatchEvent\n | PatchesEvent\n | MutationEvent\n | {\n type: 'unset'\n previousValue: Array<PortableTextBlock>\n }\n | {\n type: 'value changed'\n value: Array<PortableTextBlock> | undefined\n }\n | {\n type: 'invalid value'\n resolution: InvalidValueResolution | null\n value: Array<PortableTextBlock> | undefined\n }\n | {\n type: 'error'\n name: string\n description: string\n data: unknown\n }\n | {type: 'selection'; selection: EditorSelection}\n | {type: 'blur'; event: FocusEvent<HTMLDivElement, Element>}\n | {type: 'focus'; event: FocusEvent<HTMLDivElement, Element>}\n | {type: 'online'}\n | {type: 'offline'}\n | {type: 'loading'}\n | {type: 'done loading'}\n\n/**\n * @internal\n */\nexport const editorMachine = setup({\n types: {\n context: {} as {\n behaviors: Array<Behavior>\n keyGenerator: () => string\n pendingEvents: Array<PatchEvent | MutationEvent>\n schema: PortableTextMemberSchemaTypes\n },\n events: {} as EditorEvent,\n emitted: {} as EditorEmittedEvent,\n input: {} as {\n behaviors?: Array<Behavior>\n keyGenerator: () => string\n schema: PortableTextMemberSchemaTypes\n },\n },\n actions: {\n 'assign behaviors': assign({\n behaviors: ({event}) => {\n assertEvent(event, 'update behaviors')\n return event.behaviors\n },\n }),\n 'assign schema': assign({\n schema: ({event}) => {\n assertEvent(event, 'update schema')\n return event.schema\n },\n }),\n 'emit patch event': emit(({event}) => {\n assertEvent(event, 'patch')\n return event\n }),\n 'emit mutation event': emit(({event}) => {\n assertEvent(event, 'mutation')\n return event\n }),\n 'defer event': assign({\n pendingEvents: ({context, event}) => {\n assertEvent(event, ['patch', 'mutation'])\n return [...context.pendingEvents, event]\n },\n }),\n 'emit pending events': enqueueActions(({context, enqueue}) => {\n for (const event of context.pendingEvents) {\n enqueue(emit(event))\n }\n }),\n 'clear pending events': assign({\n pendingEvents: [],\n }),\n 'handle behavior event': enqueueActions(({context, event, enqueue}) => {\n assertEvent(event, ['behavior event'])\n\n const defaultAction = {\n ...event.behaviorEvent,\n editor: event.editor,\n } satisfies BehaviorAction\n\n const eventBehaviors = context.behaviors.filter(\n (behavior) => behavior.on === event.behaviorEvent.type,\n )\n\n if (eventBehaviors.length === 0) {\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends: [defaultAction],\n })\n return\n }\n\n const value = fromSlateValue(\n event.editor.children,\n context.schema.block.name,\n KEY_TO_VALUE_ELEMENT.get(event.editor),\n )\n const selection = toPortableTextRange(\n value,\n event.editor.selection,\n context.schema,\n )\n\n if (!selection) {\n console.warn(\n `Unable to handle event ${event.type} due to missing selection`,\n )\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends: [defaultAction],\n })\n return\n }\n\n const behaviorContext = {\n schema: context.schema,\n value,\n selection,\n } satisfies BehaviorContext\n\n let behaviorOverwritten = false\n\n for (const eventBehavior of eventBehaviors) {\n const shouldRun =\n eventBehavior.guard?.({\n context: behaviorContext,\n event: event.behaviorEvent,\n }) ?? true\n\n if (!shouldRun) {\n continue\n }\n\n const actionIntendSets = eventBehavior.actions.map((actionSet) =>\n actionSet(\n {context: behaviorContext, event: event.behaviorEvent},\n shouldRun,\n ),\n )\n\n for (const actionIntends of actionIntendSets) {\n behaviorOverwritten =\n actionIntends.length > 0 &&\n actionIntends.some((actionIntend) => actionIntend.type !== 'effect')\n\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends,\n })\n }\n\n if (behaviorOverwritten) {\n break\n }\n }\n\n if (!behaviorOverwritten) {\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends: [defaultAction],\n })\n }\n }),\n },\n actors: {\n networkLogic,\n },\n}).createMachine({\n id: 'editor',\n context: ({input}) => ({\n behaviors: input.behaviors ?? coreBehaviors,\n keyGenerator: input.keyGenerator,\n pendingEvents: [],\n schema: input.schema,\n }),\n invoke: {\n id: 'networkLogic',\n src: 'networkLogic',\n },\n on: {\n 'ready': {actions: emit(({event}) => event)},\n 'unset': {actions: emit(({event}) => event)},\n 'value changed': {actions: emit(({event}) => event)},\n 'invalid value': {actions: emit(({event}) => event)},\n 'error': {actions: emit(({event}) => event)},\n 'selection': {actions: emit(({event}) => event)},\n 'blur': {actions: emit(({event}) => event)},\n 'focus': {actions: emit(({event}) => event)},\n 'online': {actions: emit({type: 'online'})},\n 'offline': {actions: emit({type: 'offline'})},\n 'loading': {actions: emit({type: 'loading'})},\n 'patches': {actions: emit(({event}) => event)},\n 'done loading': {actions: emit({type: 'done loading'})},\n 'update behaviors': {actions: 'assign behaviors'},\n 'update schema': {actions: 'assign schema'},\n 'behavior event': {actions: 'handle behavior event'},\n 'behavior action intends': {\n actions: [\n ({context, event}) => {\n Editor.withoutNormalizing(event.editor, () => {\n for (const actionIntend of event.actionIntends) {\n const action = {\n ...actionIntend,\n editor: event.editor,\n }\n\n performAction({context, action})\n }\n })\n event.editor.onChange()\n },\n enqueueActions(({context, event, enqueue}) => {\n if (\n event.actionIntends.some(\n (actionIntend) => actionIntend.type === 'reselect',\n )\n ) {\n enqueue.raise({\n type: 'selection',\n selection: toPortableTextRange(\n event.editor.children,\n event.editor.selection,\n context.schema,\n ),\n })\n }\n }),\n ],\n },\n },\n initial: 'pristine',\n states: {\n pristine: {\n initial: 'idle',\n states: {\n idle: {\n on: {\n normalizing: {\n target: 'normalizing',\n },\n patch: {\n actions: 'defer event',\n target: '#editor.dirty',\n },\n mutation: {\n actions: 'defer event',\n target: '#editor.dirty',\n },\n },\n },\n normalizing: {\n on: {\n 'done normalizing': {\n target: 'idle',\n },\n 'patch': {\n actions: 'defer event',\n },\n 'mutation': {\n actions: 'defer event',\n },\n },\n },\n },\n },\n dirty: {\n entry: ['emit pending events', 'clear pending events'],\n on: {\n patch: {\n actions: 'emit patch event',\n },\n mutation: {\n actions: 'emit mutation event',\n },\n },\n },\n },\n})\n","import {\n createContext,\n startTransition,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport type {EditorSelection} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\n\n/**\n * A React context for sharing the editor selection.\n */\nconst PortableTextEditorSelectionContext =\n createContext<EditorSelection | null>(null)\n\n/**\n * @public\n * Get the current editor selection from the React context.\n */\nexport const usePortableTextEditorSelection = (): EditorSelection => {\n const selection = useContext(PortableTextEditorSelectionContext)\n\n if (selection === undefined) {\n throw new Error(\n `The \\`usePortableTextEditorSelection\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n return selection\n}\nconst debug = debugWithName('component:PortableTextEditor:SelectionProvider')\nconst debugVerbose = debug.enabled && false\n\n/**\n * @internal\n */\nexport function PortableTextEditorSelectionProvider(\n props: React.PropsWithChildren<{\n editorActor: EditorActor\n }>,\n) {\n const [selection, setSelection] = useState<EditorSelection>(null)\n\n // Subscribe to, and handle changes from the editor\n useEffect(() => {\n debug('Subscribing to selection changes')\n const subscription = props.editorActor.on('selection', (event) => {\n // Set the selection state in a transition, we don't need the state immediately.\n startTransition(() => {\n if (debugVerbose) debug('Setting selection')\n setSelection(event.selection)\n })\n })\n\n return () => {\n debug('Unsubscribing to selection changes')\n subscription.unsubscribe()\n }\n }, [props.editorActor])\n\n return (\n <PortableTextEditorSelectionContext.Provider value={selection}>\n {props.children}\n </PortableTextEditorSelectionContext.Provider>\n )\n}\n","import {randomKey} from '@sanity/util/content'\n\n/**\n * @public\n */\nexport const defaultKeyGenerator = (): string => randomKey(12)\n","import type {\n ArrayDefinition,\n ArraySchemaType,\n Path,\n PortableTextBlock,\n PortableTextChild,\n PortableTextObject,\n} from '@sanity/types'\nimport {\n Component,\n useEffect,\n type MutableRefObject,\n type PropsWithChildren,\n} from 'react'\nimport {Subject} from 'rxjs'\nimport {createActor} from 'xstate'\nimport type {\n EditableAPI,\n EditableAPIDeleteOptions,\n EditorChange,\n EditorChanges,\n EditorSelection,\n PatchObservable,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport {debugWithName} from '../utils/debug'\nimport {getPortableTextMemberSchemaTypes} from '../utils/getPortableTextMemberSchemaTypes'\nimport {compileType} from '../utils/schema'\nimport {SlateContainer} from './components/SlateContainer'\nimport {Synchronizer} from './components/Synchronizer'\nimport {EditorActorContext} from './editor-actor-context'\nimport {editorMachine, type EditorActor} from './editor-machine'\nimport {PortableTextEditorContext} from './hooks/usePortableTextEditor'\nimport {PortableTextEditorSelectionProvider} from './hooks/usePortableTextEditorSelection'\nimport {PortableTextEditorReadOnlyContext} from './hooks/usePortableTextReadOnly'\nimport {defaultKeyGenerator} from './key-generator'\nimport type {Editor} from './use-editor'\n\nconst debug = debugWithName('component:PortableTextEditor')\n\n/**\n * Props for the PortableTextEditor component\n *\n * @public\n */\nexport type PortableTextEditorProps<\n TEditor extends Editor | undefined = undefined,\n> = PropsWithChildren<\n (TEditor extends Editor\n ? {\n /**\n * @alpha\n */\n editor: TEditor\n }\n : {\n editor?: undefined\n\n /**\n * Function that gets called when the editor changes the value\n */\n onChange: (change: EditorChange) => void\n\n /**\n * Schema type for the portable text field\n */\n schemaType: ArraySchemaType<PortableTextBlock> | ArrayDefinition\n\n /**\n * Maximum number of blocks to allow within the editor\n */\n maxBlocks?: number | string\n\n /**\n * Function used to generate keys for array items (`_key`)\n */\n keyGenerator?: () => string\n\n /**\n * Observable of local and remote patches for the edited value.\n */\n patches$?: PatchObservable\n\n /**\n * Backward compatibility (renamed to patches$).\n */\n incomingPatches$?: PatchObservable\n }) & {\n /**\n * Whether or not the editor should be in read-only mode\n */\n readOnly?: boolean\n\n /**\n * The current value of the portable text field\n */\n value?: PortableTextBlock[]\n\n /**\n * A ref to the editor instance\n */\n editorRef?: MutableRefObject<PortableTextEditor | null>\n }\n>\n\n/**\n * The main Portable Text Editor component.\n * @public\n */\nexport class PortableTextEditor extends Component<\n PortableTextEditorProps<Editor | undefined>\n> {\n public static displayName = 'PortableTextEditor'\n /**\n * An observable of all the editor changes.\n */\n public change$: EditorChanges = new Subject()\n /**\n * A lookup table for all the relevant schema types for this portable text type.\n */\n public schemaTypes: PortableTextMemberSchemaTypes\n /**\n * The editor API (currently implemented with Slate).\n */\n private editable?: EditableAPI\n private editorActor: EditorActor\n\n constructor(props: PortableTextEditorProps) {\n super(props)\n\n if (props.editor) {\n this.editorActor = props.editor\n this.editorActor.start()\n this.schemaTypes = this.editorActor.getSnapshot().context.schema\n } else {\n if (!props.schemaType) {\n throw new Error('PortableTextEditor: missing \"schemaType\" property')\n }\n\n if (props.incomingPatches$) {\n console.warn(\n `The prop 'incomingPatches$' is deprecated and renamed to 'patches$'`,\n )\n }\n\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n props.schemaType.hasOwnProperty('jsonType')\n ? props.schemaType\n : compileType(props.schemaType),\n )\n\n this.editorActor =\n props.editor ??\n createActor(editorMachine, {\n input: {\n keyGenerator: props.keyGenerator || defaultKeyGenerator,\n schema: this.schemaTypes,\n },\n })\n this.editorActor.start()\n }\n }\n\n componentDidUpdate(prevProps: PortableTextEditorProps) {\n // Set up the schema type lookup table again if the source schema type changes\n if (\n !this.props.editor &&\n !prevProps.editor &&\n this.props.schemaType !== prevProps.schemaType\n ) {\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n this.props.schemaType.hasOwnProperty('jsonType')\n ? this.props.schemaType\n : compileType(this.props.schemaType),\n )\n\n this.editorActor.send({\n type: 'update schema',\n schema: this.schemaTypes,\n })\n }\n\n if (this.props.editorRef !== prevProps.editorRef && this.props.editorRef) {\n this.props.editorRef.current = this\n }\n }\n\n public setEditable = (editable: EditableAPI) => {\n this.editable = {...this.editable, ...editable}\n }\n\n private getValue = () => {\n if (this.editable) {\n return this.editable.getValue()\n }\n\n return undefined\n }\n\n render() {\n const maxBlocks = !this.props.editor\n ? typeof this.props.maxBlocks === 'undefined'\n ? undefined\n : Number.parseInt(this.props.maxBlocks.toString(), 10) || undefined\n : undefined\n\n const readOnly = Boolean(this.props.readOnly)\n const legacyPatches = !this.props.editor\n ? (this.props.incomingPatches$ ?? this.props.patches$)\n : undefined\n\n return (\n <>\n {legacyPatches ? (\n <RoutePatchesObservableToEditorActor\n editorActor={this.editorActor}\n patches$={legacyPatches}\n />\n ) : null}\n <EditorActorContext.Provider value={this.editorActor}>\n <SlateContainer\n editorActor={this.editorActor}\n maxBlocks={maxBlocks}\n portableTextEditor={this}\n readOnly={readOnly}\n >\n <PortableTextEditorContext.Provider value={this}>\n <PortableTextEditorReadOnlyContext.Provider value={readOnly}>\n <PortableTextEditorSelectionProvider\n editorActor={this.editorActor}\n >\n <Synchronizer\n editorActor={this.editorActor}\n getValue={this.getValue}\n onChange={(change) => {\n if (!this.props.editor) {\n this.props.onChange(change)\n }\n /**\n * For backwards compatibility, we relay all changes to the\n * `change$` Subject as well.\n */\n this.change$.next(change)\n }}\n value={this.props.value}\n />\n {this.props.children}\n </PortableTextEditorSelectionProvider>\n </PortableTextEditorReadOnlyContext.Provider>\n </PortableTextEditorContext.Provider>\n </SlateContainer>\n </EditorActorContext.Provider>\n </>\n )\n }\n\n // Static API methods\n static activeAnnotations = (\n editor: PortableTextEditor,\n ): PortableTextObject[] => {\n return editor && editor.editable ? editor.editable.activeAnnotations() : []\n }\n static isAnnotationActive = (\n editor: PortableTextEditor,\n annotationType: PortableTextObject['_type'],\n ): boolean => {\n return editor && editor.editable\n ? editor.editable.isAnnotationActive(annotationType)\n : false\n }\n static addAnnotation = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n value?: {[prop: string]: unknown},\n ):\n | {\n /**\n * @deprecated An annotation may be applied to multiple blocks, resulting\n * in multiple `markDef`'s being created. Use `markDefPaths` instead.\n */\n markDefPath: Path\n markDefPaths: Array<Path>\n /**\n * @deprecated Does not return anything meaningful since an annotation\n * can span multiple blocks and spans. If references the span closest\n * to the focus point of the selection.\n */\n spanPath: Path\n }\n | undefined => editor.editable?.addAnnotation(type, value)\n static blur = (editor: PortableTextEditor): void => {\n debug('Host blurred')\n editor.editable?.blur()\n }\n static delete = (\n editor: PortableTextEditor,\n selection: EditorSelection,\n options?: EditableAPIDeleteOptions,\n ) => editor.editable?.delete(selection, options)\n static findDOMNode = (\n editor: PortableTextEditor,\n element: PortableTextBlock | PortableTextChild,\n ) => {\n return editor.editable?.findDOMNode(element)\n }\n static findByPath = (editor: PortableTextEditor, path: Path) => {\n return editor.editable?.findByPath(path) || []\n }\n static focus = (editor: PortableTextEditor): void => {\n debug('Host requesting focus')\n editor.editable?.focus()\n }\n static focusBlock = (editor: PortableTextEditor) => {\n return editor.editable?.focusBlock()\n }\n static focusChild = (\n editor: PortableTextEditor,\n ): PortableTextChild | undefined => {\n return editor.editable?.focusChild()\n }\n static getSelection = (editor: PortableTextEditor) => {\n return editor.editable ? editor.editable.getSelection() : null\n }\n static getValue = (editor: PortableTextEditor) => {\n return editor.editable?.getValue()\n }\n static hasBlockStyle = (editor: PortableTextEditor, blockStyle: string) => {\n return editor.editable?.hasBlockStyle(blockStyle)\n }\n static hasListStyle = (editor: PortableTextEditor, listStyle: string) => {\n return editor.editable?.hasListStyle(listStyle)\n }\n static isCollapsedSelection = (editor: PortableTextEditor) =>\n editor.editable?.isCollapsedSelection()\n static isExpandedSelection = (editor: PortableTextEditor) =>\n editor.editable?.isExpandedSelection()\n static isMarkActive = (editor: PortableTextEditor, mark: string) =>\n editor.editable?.isMarkActive(mark)\n static insertChild = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n value?: {[prop: string]: unknown},\n ): Path | undefined => {\n debug(`Host inserting child`)\n return editor.editable?.insertChild(type, value)\n }\n static insertBlock = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n value?: {[prop: string]: unknown},\n ): Path | undefined => {\n return editor.editable?.insertBlock(type, value)\n }\n static insertBreak = (editor: PortableTextEditor): void => {\n return editor.editable?.insertBreak()\n }\n static isVoid = (\n editor: PortableTextEditor,\n element: PortableTextBlock | PortableTextChild,\n ) => {\n return editor.editable?.isVoid(element)\n }\n static isObjectPath = (_editor: PortableTextEditor, path: Path): boolean => {\n if (!path || !Array.isArray(path)) return false\n const isChildObjectEditPath = path.length > 3 && path[1] === 'children'\n const isBlockObjectEditPath = path.length > 1 && path[1] !== 'children'\n return isBlockObjectEditPath || isChildObjectEditPath\n }\n static marks = (editor: PortableTextEditor) => {\n return editor.editable?.marks()\n }\n static select = (\n editor: PortableTextEditor,\n selection: EditorSelection | null,\n ) => {\n debug(`Host setting selection`, selection)\n editor.editable?.select(selection)\n }\n static removeAnnotation = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n ) => editor.editable?.removeAnnotation(type)\n static toggleBlockStyle = (\n editor: PortableTextEditor,\n blockStyle: string,\n ) => {\n debug(`Host is toggling block style`)\n return editor.editable?.toggleBlockStyle(blockStyle)\n }\n static toggleList = (editor: PortableTextEditor, listStyle: string): void => {\n return editor.editable?.toggleList(listStyle)\n }\n static toggleMark = (editor: PortableTextEditor, mark: string): void => {\n debug(`Host toggling mark`, mark)\n editor.editable?.toggleMark(mark)\n }\n static getFragment = (\n editor: PortableTextEditor,\n ): PortableTextBlock[] | undefined => {\n debug(`Host getting fragment`)\n return editor.editable?.getFragment()\n }\n static undo = (editor: PortableTextEditor): void => {\n debug('Host undoing')\n editor.editable?.undo()\n }\n static redo = (editor: PortableTextEditor): void => {\n debug('Host redoing')\n editor.editable?.redo()\n }\n static isSelectionsOverlapping = (\n editor: PortableTextEditor,\n selectionA: EditorSelection,\n selectionB: EditorSelection,\n ) => {\n return editor.editable?.isSelectionsOverlapping(selectionA, selectionB)\n }\n}\n\nfunction RoutePatchesObservableToEditorActor(props: {\n editorActor: EditorActor\n patches$: PatchObservable\n}) {\n useEffect(() => {\n const subscription = props.patches$.subscribe((payload) => {\n props.editorActor.send({\n type: 'patches',\n ...payload,\n })\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [props.editorActor, props.patches$])\n\n return null\n}\n","import type {\n Path,\n PortableTextObject,\n PortableTextTextBlock,\n} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {\n startTransition,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactElement,\n} from 'react'\nimport {Text} from 'slate'\nimport {useSelected, type RenderLeafProps} from 'slate-react'\nimport type {\n BlockAnnotationRenderProps,\n BlockChildRenderProps,\n BlockDecoratorRenderProps,\n PortableTextMemberSchemaTypes,\n RenderAnnotationFunction,\n RenderChildFunction,\n RenderDecoratorFunction,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\nimport {usePortableTextEditor} from '../hooks/usePortableTextEditor'\nimport {DefaultAnnotation} from '../nodes/DefaultAnnotation'\nimport {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('components:Leaf')\n\nconst EMPTY_MARKS: string[] = []\n\n/**\n * @internal\n */\nexport interface LeafProps extends RenderLeafProps {\n editorActor: EditorActor\n children: ReactElement\n schemaTypes: PortableTextMemberSchemaTypes\n renderAnnotation?: RenderAnnotationFunction\n renderChild?: RenderChildFunction\n renderDecorator?: RenderDecoratorFunction\n readOnly: boolean\n}\n\n/**\n * Renders Portable Text span nodes in Slate\n * @internal\n */\nexport const Leaf = (props: LeafProps) => {\n const {\n editorActor,\n attributes,\n children,\n leaf,\n schemaTypes,\n renderChild,\n renderDecorator,\n renderAnnotation,\n } = props\n const spanRef = useRef<HTMLElement>(null)\n const portableTextEditor = usePortableTextEditor()\n const blockSelected = useSelected()\n const [focused, setFocused] = useState(false)\n const [selected, setSelected] = useState(false)\n const block = children.props.parent as PortableTextTextBlock | undefined\n const path: Path = useMemo(\n () => (block ? [{_key: block?._key}, 'children', {_key: leaf._key}] : []),\n [block, leaf._key],\n )\n const decoratorValues = useMemo(\n () => schemaTypes.decorators.map((dec) => dec.value),\n [schemaTypes.decorators],\n )\n const marks: string[] = useMemo(\n () =>\n uniq(\n (leaf.marks || EMPTY_MARKS).filter((mark) =>\n decoratorValues.includes(mark),\n ),\n ),\n [decoratorValues, leaf.marks],\n )\n const annotationMarks = Array.isArray(leaf.marks) ? leaf.marks : EMPTY_MARKS\n const annotations = useMemo(\n () =>\n annotationMarks\n .map(\n (mark) =>\n !decoratorValues.includes(mark) &&\n block?.markDefs?.find((def) => def._key === mark),\n )\n .filter(Boolean) as PortableTextObject[],\n [annotationMarks, block, decoratorValues],\n )\n\n const shouldTrackSelectionAndFocus = annotations.length > 0 && blockSelected\n\n useEffect(() => {\n if (!shouldTrackSelectionAndFocus) {\n setFocused(false)\n return\n }\n const sel = PortableTextEditor.getSelection(portableTextEditor)\n if (\n sel &&\n isEqual(sel.focus.path, path) &&\n PortableTextEditor.isCollapsedSelection(portableTextEditor)\n ) {\n startTransition(() => {\n setFocused(true)\n })\n }\n }, [shouldTrackSelectionAndFocus, path, portableTextEditor])\n\n // Function to check if this leaf is currently inside the user's text selection\n const setSelectedFromRange = useCallback(() => {\n if (!shouldTrackSelectionAndFocus) {\n return\n }\n debug('Setting selection and focus from range')\n const winSelection = window.getSelection()\n if (!winSelection) {\n setSelected(false)\n return\n }\n if (winSelection && winSelection.rangeCount > 0) {\n const range = winSelection.getRangeAt(0)\n if (spanRef.current && range.intersectsNode(spanRef.current)) {\n setSelected(true)\n } else {\n setSelected(false)\n }\n } else {\n setSelected(false)\n }\n }, [shouldTrackSelectionAndFocus])\n\n useEffect(() => {\n if (!shouldTrackSelectionAndFocus) {\n return undefined\n }\n\n const onBlur = editorActor.on('blur', () => {\n setFocused(false)\n setSelected(false)\n })\n\n const onFocus = editorActor.on('focus', () => {\n const sel = PortableTextEditor.getSelection(portableTextEditor)\n if (\n sel &&\n isEqual(sel.focus.path, path) &&\n PortableTextEditor.isCollapsedSelection(portableTextEditor)\n ) {\n setFocused(true)\n }\n setSelectedFromRange()\n })\n\n const onSelection = editorActor.on('selection', (event) => {\n if (\n event.selection &&\n isEqual(event.selection.focus.path, path) &&\n PortableTextEditor.isCollapsedSelection(portableTextEditor)\n ) {\n setFocused(true)\n } else {\n setFocused(false)\n }\n setSelectedFromRange()\n })\n\n return () => {\n onBlur.unsubscribe()\n onFocus.unsubscribe()\n onSelection.unsubscribe()\n }\n }, [\n editorActor,\n path,\n portableTextEditor,\n setSelectedFromRange,\n shouldTrackSelectionAndFocus,\n ])\n\n useEffect(() => setSelectedFromRange(), [setSelectedFromRange])\n\n const content = useMemo(() => {\n let returnedChildren = children\n // Render text nodes\n if (Text.isText(leaf) && leaf._type === schemaTypes.span.name) {\n marks.forEach((mark) => {\n const schemaType = schemaTypes.decorators.find(\n (dec) => dec.value === mark,\n )\n if (schemaType && renderDecorator) {\n const _props: Omit<BlockDecoratorRenderProps, 'type'> =\n Object.defineProperty(\n {\n children: returnedChildren,\n editorElementRef: spanRef,\n focused,\n path,\n selected,\n schemaType,\n value: mark,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaType\n },\n },\n )\n returnedChildren = renderDecorator(\n _props as BlockDecoratorRenderProps,\n )\n }\n })\n\n if (block && annotations.length > 0) {\n annotations.forEach((annotation) => {\n const schemaType = schemaTypes.annotations.find(\n (t) => t.name === annotation._type,\n )\n if (schemaType) {\n if (renderAnnotation) {\n const _props: Omit<BlockAnnotationRenderProps, 'type'> =\n Object.defineProperty(\n {\n block,\n children: returnedChildren,\n editorElementRef: spanRef,\n focused,\n path,\n selected,\n schemaType,\n value: annotation,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaType\n },\n },\n )\n\n returnedChildren = (\n <span ref={spanRef}>\n {renderAnnotation(_props as BlockAnnotationRenderProps)}\n </span>\n )\n } else {\n returnedChildren = (\n <DefaultAnnotation annotation={annotation}>\n <span ref={spanRef}>{returnedChildren}</span>\n </DefaultAnnotation>\n )\n }\n }\n })\n }\n if (block && renderChild) {\n const child = block.children.find((_child) => _child._key === leaf._key) // Ensure object equality\n if (child) {\n const defaultRendered = <>{returnedChildren}</>\n const _props: Omit<BlockChildRenderProps, 'type'> =\n Object.defineProperty(\n {\n annotations,\n children: defaultRendered,\n editorElementRef: spanRef,\n focused,\n path,\n schemaType: schemaTypes.span,\n selected,\n value: child,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaTypes.span\n },\n },\n )\n returnedChildren = renderChild(_props as BlockChildRenderProps)\n }\n }\n }\n return returnedChildren\n }, [\n annotations,\n block,\n children,\n focused,\n leaf,\n marks,\n path,\n renderAnnotation,\n renderChild,\n renderDecorator,\n schemaTypes.annotations,\n schemaTypes.decorators,\n schemaTypes.span,\n selected,\n ])\n return useMemo(\n () => (\n <span key={leaf._key} {...attributes} ref={spanRef}>\n {content}\n </span>\n ),\n [leaf, attributes, content],\n )\n}\n\nLeaf.displayName = 'Leaf'\n","import type {BaseEditor, Operation} from 'slate'\nimport type {ReactEditor} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../types/editor'\n\n// React Compiler considers `slateEditor` as immutable, and opts-out if we do this inline in a useEffect, doing it in a function moves it out of the scope, and opts-in again for the rest of the component.\nexport function withSyncRangeDecorations(\n slateEditor: BaseEditor & ReactEditor & PortableTextSlateEditor,\n syncRangeDecorations: (operation?: Operation) => void,\n) {\n const originalApply = slateEditor.apply\n slateEditor.apply = (op: Operation) => {\n originalApply(op)\n if (op.type !== 'set_selection') {\n syncRangeDecorations(op)\n }\n }\n return () => {\n slateEditor.apply = originalApply\n }\n}\n","import type {PortableTextBlock} from '@sanity/types'\nimport {isEqual, noop} from 'lodash'\nimport {\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type CSSProperties,\n type FocusEventHandler,\n type KeyboardEvent,\n type MutableRefObject,\n type TextareaHTMLAttributes,\n} from 'react'\nimport {\n Editor,\n Node,\n Path,\n Range as SlateRange,\n Transforms,\n type BaseRange,\n type NodeEntry,\n type Operation,\n type Text,\n} from 'slate'\nimport {\n ReactEditor,\n Editable as SlateEditable,\n useSlate,\n type RenderElementProps,\n type RenderLeafProps,\n} from 'slate-react'\nimport type {\n EditorSelection,\n OnCopyFn,\n OnPasteFn,\n RangeDecoration,\n RenderAnnotationFunction,\n RenderBlockFunction,\n RenderChildFunction,\n RenderDecoratorFunction,\n RenderListItemFunction,\n RenderPlaceholderFunction,\n RenderStyleFunction,\n ScrollSelectionIntoViewFunction,\n} from '../types/editor'\nimport type {HotkeyOptions} from '../types/options'\nimport type {SlateTextBlock, VoidElement} from '../types/slate'\nimport {debugWithName} from '../utils/debug'\nimport {\n moveRangeByOperation,\n toPortableTextRange,\n toSlateRange,\n} from '../utils/ranges'\nimport {normalizeSelection} from '../utils/selection'\nimport {\n fromSlateValue,\n isEqualToEmptyEditor,\n toSlateValue,\n} from '../utils/values'\nimport {Element} from './components/Element'\nimport {Leaf} from './components/Leaf'\nimport {EditorActorContext} from './editor-actor-context'\nimport {usePortableTextEditor} from './hooks/usePortableTextEditor'\nimport {usePortableTextEditorReadOnlyStatus} from './hooks/usePortableTextReadOnly'\nimport {createWithHotkeys, createWithInsertData} from './plugins'\nimport {PortableTextEditor} from './PortableTextEditor'\nimport {withSyncRangeDecorations} from './withSyncRangeDecorations'\n\nconst debug = debugWithName('component:Editable')\n\nconst PLACEHOLDER_STYLE: CSSProperties = {\n position: 'absolute',\n userSelect: 'none',\n pointerEvents: 'none',\n left: 0,\n right: 0,\n}\n\ninterface BaseRangeWithDecoration extends BaseRange {\n rangeDecoration: RangeDecoration\n}\n\n/**\n * @public\n */\nexport type PortableTextEditableProps = Omit<\n TextareaHTMLAttributes<HTMLDivElement>,\n 'onPaste' | 'onCopy' | 'onBeforeInput'\n> & {\n hotkeys?: HotkeyOptions\n onBeforeInput?: (event: InputEvent) => void\n onPaste?: OnPasteFn\n onCopy?: OnCopyFn\n ref: MutableRefObject<HTMLDivElement | null>\n rangeDecorations?: RangeDecoration[]\n renderAnnotation?: RenderAnnotationFunction\n renderBlock?: RenderBlockFunction\n renderChild?: RenderChildFunction\n renderDecorator?: RenderDecoratorFunction\n renderListItem?: RenderListItemFunction\n renderPlaceholder?: RenderPlaceholderFunction\n renderStyle?: RenderStyleFunction\n scrollSelectionIntoView?: ScrollSelectionIntoViewFunction\n selection?: EditorSelection\n spellCheck?: boolean\n}\n\n/**\n * @public\n */\nexport const PortableTextEditable = forwardRef<\n Omit<HTMLDivElement, 'as' | 'onPaste' | 'onBeforeInput'>,\n PortableTextEditableProps\n>(function PortableTextEditable(props, forwardedRef) {\n const {\n hotkeys,\n onBlur,\n onFocus,\n onBeforeInput,\n onPaste,\n onCopy,\n onClick,\n rangeDecorations,\n renderAnnotation,\n renderBlock,\n renderChild,\n renderDecorator,\n renderListItem,\n renderPlaceholder,\n renderStyle,\n selection: propsSelection,\n scrollSelectionIntoView,\n spellCheck,\n ...restProps\n } = props\n\n const portableTextEditor = usePortableTextEditor()\n const readOnly = usePortableTextEditorReadOnlyStatus()\n const ref = useRef<HTMLDivElement | null>(null)\n const [editableElement, setEditableElement] = useState<HTMLDivElement | null>(\n null,\n )\n const [hasInvalidValue, setHasInvalidValue] = useState(false)\n const [rangeDecorationState, setRangeDecorationsState] = useState<\n BaseRangeWithDecoration[]\n >([])\n\n // Forward ref to parent component\n useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(\n forwardedRef,\n () => ref.current,\n )\n\n const rangeDecorationsRef = useRef(rangeDecorations)\n\n const editorActor = useContext(EditorActorContext)\n const {schemaTypes} = portableTextEditor\n const slateEditor = useSlate()\n\n const blockTypeName = schemaTypes.block.name\n\n // Output a minimal React editor inside Editable when in readOnly mode.\n // NOTE: make sure all the plugins used here can be safely run over again at any point.\n // There will be a problem if they redefine editor methods and then calling the original method within themselves.\n useMemo(() => {\n // React/UI-specific plugins\n const withInsertData = createWithInsertData(editorActor, schemaTypes)\n\n if (readOnly) {\n debug('Editable is in read only mode')\n return withInsertData(slateEditor)\n }\n const withHotKeys = createWithHotkeys(\n editorActor,\n portableTextEditor,\n hotkeys,\n )\n\n debug('Editable is in edit mode')\n return withInsertData(withHotKeys(slateEditor))\n }, [\n editorActor,\n hotkeys,\n portableTextEditor,\n readOnly,\n schemaTypes,\n slateEditor,\n ])\n\n const renderElement = useCallback(\n (eProps: RenderElementProps) => (\n <Element\n {...eProps}\n readOnly={readOnly}\n renderBlock={renderBlock}\n renderChild={renderChild}\n renderListItem={renderListItem}\n renderStyle={renderStyle}\n schemaTypes={schemaTypes}\n spellCheck={spellCheck}\n />\n ),\n [\n schemaTypes,\n spellCheck,\n readOnly,\n renderBlock,\n renderChild,\n renderListItem,\n renderStyle,\n ],\n )\n\n const renderLeaf = useCallback(\n (\n lProps: RenderLeafProps & {\n leaf: Text & {placeholder?: boolean; rangeDecoration?: RangeDecoration}\n },\n ) => {\n if (lProps.leaf._type === 'span') {\n let rendered = (\n <Leaf\n {...lProps}\n editorActor={editorActor}\n schemaTypes={schemaTypes}\n renderAnnotation={renderAnnotation}\n renderChild={renderChild}\n renderDecorator={renderDecorator}\n readOnly={readOnly}\n />\n )\n if (\n renderPlaceholder &&\n lProps.leaf.placeholder &&\n lProps.text.text === ''\n ) {\n return (\n <>\n <span style={PLACEHOLDER_STYLE} contentEditable={false}>\n {renderPlaceholder()}\n </span>\n {rendered}\n </>\n )\n }\n const decoration = lProps.leaf.rangeDecoration\n if (decoration) {\n rendered = decoration.component({children: rendered})\n }\n return rendered\n }\n return lProps.children\n },\n [\n editorActor,\n readOnly,\n renderAnnotation,\n renderChild,\n renderDecorator,\n renderPlaceholder,\n schemaTypes,\n ],\n )\n\n const restoreSelectionFromProps = useCallback(() => {\n if (propsSelection) {\n debug(`Selection from props ${JSON.stringify(propsSelection)}`)\n const normalizedSelection = normalizeSelection(\n propsSelection,\n fromSlateValue(slateEditor.children, blockTypeName),\n )\n if (normalizedSelection !== null) {\n debug(\n `Normalized selection from props ${JSON.stringify(normalizedSelection)}`,\n )\n const slateRange = toSlateRange(normalizedSelection, slateEditor)\n if (slateRange) {\n Transforms.select(slateEditor, slateRange)\n // Output selection here in those cases where the editor selection was the same, and there are no set_selection operations made.\n // The selection is usually automatically emitted to change$ by the withPortableTextSelections plugin whenever there is a set_selection operation applied.\n if (!slateEditor.operations.some((o) => o.type === 'set_selection')) {\n editorActor.send({\n type: 'selection',\n selection: normalizedSelection,\n })\n }\n slateEditor.onChange()\n }\n }\n }\n }, [blockTypeName, editorActor, propsSelection, slateEditor])\n\n const syncRangeDecorations = useCallback(\n (operation?: Operation) => {\n if (rangeDecorations && rangeDecorations.length > 0) {\n const newSlateRanges: BaseRangeWithDecoration[] = []\n rangeDecorations.forEach((rangeDecorationItem) => {\n const slateRange = toSlateRange(\n rangeDecorationItem.selection,\n slateEditor,\n )\n if (!SlateRange.isRange(slateRange)) {\n if (rangeDecorationItem.onMoved) {\n rangeDecorationItem.onMoved({\n newSelection: null,\n rangeDecoration: rangeDecorationItem,\n origin: 'local',\n })\n }\n return\n }\n let newRange: BaseRange | null | undefined\n if (operation) {\n newRange = moveRangeByOperation(slateRange, operation)\n if (\n (newRange && newRange !== slateRange) ||\n (newRange === null && slateRange)\n ) {\n const value = PortableTextEditor.getValue(portableTextEditor)\n const newRangeSelection = toPortableTextRange(\n value,\n newRange,\n schemaTypes,\n )\n if (rangeDecorationItem.onMoved) {\n rangeDecorationItem.onMoved({\n newSelection: newRangeSelection,\n rangeDecoration: rangeDecorationItem,\n origin: 'local',\n })\n }\n }\n }\n // If the newRange is null, it means that the range is not valid anymore and should be removed\n // If it's undefined, it means that the slateRange is still valid and should be kept\n if (newRange !== null) {\n newSlateRanges.push({\n ...(newRange || slateRange),\n rangeDecoration: rangeDecorationItem,\n })\n }\n })\n if (newSlateRanges.length > 0) {\n setRangeDecorationsState(newSlateRanges)\n return\n }\n }\n setRangeDecorationsState((rangeDecorationState) => {\n // If there's state then we want to reset\n if (rangeDecorationState.length > 0) {\n return []\n }\n // Otherwise we no-op, React will skip a state update if what we return has reference equality to the previous state\n return rangeDecorationState\n })\n },\n [portableTextEditor, rangeDecorations, schemaTypes, slateEditor],\n )\n\n // Restore selection from props when the editor has been initialized properly with it's value\n useEffect(() => {\n const onReady = editorActor.on('ready', () => {\n restoreSelectionFromProps()\n })\n const onInvalidValue = editorActor.on('invalid value', () => {\n setHasInvalidValue(true)\n })\n const onValueChanged = editorActor.on('value changed', () => {\n setHasInvalidValue(false)\n })\n\n return () => {\n onReady.unsubscribe()\n onInvalidValue.unsubscribe()\n onValueChanged.unsubscribe()\n }\n }, [editorActor, restoreSelectionFromProps])\n\n // Restore selection from props when it changes\n useEffect(() => {\n if (propsSelection && !hasInvalidValue) {\n restoreSelectionFromProps()\n }\n }, [hasInvalidValue, propsSelection, restoreSelectionFromProps])\n\n const [syncedRangeDecorations, setSyncedRangeDecorations] = useState(false)\n useEffect(() => {\n if (!syncedRangeDecorations) {\n // We only want this to run once, on mount\n setSyncedRangeDecorations(true)\n syncRangeDecorations()\n }\n }, [syncRangeDecorations, syncedRangeDecorations])\n\n useEffect(() => {\n if (!isEqual(rangeDecorations, rangeDecorationsRef.current)) {\n syncRangeDecorations()\n }\n rangeDecorationsRef.current = rangeDecorations\n }, [rangeDecorations, syncRangeDecorations])\n\n // Sync range decorations after an operation is applied\n useEffect(() => {\n const teardown = withSyncRangeDecorations(slateEditor, syncRangeDecorations)\n return () => teardown()\n }, [slateEditor, syncRangeDecorations])\n\n // Handle from props onCopy function\n const handleCopy = useCallback(\n (event: ClipboardEvent<HTMLDivElement>): void | ReactEditor => {\n if (onCopy) {\n const result = onCopy(event)\n // CopyFn may return something to avoid doing default stuff\n if (result !== undefined) {\n event.preventDefault()\n }\n }\n },\n [onCopy],\n )\n\n // Handle incoming pasting events in the editor\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLDivElement>): Promise<void> | void => {\n event.preventDefault()\n if (!slateEditor.selection) {\n return\n }\n if (!onPaste) {\n debug('Pasting normally')\n slateEditor.insertData(event.clipboardData)\n return\n }\n\n const value = PortableTextEditor.getValue(portableTextEditor)\n const ptRange = toPortableTextRange(\n value,\n slateEditor.selection,\n schemaTypes,\n )\n const path = ptRange?.focus.path || []\n const onPasteResult = onPaste({event, value, path, schemaTypes})\n\n if (onPasteResult === undefined) {\n debug('No result from custom paste handler, pasting normally')\n slateEditor.insertData(event.clipboardData)\n } else {\n // Resolve it as promise (can be either async promise or sync return value)\n editorActor.send({type: 'loading'})\n Promise.resolve(onPasteResult)\n .then((result) => {\n debug('Custom paste function from client resolved', result)\n if (!result || !result.insert) {\n debug('No result from custom paste handler, pasting normally')\n slateEditor.insertData(event.clipboardData)\n } else if (result.insert) {\n slateEditor.insertFragment(\n toSlateValue(result.insert as PortableTextBlock[], {\n schemaTypes,\n }),\n )\n } else {\n console.warn(\n 'Your onPaste function returned something unexpected:',\n result,\n )\n }\n })\n .catch((error) => {\n console.error(error)\n return error\n })\n .finally(() => {\n editorActor.send({type: 'done loading'})\n })\n }\n },\n [editorActor, onPaste, portableTextEditor, schemaTypes, slateEditor],\n )\n\n const handleOnFocus: FocusEventHandler<HTMLDivElement> = useCallback(\n (event) => {\n if (onFocus) {\n onFocus(event)\n }\n if (!event.isDefaultPrevented()) {\n const selection = PortableTextEditor.getSelection(portableTextEditor)\n // Create an editor selection if it does'nt exist\n if (selection === null) {\n Transforms.select(slateEditor, Editor.start(slateEditor, []))\n slateEditor.onChange()\n }\n editorActor.send({type: 'focus', event})\n const newSelection = PortableTextEditor.getSelection(portableTextEditor)\n // If the selection is the same, emit it explicitly here as there is no actual onChange event triggered.\n if (selection === newSelection) {\n editorActor.send({\n type: 'selection',\n selection,\n })\n }\n }\n },\n [editorActor, onFocus, portableTextEditor, slateEditor],\n )\n\n const handleClick = useCallback(\n (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n if (onClick) {\n onClick(event)\n }\n // Inserts a new block if it's clicking on the editor, focused on the last block and it's a void element\n if (slateEditor.selection && event.target === event.currentTarget) {\n const [lastBlock, path] = Node.last(slateEditor, [])\n const focusPath = slateEditor.selection.focus.path.slice(0, 1)\n const lastPath = path.slice(0, 1)\n if (Path.equals(focusPath, lastPath)) {\n const node = Node.descendant(slateEditor, path.slice(0, 1)) as\n | SlateTextBlock\n | VoidElement\n if (lastBlock && Editor.isVoid(slateEditor, node)) {\n Transforms.insertNodes(\n slateEditor,\n slateEditor.pteCreateTextBlock({decorators: []}),\n )\n slateEditor.onChange()\n }\n }\n }\n },\n [onClick, slateEditor],\n )\n\n const handleOnBlur: FocusEventHandler<HTMLDivElement> = useCallback(\n (event) => {\n if (onBlur) {\n onBlur(event)\n }\n if (!event.isPropagationStopped()) {\n editorActor.send({type: 'blur', event})\n }\n },\n [editorActor, onBlur],\n )\n\n const handleOnBeforeInput = useCallback(\n (event: InputEvent) => {\n if (onBeforeInput) {\n onBeforeInput(event)\n }\n },\n [onBeforeInput],\n )\n\n // This function will handle unexpected DOM changes inside the Editable rendering,\n // and make sure that we can maintain a stable slateEditor.selection when that happens.\n //\n // For example, if this Editable is rendered inside something that might re-render\n // this component (hidden contexts) while the user is still actively changing the\n // contentEditable, this could interfere with the intermediate DOM selection,\n // which again could be picked up by ReactEditor's event listeners.\n // If that range is invalid at that point, the slate.editorSelection could be\n // set either wrong, or invalid, to which slateEditor will throw exceptions\n // that are impossible to recover properly from or result in a wrong selection.\n //\n // Also the other way around, when the ReactEditor will try to create a DOM Range\n // from the current slateEditor.selection, it may throw unrecoverable errors\n // if the current editor.selection is invalid according to the DOM.\n // If this is the case, default to selecting the top of the document, if the\n // user already had a selection.\n const validateSelection = useCallback(() => {\n if (!slateEditor.selection) {\n return\n }\n const root = ReactEditor.findDocumentOrShadowRoot(slateEditor)\n const {activeElement} = root\n // Return if the editor isn't the active element\n if (ref.current !== activeElement) {\n return\n }\n const window = ReactEditor.getWindow(slateEditor)\n const domSelection = window.getSelection()\n if (!domSelection || domSelection.rangeCount === 0) {\n return\n }\n const existingDOMRange = domSelection.getRangeAt(0)\n try {\n const newDOMRange = ReactEditor.toDOMRange(\n slateEditor,\n slateEditor.selection,\n )\n if (\n newDOMRange.startOffset !== existingDOMRange.startOffset ||\n newDOMRange.endOffset !== existingDOMRange.endOffset\n ) {\n debug('DOM range out of sync, validating selection')\n // Remove all ranges temporary\n domSelection?.removeAllRanges()\n // Set the correct range\n domSelection.addRange(newDOMRange)\n }\n } catch {\n debug(`Could not resolve selection, selecting top document`)\n // Deselect the editor\n Transforms.deselect(slateEditor)\n // Select top document if there is a top block to select\n if (slateEditor.children.length > 0) {\n Transforms.select(slateEditor, [0, 0])\n }\n slateEditor.onChange()\n }\n }, [ref, slateEditor])\n\n // Observe mutations (child list and subtree) to this component's DOM,\n // and make sure the editor selection is valid when that happens.\n useEffect(() => {\n if (editableElement) {\n const mutationObserver = new MutationObserver(validateSelection)\n mutationObserver.observe(editableElement, {\n attributeOldValue: false,\n attributes: false,\n characterData: false,\n childList: true,\n subtree: true,\n })\n return () => {\n mutationObserver.disconnect()\n }\n }\n return undefined\n }, [validateSelection, editableElement])\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (props.onKeyDown) {\n props.onKeyDown(event)\n }\n if (!event.isDefaultPrevented()) {\n slateEditor.pteWithHotKeys(event)\n }\n },\n [props, slateEditor],\n )\n\n const scrollSelectionIntoViewToSlate = useMemo(() => {\n // Use slate-react default scroll into view\n if (scrollSelectionIntoView === undefined) {\n return undefined\n }\n // Disable scroll into view totally\n if (scrollSelectionIntoView === null) {\n return noop\n }\n // Translate PortableTextEditor prop fn to Slate plugin fn\n return (_editor: ReactEditor, domRange: Range) => {\n scrollSelectionIntoView(portableTextEditor, domRange)\n }\n }, [portableTextEditor, scrollSelectionIntoView])\n\n const decorate: (entry: NodeEntry) => BaseRange[] = useCallback(\n ([, path]) => {\n if (isEqualToEmptyEditor(slateEditor.children, schemaTypes)) {\n return [\n {\n anchor: {\n path: [0, 0],\n offset: 0,\n },\n focus: {\n path: [0, 0],\n offset: 0,\n },\n placeholder: true,\n },\n ]\n }\n // Editor node has a path length of 0 (should never be decorated)\n if (path.length === 0) {\n return []\n }\n const result = rangeDecorationState.filter((item) => {\n // Special case in order to only return one decoration for collapsed ranges\n if (SlateRange.isCollapsed(item)) {\n // Collapsed ranges should only be decorated if they are on a block child level (length 2)\n if (path.length !== 2) {\n return false\n }\n return (\n Path.equals(item.focus.path, path) &&\n Path.equals(item.anchor.path, path)\n )\n }\n // Include decorations that either include or intersects with this path\n return (\n SlateRange.intersection(item, {\n anchor: {path, offset: 0},\n focus: {path, offset: 0},\n }) || SlateRange.includes(item, path)\n )\n })\n if (result.length > 0) {\n return result\n }\n return []\n },\n [slateEditor, schemaTypes, rangeDecorationState],\n )\n\n // Set the forwarded ref to be the Slate editable DOM element\n // Also set the editable element in a state so that the MutationObserver\n // is setup when this element is ready.\n useEffect(() => {\n ref.current = ReactEditor.toDOMNode(\n slateEditor,\n slateEditor,\n ) as HTMLDivElement | null\n setEditableElement(ref.current)\n }, [slateEditor, ref])\n\n if (!portableTextEditor) {\n return null\n }\n return hasInvalidValue ? null : (\n <SlateEditable\n {...restProps}\n autoFocus={false}\n className={restProps.className || 'pt-editable'}\n decorate={decorate}\n onBlur={handleOnBlur}\n onCopy={handleCopy}\n onClick={handleClick}\n onDOMBeforeInput={handleOnBeforeInput}\n onFocus={handleOnFocus}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n readOnly={readOnly}\n // We have implemented our own placeholder logic with decorations.\n // This 'renderPlaceholder' should not be used.\n renderPlaceholder={undefined}\n renderElement={renderElement}\n renderLeaf={renderLeaf}\n scrollSelectionIntoView={scrollSelectionIntoViewToSlate}\n />\n )\n})\n\nPortableTextEditable.displayName = 'ForwardRef(PortableTextEditable)'\n","import type {\n ArrayDefinition,\n ArraySchemaType,\n PortableTextBlock,\n} from '@sanity/types'\nimport {useActorRef} from '@xstate/react'\nimport {getPortableTextMemberSchemaTypes} from '../utils/getPortableTextMemberSchemaTypes'\nimport {compileType} from '../utils/schema'\nimport type {Behavior} from './behavior/behavior.types'\nimport {compileSchemaDefinition, type SchemaDefinition} from './define-schema'\nimport {editorMachine} from './editor-machine'\nimport {defaultKeyGenerator} from './key-generator'\n\n/**\n * @alpha\n */\nexport type EditorConfig = {\n behaviors?: Array<Behavior>\n keyGenerator?: () => string\n} & (\n | {\n schemaDefinition: SchemaDefinition\n schema?: undefined\n }\n | {\n schemaDefinition?: undefined\n schema: ArraySchemaType<PortableTextBlock> | ArrayDefinition\n }\n)\n\n/**\n * @alpha\n */\nexport type Editor = ReturnType<typeof useEditor>\n\n/**\n * @alpha\n */\nexport function useEditor(config: EditorConfig) {\n const schema = config.schemaDefinition\n ? compileSchemaDefinition(config.schemaDefinition)\n : getPortableTextMemberSchemaTypes(\n config.schema.hasOwnProperty('jsonType')\n ? config.schema\n : compileType(config.schema),\n )\n\n const editorActor = useActorRef(editorMachine, {\n input: {\n behaviors: config.behaviors,\n keyGenerator: config.keyGenerator ?? defaultKeyGenerator,\n schema,\n },\n })\n\n return editorActor\n}\n"],"names":["defineBehavior","behavior","selectionIsCollapsed","context","selection","anchor","path","join","focus","offset","getFocusBlock","key","isKeySegment","_key","undefined","node","value","find","block","getFocusTextBlock","focusBlock","isPortableTextTextBlock","getFocusBlockObject","getFocusChild","children","span","getFocusSpan","focusChild","isPortableTextSpan","getSelectionStartBlock","backward","getSelectionEndBlock","getPreviousBlock","previousBlock","selectionStartBlock","foundSelectionStartBlock","getNextBlock","nextBlock","selectionEndBlock","foundSelectionEndBlock","isEmptyTextBlock","length","text","breakingBlockObject","on","guard","actions","type","decorators","deletingEmptyTextBlockAfterBlockObject","focusTextBlock","selectionCollapsed","_","deletingEmptyTextBlockBeforeBlockObject","coreBlockObjectBehaviors","decoratorAdd","event","decorator","decoratorRemove","decoratorToggle","coreDecoratorBehaviors","clearListOnBackspace","focusSpan","level","props","paths","unindentListOnBackspace","coreListBehaviors","softReturn","coreBehaviors","coreBehavior","blockObjects","lists","createMarkdownBehaviors","config","automaticBlockquoteOnSpace","caretAtTheEndOfQuote","looksLikeMarkdownQuote","test","blockquoteStyle","mapBlockquoteStyle","schema","style","automaticHeadingOnSpace","markdownHeadingSearch","exec","headingLevel","headingStyle","mapHeadingStyle","clearStyleOnBackspace","atTheBeginningOfBLock","defaultStyle","mapDefaultStyle","automaticListOnSpace","looksLikeUnorderedList","unorderedListStyle","mapUnorderedListStyle","caretAtTheEndOfUnorderedList","listItem","listItemLength","looksLikeOrderedList","orderedListStyle","mapOrderedListStyle","caretAtTheEndOfOrderedList","getPortableTextMemberSchemaTypes","portableTextType","Error","blockType","of","findBlockType","childrenField","fields","field","name","ofType","spanType","memberType","inlineObjectTypes","filter","blockObjectTypes","styles","resolveEnabledStyles","resolveEnabledDecorators","resolveEnabledListItems","portableText","inlineObjects","annotations","styleField","btField","textStyles","options","list","listField","listItems","defineSchema","definition","compileSchemaDefinition","map","blockObject","defineType","title","icon","inlineObject","portableTextSchema","defineField","marks","startCase","annotation","SanitySchema","compile","types","get","pteSchema","rootName","debug","debugWithName","namespace","enabled","createKeyedPath","point","blockPath","keyedBlockPath","_type","keyedChildPath","childPath","slice","child","Array","isArray","createArrayedPath","editor","from","Editor","nodes","at","match","n","Element","isElement","isVoid","childIndex","findIndex","isEqual","concat","toPortableTextRange","range","anchorPath","focusPath","Boolean","Range","isRange","isBackward","toSlateRange","moveRangeByOperation","operation","Point","transform","equals","normalizePoint","newPath","newOffset","blockKey","childKey","blk","push","cld","normalizeSelection","newAnchor","newFocus","EMPTY_MARKDEFS","VOID_CHILD_KEY","keepObjectEquality","object","keyMap","toSlateValue","schemaTypes","rest","voidChildren","textBlock","hasInlines","hasMissingStyle","hasMissingMarkDefs","markDefs","hasMissingChildren","cType","cKey","cRest","__inline","fromSlateValue","textBlockType","_cType","v","k","t","_i","_c","blockValue","isEqualToEmptyEditor","Text","isText","IS_PROCESSING_REMOTE_CHANGES","WeakMap","IS_PROCESSING_LOCAL_CHANGES","IS_DRAGGING","IS_DRAGGING_BLOCK_ELEMENT","IS_DRAGGING_ELEMENT_TARGET","IS_DRAGGING_BLOCK_TARGET_POSITION","KEY_TO_SLATE_ELEMENT","KEY_TO_VALUE_ELEMENT","SLATE_TO_PORTABLE_TEXT_RANGE","DefaultObject","$","t0","JSON","stringify","t1","displayName","DefaultBlockObject","styled","div","selected","DefaultListItem","getLeftPositionForListLevel","listLevel","getContentForListLevelAndStyle","listStyle","getCounterIncrementForListLevel","getCounterResetForListLevel","getCounterContentForListLevel","DefaultListItemInner","Number","bullets","normalizedLevel","DraggableBlock","element","readOnly","blockRef","useSlateStatic","dragGhostRef","useRef","isDragOver","setIsDragOver","useState","t2","t3","t4","isInline","blockElement","setBlockElement","t5","t6","current","ReactEditor","toDOMNode","useEffect","t7","isMyDragOver","preventDefault","dataTransfer","dropEffect","set","elementRect","getBoundingClientRect","top","height","Y","pageY","loc","Math","abs","handleDragOver","t8","Symbol","for","handleDragLeave","t9","event_0","targetBlock","stopPropagation","delete","document","body","removeChild","dragPosition","targetPath","findPath","myPath","isBefore","Path","originalPath","originalPath_0","Transforms","moveNodes","to","onChange","handleDragEnd","t10","event_1","handleDrop","t11","event_2","target","HTMLElement","opacity","handleDrag","t12","event_3","setData","effectAllowed","dragGhost","cloneNode","customGhost","querySelector","setAttribute","position","left","boxSizing","appendChild","rect","x","clientX","y","clientY","width","setDragImage","handleDragStart","t13","isDraggingOverFirstBlock","t14","isDraggingOverLastBlock","dragPosition_0","isDraggingOverTop","isDraggingOverBottom","t15","t16","borderBottom","zIndex","dropIndicator","t17","t18","t19","EMPTY_ANNOTATIONS","inlineBlockStyle","display","attributes","renderBlock","renderChild","renderListItem","renderStyle","spellCheck","useSelected","inlineBlockObjectRef","focused","isCollapsed","useMemo","renderedBlock","className","depth","schemaType","SlateElement","elmPath","debugRenders","ObjectNode","editorElementRef","isListItem","blockStyleType","item","isListBlock","listType","renderProps","Object","defineProperty","enumerable","warn","propsOrDefaultRendered","renderedBlockFromProps","_props","PortableTextEditorContext","createContext","usePortableTextEditor","useContext","DefaultAnnotation","alert","handleClick","color","compileType","rawType","Schema","createOperationToPatches","textBlockName","insertTextPatch","beforeValue","isTextBlock","textChild","isTextSpan","prevBlock","prevChild","prevText","patch","diffMatchPatch","removeTextPatch","beforeBlock","prevTextChild","setNodePatch","setNode","omitBy","newProperties","isUndefined","patches","keys","forEach","keyName","val","indexOf","insertNodePatch","targetKey","insert","setIfMissing","splitNodePatch","splitBlock","oldBlock","targetValue","unset","splitSpan","targetSpans","removeNodePatch","spanToRemove","console","mergeNodePatch","updatedBlock","newBlock","updatedSpan","removedSpan","moveNodePatch","targetChild","childToInsert","createWithEventListeners","editorActor","addMark","mark","send","behaviorEvent","removeMark","deleteBackward","unit","deleteForward","insertBreak","insertSoftBreak","insertText","every","isPortableTextBlock","def","getPreviousSpan","spanPath","previousSpan","Node","reverse","getNextSpan","nextSpan","isAfter","withRemoteChanges","fn","prev","isChangingRemotely","isChangingLocally","IS_UDOING","IS_REDOING","withUndoing","isUndoing","setIsUndoing","withRedoing","isRedoing","setIsRedoing","createWithPortableTextMarkModel","apply","normalizeNode","nodeEntry","nextNode","includes","mergeNodes","voids","setNodes","parent","orphanedAnnotations","markDefKeys","Set","newMarkDefs","markDef","has","add","operations","some","op","properties","previousSelectionIsCollapsed","newSelectionIsCollapsed","mode","newFocusSpan","movedToNextSpan","movedToPreviousSpan","_block","previousSpanAnnotations","nextSpanAnnotations","annotationsEnding","atTheEndOfAnnotation","insertNodes","annotationsStarting","atTheStartOfAnnotation","nextSpanDecorators","collapsedSelection","marksWithoutAnnotations","spanHasAnnotations","spanIsEmpty","atTheBeginningOfSpan","atTheEndOfSpan","spanAnnotations","previousSpanHasAnnotations","previousSpanHasSameAnnotations","previousSpanHasSameAnnotation","previousSpanHasSameMarks","nextSpanSharesSomeAnnotations","getSnapshot","keyGenerator","isExpanded","deletingFromTheEnd","deletingAllText","nextSpanHasSameAnnotation","marksWithoutAnnotationMarks","withoutNormalizing","oldDefs","uniq","addDecoratorActionImplementation","action","split","hanging","splitTextNodes","eMark","lonelyEmptySpan","existingMarks","existingMarksWithoutDecorator","existingMark","removeDecoratorActionImplementation","isDecoratorActive","selectedNodes","toggleDecoratorActionImplementation","createWithEditableAPI","portableTextEditor","setEditable","blur","toggleMark","toggleList","pteToggleListItem","toggleBlockStyle","blockStyle","pteToggleBlockStyle","isMarkActive","err","undo","redo","select","slateSelection","deselect","descendant","insertChild","focusChildPath","isSpanNode","focusNode","move","distance","insertBlock","lastBlock","isEditor","insertNode","removeNodes","hasBlockStyle","pteHasBlockStyle","hasListStyle","pteHasListStyle","findByPath","slatePath","ptBlock","ptChild","findDOMNode","activeAnnotations","spans","isAnnotationActive","annotationType","selectionMarkDefs","reduce","accMarkDefs","markKey","addAnnotation","originalSelection","returnValue","pteExpandToWord","markDefPath","markDefPaths","selectedBlocks","annotationKey","unshift","existingSameTypeAnnotations","pteCreateTextBlock","removeAnnotation","potentialAnnotations","selectedChild","selectedChildPath","annotationToRemove","previousSpansWithSameAnnotation","SlatePath","nextSpansWithSameAnnotation","blocks","marksWithoutAnnotation","getSelection","ptRange","existing","getValue","isCollapsedSelection","isExpandedSelection","getFragment","isSelectionsOverlapping","selectionA","selectionB","rangeA","rangeB","createWithMaxBlocks","maxBlocks","rows","createWithObjectKeys","entry","isHighSurrogate","char","charCode","charCodeAt","isLowSurrogate","debugVerbose","createApplyPatch","changed","insertPatch","unsetPatch","setPatch","error","findBlockAndChildFromPath","parsePatch","newValue","diffMatchPatchApplyPatches","allowExceedingIndices","diff","cleanupEfficiency","makeDiff","debugState","DIFF_INSERT","DIFF_DELETE","DIFF_EQUAL","targetBlockPath","targetChildPath","items","blocksToInsert","targetBlockIndex","normalizedIdx","childrenToInsert","targetChildIndex","childInsertPath","newText","nextRest","prevChildren","prevRest","c","cIndex","newVal","applyAll","previousSelection","_child","i","blockIndex","isKeyedSegment","segment","stateName","findBlockFromPath","index","isMatch","PATCHING","withoutPatching","isPatching","SAVING","REMOTE_PATCHES","UNDO_STEP_LIMIT","isSaving","state","getRemotePatches","createWithUndoRedo","blockSchemaType","previousSnapshot","remotePatches","subscriptions","sub","snapshot","reset","origin","history","undos","redos","splice","time","Date","unsubscribe","step","lastOp","overwrite","shouldOverwrite","save","merge","shouldMerge","newStep","createSelectOperation","timestamp","shift","shouldClear","otherPatches","transformedOperations","flatten","transformOperation","reversedOperations","Operation","inverse","withoutSaving","normalize","pop","transformedOperation","insertBlockIndex","adjustBlockPath","unsetBlockIndex","operationTargetBlock","findOperationTargetBlock","diffPatch","adjustOffsetBy","changedOffset","utf8Start1","diffs","diffType","dType","currentFocus","currentAnchor","createWithPatches","patchFunctions","previousChildren","applyPatch","bufferedPatches","handleBufferedRemotePatches","handlePatches","p","editorWasEmpty","editorIsEmpty","previousValue","createWithPlaceholderBlock","nextPath","next","createWithPortableTextBlockStyle","SlateText","MAX_LIST_LEVEL","createWithPortableTextLists","listItemStyle","pteUnsetListItem","pteSetListItem","newNode","pteEndList","pteIncrementBlockLevels","min","max","createWithPortableTextSelections","prevSelection","emitPortableTextSelection","hasChanges","createWithSchemaTypes","isPortableTextListBlock","obj","createWithUtils","textNode","focusOffset","charsBefore","charsAfter","isEmpty","str","whiteSpaceBeforeIndex","newStartOffset","whiteSpaceAfterIndex","newEndOffset","isNaN","setSelection","DEFAULT_HOTKEYS","custom","createWithHotkeys","hotkeysFromOptions","reservedHotkeys","activeHotkeys","pteWithHotKeys","cat","hotkey","isHotkey","nativeEvent","possibleMark","possibleCommand","command","isEnter","isTab","isShiftEnter","isShiftTab","isArrowDown","isArrowUp","isFirstBlock","hasAnnotationFocus","m","start","edges","atStartOfNode","isStart","focusBlockPath","validateValue","resolution","valid","validChildTypes","validBlockTypes","description","i18n","isPlainObject","String","values","currentBlockTypeName","expectedTypeName","typeName","newSpan","autoResolve","allUsedMarks","unusedMarkDefs","markDefKey","toString","orphanedMarks","dec","spanChildren","orphaned","cMrk","newChild","childType","createWithInsertData","blockTypeName","spanTypeName","whitespaceOnPasteMode","unstable_whitespaceOnPasteMode","toPlainText","setFragmentData","data","originEvent","end","startVoid","void","endVoid","domRange","toDOMRange","contents","cloneContents","voidNode","r","cloneRange","domNode","setEndAfter","querySelectorAll","zw","isNewline","getAttribute","textContent","elm","removeAttribute","hasAttribute","ownerDocument","createElement","asHTML","innerHTML","fragment","asJSON","asPlainText","clearData","insertPortableTextData","pText","getData","parsed","parse","slateValue","_regenerateKeys","validation","errorDescription","insertTextOrHTMLData","html","insertedType","htmlToBlocks","normalizeBlock","textToHtml","escapeHtml","line","replace","_insertFragment","insertData","insertFragmentData","insertFragment","entityMap","s","editorTypes","NewNodeNoDefs","allowedAnnotations","oldKey","newKey","nodeWithNewKeys","splitNodes","originalFnMap","withPlugins","e","destroy","operationToPatches","withObjectKeys","withSchemaTypes","withEditableAPI","withPatches","withMaxBlocks","withPortableTextLists","withUndoRedo","withPortableTextMarkModel","withPortableTextBlockStyle","withPlaceholderBlock","withUtils","withPortableTextSelections","withEventListeners","originalFunctions","subscribe","noop","unsubscribes","subscribeFn","unsubscribeFn","SlateContainer","_sub","withReact","createEditor","slateEditor","initialValue","PortableTextEditorReadOnlyContext","usePortableTextEditorReadOnlyStatus","CURRENT_VALUE","useSyncValue","useSlate","updateValueFunctionRef","updateFromCurrentValue","useCallback","currentValue","updateValueDebounced","debounce","trailing","leading","updateFunction","isProcessingLocalChanges","isProcessingRemoteChanges","isChanged","isValid","hadSelection","childrenLength","slateValueFromProps","currentBlock","currentBlockIndex","validationValue","_updateBlock","_replaceBlock","currentSelection","selectionFocusOnBlock","oldBlockChildrenLength","currentBlockChild","currentBlockChildIndex","oldBlockChild","isChildChanged","isTextChanged","FLUSH_PATCHES_THROTTLED_MS","process","env","NODE_ENV","Synchronizer","pendingPatches","syncValue","onFlushPendingPatches","change","handleChange","useEffectEvent","onFlushPendingPatchesThrottled","throttle","isNormalizing","bb18","isLoading","handleOnline","subscription","isInitialValueFromProps","EditorActorContext","insertBreakActionImplementation","focusDecorators","focusAnnotations","atTheStartOfBlock","nextBlockPath","lastFocusBlockChild","atTheEndOfBlock","nextNodePath","newMarkDefKeys","Map","prevNodeSpans","prevNodeSpan","newMarks","behaviorActionImplementations","set block","unset block","unsetNodes","delete backward","delete forward","location","insert text","insert text block","effect","newSelection","reselect","performAction","performDefaultAction","networkLogic","fromCallback","sendBack","onlineHandler","offlineHandler","addEventListener","window","removeEventListener","editorMachine","setup","events","emitted","input","assign","behaviors","assertEvent","emit","pendingEvents","enqueueActions","enqueue","defaultAction","eventBehaviors","raise","actionIntends","behaviorContext","behaviorOverwritten","eventBehavior","shouldRun","actionIntendSets","actionSet","actionIntend","actors","createMachine","id","invoke","src","initial","states","pristine","idle","normalizing","mutation","dirty","PortableTextEditorSelectionContext","usePortableTextEditorSelection","PortableTextEditorSelectionProvider","startTransition","defaultKeyGenerator","randomKey","PortableTextEditor","Component","change$","Subject","constructor","incomingPatches$","hasOwnProperty","createActor","componentDidUpdate","prevProps","editorRef","editable","render","parseInt","legacyPatches","patches$","isObjectPath","_editor","isChildObjectEditPath","RoutePatchesObservableToEditorActor","payload","EMPTY_MARKS","Leaf","leaf","renderDecorator","renderAnnotation","spanRef","blockSelected","setFocused","setSelected","decoratorValues","annotationMarks","shouldTrackSelectionAndFocus","sel","setSelectedFromRange","winSelection","rangeCount","getRangeAt","intersectsNode","onBlur","onFocus","onSelection","content","returnedChildren","withSyncRangeDecorations","syncRangeDecorations","originalApply","PLACEHOLDER_STYLE","userSelect","pointerEvents","right","PortableTextEditable","forwardRef","forwardedRef","hotkeys","onBeforeInput","onPaste","onCopy","onClick","rangeDecorations","renderPlaceholder","propsSelection","scrollSelectionIntoView","restProps","ref","editableElement","setEditableElement","hasInvalidValue","setHasInvalidValue","rangeDecorationState","setRangeDecorationsState","rangeDecorationsRef","withInsertData","withHotKeys","renderElement","eProps","renderLeaf","lProps","rendered","placeholder","decoration","rangeDecoration","component","restoreSelectionFromProps","normalizedSelection","slateRange","o","newSlateRanges","rangeDecorationItem","SlateRange","onMoved","newRange","newRangeSelection","onReady","onInvalidValue","onValueChanged","syncedRangeDecorations","setSyncedRangeDecorations","teardown","handleCopy","handlePaste","clipboardData","onPasteResult","Promise","resolve","then","result","catch","finally","handleOnFocus","isDefaultPrevented","currentTarget","last","lastPath","handleOnBlur","isPropagationStopped","handleOnBeforeInput","validateSelection","root","findDocumentOrShadowRoot","activeElement","domSelection","getWindow","existingDOMRange","newDOMRange","startOffset","endOffset","removeAllRanges","addRange","mutationObserver","MutationObserver","observe","attributeOldValue","characterData","childList","subtree","disconnect","handleKeyDown","onKeyDown","scrollSelectionIntoViewToSlate","decorate","intersection","SlateEditable","useEditor","schemaDefinition","useActorRef"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8JO,SAASA,eAGdC,UAAkE;AAC3DA,SAAAA;AACT;ACnJO,SAASC,qBAAqBC,SAA0B;AAC7D,SACEA,QAAQC,WAAWC,OAAOC,KAAKC,WAC7BJ,QAAQC,WAAWI,MAAMF,KAAKC,UAChCJ,QAAQC,WAAWC,OAAOI,WAAWN,QAAQC,WAAWI,MAAMC;AAElE;AAMO,SAASC,cACdP,SAC6D;AAC7D,QAAMQ,MAAMR,QAAQC,aAChBQ,aAAaT,QAAQC,UAAUI,MAAMF,KAAK,CAAC,CAAC,IAC1CH,QAAQC,UAAUI,MAAMF,KAAK,CAAC,EAAEO,OAElCC,QAEEC,OAAOJ,MACTR,QAAQa,MAAMC,KAAMC,CAAUA,UAAAA,MAAML,SAASF,GAAG,IAChDG;AAEJ,SAAOC,QAAQJ,MAAM;AAAA,IAACI;AAAAA,IAAMT,MAAM,CAAC;AAAA,MAACO,MAAMF;AAAAA,IAAI,CAAA;AAAA,EAAKG,IAAAA;AACrD;AAEO,SAASK,kBACdhB,SACiE;AAC3DiB,QAAAA,aAAaV,cAAcP,OAAO;AAExC,SAAOiB,cAAcC,wBAAwBD,WAAWL,IAAI,IACxD;AAA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wBX,CAAC;AAEDxF,qBAAqB14B,cAAc;ACzsB5B,SAAAs+B,UAAA5pC,QAAA;AAAAiL,QAAAA,IAAAhB,EAAA,CAAA;AAAAiB,MAAAA;AAAAD,IAAAjL,CAAAA,MAAAA,OAAA6pC,oBAAA5+B,EAAA,CAAA,MAAAjL,OAAAO,UACU2K,KAAAlL,OAAM6pC,mBACjB/lC,wBAAwB9D,OAAM6pC,gBAAiB,IAC/C/nC,iCACE9B,OAAMO,OAAA4gC,eAAuB,UAAU,IACnCnhC,OAAMO,SACNwV,YAAY/V,OAAMO,MAAO,CAC/B,GAAC0K,EAAA,CAAA,IAAAjL,OAAA6pC,kBAAA5+B,EAAA,CAAA,IAAAjL,OAAAO,QAAA0K,OAAAC,MAAAA,KAAAD,EAAA,CAAA;AANL,QAAA1K,SAAe2K,IAWGG,KAAArL,OAAMwe,gBAAAmiB;AAAoC1zB,MAAAA;AAAA,SAAAhC,EAAA,CAAA,MAAAjL,OAAA0+B,aAAAzzB,EAAA,CAAA,MAAAI,MAAAJ,EAAA,CAAA,MAAA1K,UAHb0M,KAAA;AAAA,IAAAuxB,OAAA;AAAA,MAAAE,WAEhC1+B,OAAM0+B;AAAAA,MAAAlgB,cACHnT;AAAAA,MAA0C9K;AAAAA,IAAAA;AAAAA,EAAA,GAG3D0K,EAAA,CAAA,IAAAjL,OAAA0+B,WAAAzzB,OAAAI,IAAAJ,OAAA1K,QAAA0K,OAAAgC,MAAAA,KAAAhC,EAAA,CAAA,GANmB6+B,YAAA1L,eAA2BnxB,EAM9C;AAEiB;","x_google_ignoreList":[24,32]}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/editor/behavior/behavior.types.ts","../src/editor/behavior/behavior.utils.ts","../src/editor/behavior/behavior.core.block-objects.ts","../src/editor/behavior/behavior.core.decorators.ts","../src/editor/behavior/behavior.core.lists.ts","../src/editor/behavior/behavior.core.ts","../src/editor/behavior/behavior.markdown.ts","../src/utils/getPortableTextMemberSchemaTypes.ts","../src/editor/define-schema.ts","../src/utils/debug.ts","../src/utils/paths.ts","../src/utils/ranges.ts","../src/utils/selection.ts","../src/utils/values.ts","../src/utils/weakMaps.ts","../src/editor/nodes/DefaultObject.tsx","../src/editor/nodes/index.ts","../src/editor/components/DraggableBlock.tsx","../src/editor/components/Element.tsx","../src/editor/hooks/usePortableTextEditor.ts","../src/editor/nodes/DefaultAnnotation.tsx","../src/utils/schema.ts","../src/utils/validateValue.ts","../src/utils/withChanges.ts","../src/utils/withoutPatching.ts","../../../node_modules/.pnpm/@sanity+diff-match-patch@3.1.1/node_modules/@sanity/diff-match-patch/dist/index.js","../src/utils/withUndoRedo.ts","../src/editor/plugins/createWithUndoRedo.ts","../src/editor/hooks/useSyncValue.ts","../src/editor/components/Synchronizer.tsx","../src/utils/operationToPatches.ts","../src/editor/plugins/create-with-event-listeners.ts","../src/editor/plugins/createWithMaxBlocks.ts","../src/editor/plugins/createWithObjectKeys.ts","../src/utils/applyPatch.ts","../src/editor/plugins/createWithPatches.ts","../src/editor/plugins/createWithPlaceholderBlock.ts","../src/editor/plugins/createWithPortableTextBlockStyle.ts","../src/editor/plugins/createWithPortableTextLists.ts","../../../node_modules/.pnpm/@portabletext+toolkit@2.0.16/node_modules/@portabletext/toolkit/dist/index.js","../src/utils/sibling-utils.ts","../src/editor/plugins/createWithPortableTextMarkModel.ts","../src/editor/plugins/createWithPortableTextSelections.ts","../src/editor/plugins/createWithSchemaTypes.ts","../src/editor/plugins/createWithUtils.ts","../src/editor/plugins/with-plugins.ts","../src/editor/create-slate-editor.tsx","../src/editor/editor-actor-context.ts","../src/editor/plugins/createWithEditableAPI.ts","../src/editor/behavior/behavior.action.insert-break.ts","../src/editor/behavior/behavior.actions.ts","../src/editor/editor-machine.ts","../src/editor/hooks/usePortableTextEditorSelection.tsx","../src/editor/key-generator.ts","../src/editor/PortableTextEditor.tsx","../src/editor/components/Leaf.tsx","../src/editor/plugins/createWithHotKeys.ts","../src/editor/plugins/createWithInsertData.ts","../src/editor/withSyncRangeDecorations.ts","../src/editor/Editable.tsx","../src/editor/use-editor.ts"],"sourcesContent":["import type {KeyedSegment, PortableTextBlock} from '@sanity/types'\nimport type {TextUnit} from 'slate'\nimport type {TextInsertTextOptions} from 'slate/dist/interfaces/transforms/text'\nimport type {\n EditorSelection,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\n\n/**\n * @alpha\n */\nexport type BehaviorContext = {\n schema: PortableTextMemberSchemaTypes\n value: Array<PortableTextBlock>\n selection: NonNullable<EditorSelection>\n}\n\n/**\n * @alpha\n */\nexport type BehaviorEvent =\n | {\n type: 'annotation.add'\n annotation: {\n name: string\n value: {[prop: string]: unknown}\n }\n }\n | {\n type: 'annotation.remove'\n annotation: {\n name: string\n }\n }\n | {\n type: 'annotation.toggle'\n annotation: {\n name: string\n value: {[prop: string]: unknown}\n }\n }\n | {\n type: 'decorator.add'\n decorator: string\n }\n | {\n type: 'decorator.remove'\n decorator: string\n }\n | {\n type: 'decorator.toggle'\n decorator: string\n }\n | {\n type: 'delete backward'\n unit: TextUnit\n }\n | {\n type: 'delete forward'\n unit: TextUnit\n }\n | {\n type: 'focus'\n }\n | {\n type: 'insert soft break'\n }\n | {\n type: 'insert break'\n }\n | {\n type: 'insert text'\n text: string\n options?: TextInsertTextOptions\n }\n\n/**\n * @alpha\n */\nexport type BehaviorGuard<\n TBehaviorEvent extends BehaviorEvent,\n TGuardResponse,\n> = ({\n context,\n event,\n}: {\n event: TBehaviorEvent\n context: BehaviorContext\n}) => TGuardResponse | false\n\n/**\n * @alpha\n */\nexport type BehaviorActionIntend =\n | BehaviorEvent\n | {\n type: 'insert text block'\n decorators: Array<string>\n }\n | {\n type: 'set block'\n paths: Array<[KeyedSegment]>\n style?: string\n listItem?: string\n level?: number\n }\n | {\n type: 'unset block'\n paths: Array<[KeyedSegment]>\n props: Array<'style' | 'listItem' | 'level'>\n }\n | {\n type: 'delete'\n selection: NonNullable<EditorSelection>\n }\n | {\n type: 'effect'\n effect: () => void\n }\n | {\n type: 'select'\n selection: EditorSelection\n }\n | {\n type: 'reselect'\n }\n\n/**\n * @alpha\n */\nexport type BehaviorAction = BehaviorActionIntend & {\n editor: PortableTextSlateEditor\n}\n\n/**\n * @alpha\n */\nexport type Behavior<\n TBehaviorEventType extends BehaviorEvent['type'] = BehaviorEvent['type'],\n TGuardResponse = true,\n> = {\n /**\n * The internal editor event that triggers this behavior.\n */\n on: TBehaviorEventType\n /**\n * Predicate function that determines if the behavior should be executed.\n * Returning a non-nullable value from the guard will pass the value to the\n * actions and execute them.\n */\n guard?: BehaviorGuard<\n PickFromUnion<BehaviorEvent, 'type', TBehaviorEventType>,\n TGuardResponse\n >\n /**\n * Array of behavior action sets.\n */\n actions: Array<BehaviorActionIntendSet<TBehaviorEventType, TGuardResponse>>\n}\n\n/**\n * @alpha\n */\nexport type BehaviorActionIntendSet<\n TBehaviorEventType extends BehaviorEvent['type'] = BehaviorEvent['type'],\n TGuardResponse = true,\n> = (\n {\n context,\n event,\n }: {\n context: BehaviorContext\n event: PickFromUnion<BehaviorEvent, 'type', TBehaviorEventType>\n },\n guardResponse: TGuardResponse,\n) => Array<BehaviorActionIntend>\n\n/**\n * @alpha\n */\nexport function defineBehavior<\n TBehaviorEventType extends BehaviorEvent['type'],\n TGuardResponse = true,\n>(behavior: Behavior<TBehaviorEventType, TGuardResponse>): Behavior {\n return behavior as unknown as Behavior\n}\n\n/**\n * @alpha\n */\nexport type PickFromUnion<\n TUnion,\n TTagKey extends keyof TUnion,\n TPickedTags extends TUnion[TTagKey],\n> = TUnion extends Record<TTagKey, TPickedTags> ? TUnion : never\n","import {\n isKeySegment,\n isPortableTextSpan,\n isPortableTextTextBlock,\n type KeyedSegment,\n type PortableTextBlock,\n type PortableTextObject,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport type {BehaviorContext} from './behavior.types'\n\n/**\n * Selection utilities\n */\n\nexport function selectionIsCollapsed(context: BehaviorContext) {\n return (\n context.selection?.anchor.path.join() ===\n context.selection?.focus.path.join() &&\n context.selection?.anchor.offset === context.selection?.focus.offset\n )\n}\n\n/**\n * Value utilities\n */\n\nexport function getFocusBlock(\n context: BehaviorContext,\n): {node: PortableTextBlock; path: [KeyedSegment]} | undefined {\n const key = context.selection\n ? isKeySegment(context.selection.focus.path[0])\n ? context.selection.focus.path[0]._key\n : undefined\n : undefined\n\n const node = key\n ? context.value.find((block) => block._key === key)\n : undefined\n\n return node && key ? {node, path: [{_key: key}]} : undefined\n}\n\nexport function getFocusTextBlock(\n context: BehaviorContext,\n): {node: PortableTextTextBlock; path: [KeyedSegment]} | undefined {\n const focusBlock = getFocusBlock(context)\n\n return focusBlock && isPortableTextTextBlock(focusBlock.node)\n ? {node: focusBlock.node, path: focusBlock.path}\n : undefined\n}\n\nexport function getFocusBlockObject(\n context: BehaviorContext,\n): {node: PortableTextObject; path: [KeyedSegment]} | undefined {\n const focusBlock = getFocusBlock(context)\n\n return focusBlock && !isPortableTextTextBlock(focusBlock.node)\n ? {node: focusBlock.node, path: focusBlock.path}\n : undefined\n}\n\nexport function getFocusChild(context: BehaviorContext):\n | {\n node: PortableTextObject | PortableTextSpan\n path: [KeyedSegment, 'children', KeyedSegment]\n }\n | undefined {\n const focusBlock = getFocusTextBlock(context)\n\n if (!focusBlock) {\n return undefined\n }\n\n const key = context.selection\n ? isKeySegment(context.selection.focus.path[2])\n ? context.selection.focus.path[2]._key\n : undefined\n : undefined\n\n const node = key\n ? focusBlock.node.children.find((span) => span._key === key)\n : undefined\n\n return node && key\n ? {node, path: [...focusBlock.path, 'children', {_key: key}]}\n : undefined\n}\n\nexport function getFocusSpan(\n context: BehaviorContext,\n):\n | {node: PortableTextSpan; path: [KeyedSegment, 'children', KeyedSegment]}\n | undefined {\n const focusChild = getFocusChild(context)\n\n return focusChild && isPortableTextSpan(focusChild.node)\n ? {node: focusChild.node, path: focusChild.path}\n : undefined\n}\n\nexport function getSelectionStartBlock(context: BehaviorContext):\n | {\n node: PortableTextBlock\n path: [KeyedSegment]\n }\n | undefined {\n const key = context.selection.backward\n ? isKeySegment(context.selection.focus.path[0])\n ? context.selection.focus.path[0]._key\n : undefined\n : isKeySegment(context.selection.anchor.path[0])\n ? context.selection.anchor.path[0]._key\n : undefined\n\n const node = key\n ? context.value.find((block) => block._key === key)\n : undefined\n\n return node && key ? {node, path: [{_key: key}]} : undefined\n}\n\nexport function getSelectionEndBlock(context: BehaviorContext):\n | {\n node: PortableTextBlock\n path: [KeyedSegment]\n }\n | undefined {\n const key = context.selection.backward\n ? isKeySegment(context.selection.anchor.path[0])\n ? context.selection.anchor.path[0]._key\n : undefined\n : isKeySegment(context.selection.focus.path[0])\n ? context.selection.focus.path[0]._key\n : undefined\n\n const node = key\n ? context.value.find((block) => block._key === key)\n : undefined\n\n return node && key ? {node, path: [{_key: key}]} : undefined\n}\n\nexport function getPreviousBlock(\n context: BehaviorContext,\n): {node: PortableTextBlock; path: [KeyedSegment]} | undefined {\n let previousBlock: {node: PortableTextBlock; path: [KeyedSegment]} | undefined\n const selectionStartBlock = getSelectionStartBlock(context)\n\n if (!selectionStartBlock) {\n return undefined\n }\n\n let foundSelectionStartBlock = false\n\n for (const block of context.value) {\n if (block._key === selectionStartBlock.node._key) {\n foundSelectionStartBlock = true\n break\n }\n\n previousBlock = {node: block, path: [{_key: block._key}]}\n }\n\n if (foundSelectionStartBlock && previousBlock) {\n return previousBlock\n }\n\n return undefined\n}\n\nexport function getNextBlock(\n context: BehaviorContext,\n): {node: PortableTextBlock; path: [KeyedSegment]} | undefined {\n let nextBlock: {node: PortableTextBlock; path: [KeyedSegment]} | undefined\n const selectionEndBlock = getSelectionEndBlock(context)\n\n if (!selectionEndBlock) {\n return undefined\n }\n\n let foundSelectionEndBlock = false\n\n for (const block of context.value) {\n if (block._key === selectionEndBlock.node._key) {\n foundSelectionEndBlock = true\n continue\n }\n\n if (foundSelectionEndBlock) {\n nextBlock = {node: block, path: [{_key: block._key}]}\n break\n }\n }\n\n if (foundSelectionEndBlock && nextBlock) {\n return nextBlock\n }\n\n return undefined\n}\n\nexport function isEmptyTextBlock(block: PortableTextTextBlock) {\n return block.children.length === 1 && block.children[0].text === ''\n}\n","import {isPortableTextTextBlock} from '@sanity/types'\nimport {defineBehavior} from './behavior.types'\nimport {\n getFocusBlockObject,\n getFocusTextBlock,\n getNextBlock,\n getPreviousBlock,\n isEmptyTextBlock,\n selectionIsCollapsed,\n} from './behavior.utils'\n\nconst breakingBlockObject = defineBehavior({\n on: 'insert break',\n guard: ({context}) => {\n const focusBlockObject = getFocusBlockObject(context)\n\n return !!focusBlockObject\n },\n actions: [() => [{type: 'insert text block', decorators: []}]],\n})\n\nconst deletingEmptyTextBlockAfterBlockObject = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const focusTextBlock = getFocusTextBlock(context)\n const selectionCollapsed = selectionIsCollapsed(context)\n const previousBlock = getPreviousBlock(context)\n\n if (!focusTextBlock || !selectionCollapsed || !previousBlock) {\n return false\n }\n\n if (\n isEmptyTextBlock(focusTextBlock.node) &&\n !isPortableTextTextBlock(previousBlock.node)\n ) {\n return {focusTextBlock, previousBlock}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock, previousBlock}) => [\n {\n type: 'delete',\n selection: {\n anchor: {path: focusTextBlock.path, offset: 0},\n focus: {path: focusTextBlock.path, offset: 0},\n },\n },\n {\n type: 'select',\n selection: {\n anchor: {path: previousBlock.path, offset: 0},\n focus: {path: previousBlock.path, offset: 0},\n },\n },\n ],\n ],\n})\n\nconst deletingEmptyTextBlockBeforeBlockObject = defineBehavior({\n on: 'delete forward',\n guard: ({context}) => {\n const focusTextBlock = getFocusTextBlock(context)\n const selectionCollapsed = selectionIsCollapsed(context)\n const nextBlock = getNextBlock(context)\n\n if (!focusTextBlock || !selectionCollapsed || !nextBlock) {\n return false\n }\n\n if (\n isEmptyTextBlock(focusTextBlock.node) &&\n !isPortableTextTextBlock(nextBlock.node)\n ) {\n return {focusTextBlock, nextBlock}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock, nextBlock}) => [\n {\n type: 'delete',\n selection: {\n anchor: {path: focusTextBlock.path, offset: 0},\n focus: {path: focusTextBlock.path, offset: 0},\n },\n },\n {\n type: 'select',\n selection: {\n anchor: {path: nextBlock.path, offset: 0},\n focus: {path: nextBlock.path, offset: 0},\n },\n },\n ],\n ],\n})\n\nexport const coreBlockObjectBehaviors = {\n breakingBlockObject,\n deletingEmptyTextBlockAfterBlockObject,\n deletingEmptyTextBlockBeforeBlockObject,\n}\n","import {defineBehavior} from './behavior.types'\n\nconst decoratorAdd = defineBehavior({\n on: 'decorator.add',\n actions: [\n ({event}) => [\n {\n type: 'decorator.add',\n decorator: event.decorator,\n },\n {\n type: 'reselect',\n },\n ],\n ],\n})\n\nconst decoratorRemove = defineBehavior({\n on: 'decorator.remove',\n actions: [\n ({event}) => [\n {\n type: 'decorator.remove',\n decorator: event.decorator,\n },\n {\n type: 'reselect',\n },\n ],\n ],\n})\n\nconst decoratorToggle = defineBehavior({\n on: 'decorator.toggle',\n actions: [\n ({event}) => [\n {\n type: 'decorator.toggle',\n decorator: event.decorator,\n },\n {\n type: 'reselect',\n },\n ],\n ],\n})\n\nexport const coreDecoratorBehaviors = {\n decoratorAdd,\n decoratorRemove,\n decoratorToggle,\n}\n","import {defineBehavior} from './behavior.types'\nimport {\n getFocusSpan,\n getFocusTextBlock,\n selectionIsCollapsed,\n} from './behavior.utils'\n\nconst clearListOnBackspace = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const atTheBeginningOfBLock =\n focusTextBlock.node.children[0]._key === focusSpan.node._key &&\n context.selection.focus.offset === 0\n\n if (atTheBeginningOfBLock && focusTextBlock.node.level === 1) {\n return {focusTextBlock}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock}) => [\n {\n type: 'unset block',\n props: ['listItem', 'level'],\n paths: [focusTextBlock.path],\n },\n ],\n ],\n})\n\nconst unindentListOnBackspace = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const atTheBeginningOfBLock =\n focusTextBlock.node.children[0]._key === focusSpan.node._key &&\n context.selection.focus.offset === 0\n\n if (\n atTheBeginningOfBLock &&\n focusTextBlock.node.level !== undefined &&\n focusTextBlock.node.level > 1\n ) {\n return {focusTextBlock, level: focusTextBlock.node.level - 1}\n }\n\n return false\n },\n actions: [\n (_, {focusTextBlock, level}) => [\n {\n type: 'set block',\n level,\n paths: [focusTextBlock.path],\n },\n ],\n ],\n})\n\nexport const coreListBehaviors = {clearListOnBackspace, unindentListOnBackspace}\n","import {coreBlockObjectBehaviors} from './behavior.core.block-objects'\nimport {coreDecoratorBehaviors} from './behavior.core.decorators'\nimport {coreListBehaviors} from './behavior.core.lists'\nimport {defineBehavior} from './behavior.types'\n\nconst softReturn = defineBehavior({\n on: 'insert soft break',\n actions: [() => [{type: 'insert text', text: '\\n'}]],\n})\n\n/**\n * @alpha\n */\nexport const coreBehaviors = [\n softReturn,\n coreDecoratorBehaviors.decoratorAdd,\n coreDecoratorBehaviors.decoratorRemove,\n coreDecoratorBehaviors.decoratorToggle,\n coreBlockObjectBehaviors.breakingBlockObject,\n coreBlockObjectBehaviors.deletingEmptyTextBlockAfterBlockObject,\n coreBlockObjectBehaviors.deletingEmptyTextBlockBeforeBlockObject,\n coreListBehaviors.clearListOnBackspace,\n coreListBehaviors.unindentListOnBackspace,\n]\n\n/**\n * @alpha\n */\nexport const coreBehavior = {\n softReturn,\n decorators: coreDecoratorBehaviors,\n blockObjects: coreBlockObjectBehaviors,\n lists: coreListBehaviors,\n}\n","import type {PortableTextMemberSchemaTypes} from '../../types/editor'\nimport {defineBehavior} from './behavior.types'\nimport {\n getFocusSpan,\n getFocusTextBlock,\n selectionIsCollapsed,\n} from './behavior.utils'\n\n/**\n * @alpha\n */\nexport type MarkdownBehaviorsConfig = {\n mapDefaultStyle: (schema: PortableTextMemberSchemaTypes) => string | undefined\n mapHeadingStyle: (\n schema: PortableTextMemberSchemaTypes,\n level: number,\n ) => string | undefined\n mapBlockquoteStyle: (\n schema: PortableTextMemberSchemaTypes,\n ) => string | undefined\n mapUnorderedListStyle: (\n schema: PortableTextMemberSchemaTypes,\n ) => string | undefined\n mapOrderedListStyle: (\n schema: PortableTextMemberSchemaTypes,\n ) => string | undefined\n}\n\n/**\n * @alpha\n */\nexport function createMarkdownBehaviors(config: MarkdownBehaviorsConfig) {\n const automaticBlockquoteOnSpace = defineBehavior({\n on: 'insert text',\n guard: ({context, event}) => {\n const isSpace = event.text === ' '\n\n if (!isSpace) {\n return false\n }\n\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const caretAtTheEndOfQuote = context.selection.focus.offset === 1\n const looksLikeMarkdownQuote = /^>/.test(focusSpan.node.text)\n const blockquoteStyle = config.mapBlockquoteStyle(context.schema)\n\n if (\n caretAtTheEndOfQuote &&\n looksLikeMarkdownQuote &&\n blockquoteStyle !== undefined\n ) {\n return {focusTextBlock, focusSpan, style: blockquoteStyle}\n }\n\n return false\n },\n actions: [\n () => [\n {\n type: 'insert text',\n text: ' ',\n },\n ],\n (_, {focusTextBlock, focusSpan, style}) => [\n {\n type: 'unset block',\n props: ['listItem', 'level'],\n paths: [focusTextBlock.path],\n },\n {\n type: 'set block',\n style,\n paths: [focusTextBlock.path],\n },\n {\n type: 'delete',\n selection: {\n anchor: {\n path: focusSpan.path,\n offset: 0,\n },\n focus: {\n path: focusSpan.path,\n offset: 2,\n },\n },\n },\n ],\n ],\n })\n const automaticHeadingOnSpace = defineBehavior({\n on: 'insert text',\n guard: ({context, event}) => {\n const isSpace = event.text === ' '\n\n if (!isSpace) {\n return false\n }\n\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const markdownHeadingSearch = /^#+/.exec(focusSpan.node.text)\n const headingLevel = markdownHeadingSearch\n ? markdownHeadingSearch[0].length\n : undefined\n const caretAtTheEndOfHeading =\n context.selection.focus.offset === headingLevel\n\n if (!caretAtTheEndOfHeading) {\n return false\n }\n\n const headingStyle =\n headingLevel !== undefined\n ? config.mapHeadingStyle(context.schema, headingLevel)\n : undefined\n\n if (headingLevel !== undefined && headingStyle !== undefined) {\n return {\n focusTextBlock,\n focusSpan,\n style: headingStyle,\n level: headingLevel,\n }\n }\n\n return false\n },\n actions: [\n () => [\n {\n type: 'insert text',\n text: ' ',\n },\n ],\n (_, {focusTextBlock, focusSpan, style, level}) => [\n {\n type: 'unset block',\n props: ['listItem', 'level'],\n paths: [focusTextBlock.path],\n },\n {\n type: 'set block',\n style,\n paths: [focusTextBlock.path],\n },\n {\n type: 'delete',\n selection: {\n anchor: {\n path: focusSpan.path,\n offset: 0,\n },\n focus: {\n path: focusSpan.path,\n offset: level + 1,\n },\n },\n },\n ],\n ],\n })\n const clearStyleOnBackspace = defineBehavior({\n on: 'delete backward',\n guard: ({context}) => {\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const atTheBeginningOfBLock =\n focusTextBlock.node.children[0]._key === focusSpan.node._key &&\n context.selection.focus.offset === 0\n\n const defaultStyle = config.mapDefaultStyle(context.schema)\n\n if (\n atTheBeginningOfBLock &&\n defaultStyle &&\n focusTextBlock.node.style !== defaultStyle\n ) {\n return {defaultStyle, focusTextBlock}\n }\n\n return false\n },\n actions: [\n (_, {defaultStyle, focusTextBlock}) => [\n {\n type: 'set block',\n style: defaultStyle,\n paths: [focusTextBlock.path],\n },\n ],\n ],\n })\n const automaticListOnSpace = defineBehavior({\n on: 'insert text',\n guard: ({context, event}) => {\n const isSpace = event.text === ' '\n\n if (!isSpace) {\n return false\n }\n\n const selectionCollapsed = selectionIsCollapsed(context)\n const focusTextBlock = getFocusTextBlock(context)\n const focusSpan = getFocusSpan(context)\n\n if (!selectionCollapsed || !focusTextBlock || !focusSpan) {\n return false\n }\n\n const defaultStyle = config.mapDefaultStyle(context.schema)\n const looksLikeUnorderedList = /^(-|\\*)/.test(focusSpan.node.text)\n const unorderedListStyle = config.mapUnorderedListStyle(context.schema)\n const caretAtTheEndOfUnorderedList = context.selection.focus.offset === 1\n\n if (\n defaultStyle &&\n caretAtTheEndOfUnorderedList &&\n looksLikeUnorderedList &&\n unorderedListStyle !== undefined\n ) {\n return {\n focusTextBlock,\n focusSpan,\n listItem: unorderedListStyle,\n listItemLength: 1,\n style: defaultStyle,\n }\n }\n\n const looksLikeOrderedList = /^1./.test(focusSpan.node.text)\n const orderedListStyle = config.mapOrderedListStyle(context.schema)\n const caretAtTheEndOfOrderedList = context.selection.focus.offset === 2\n\n if (\n defaultStyle &&\n caretAtTheEndOfOrderedList &&\n looksLikeOrderedList &&\n orderedListStyle !== undefined\n ) {\n return {\n focusTextBlock,\n focusSpan,\n listItem: orderedListStyle,\n listItemLength: 2,\n style: defaultStyle,\n }\n }\n\n return false\n },\n actions: [\n () => [\n {\n type: 'insert text',\n text: ' ',\n },\n ],\n (_, {focusTextBlock, focusSpan, style, listItem, listItemLength}) => [\n {\n type: 'set block',\n listItem,\n level: 1,\n style,\n paths: [focusTextBlock.path],\n },\n {\n type: 'delete',\n selection: {\n anchor: {\n path: focusSpan.path,\n offset: 0,\n },\n focus: {\n path: focusSpan.path,\n offset: listItemLength + 1,\n },\n },\n },\n ],\n ],\n })\n\n const markdownBehaviors = [\n automaticBlockquoteOnSpace,\n automaticHeadingOnSpace,\n clearStyleOnBackspace,\n automaticListOnSpace,\n ]\n\n return markdownBehaviors\n}\n","import type {\n ArraySchemaType,\n BlockSchemaType,\n ObjectSchemaType,\n PortableTextBlock,\n SchemaType,\n SpanSchemaType,\n} from '@sanity/types'\nimport type {PortableTextMemberSchemaTypes} from '../types/editor'\n\nexport function getPortableTextMemberSchemaTypes(\n portableTextType: ArraySchemaType<PortableTextBlock>,\n): PortableTextMemberSchemaTypes {\n if (!portableTextType) {\n throw new Error(\"Parameter 'portabletextType' missing (required)\")\n }\n const blockType = portableTextType.of?.find(findBlockType) as\n | BlockSchemaType\n | undefined\n if (!blockType) {\n throw new Error('Block type is not defined in this schema (required)')\n }\n const childrenField = blockType.fields?.find(\n (field) => field.name === 'children',\n ) as {type: ArraySchemaType} | undefined\n if (!childrenField) {\n throw new Error('Children field for block type found in schema (required)')\n }\n const ofType = childrenField.type.of\n if (!ofType) {\n throw new Error(\n 'Valid types for block children not found in schema (required)',\n )\n }\n const spanType = ofType.find((memberType) => memberType.name === 'span') as\n | ObjectSchemaType\n | undefined\n if (!spanType) {\n throw new Error('Span type not found in schema (required)')\n }\n const inlineObjectTypes = (ofType.filter(\n (memberType) => memberType.name !== 'span',\n ) || []) as ObjectSchemaType[]\n const blockObjectTypes = (portableTextType.of?.filter(\n (field) => field.name !== blockType.name,\n ) || []) as ObjectSchemaType[]\n return {\n styles: resolveEnabledStyles(blockType),\n decorators: resolveEnabledDecorators(spanType),\n lists: resolveEnabledListItems(blockType),\n block: blockType,\n span: spanType,\n portableText: portableTextType,\n inlineObjects: inlineObjectTypes,\n blockObjects: blockObjectTypes,\n annotations: (spanType as SpanSchemaType).annotations,\n }\n}\n\nfunction resolveEnabledStyles(blockType: ObjectSchemaType) {\n const styleField = blockType.fields?.find(\n (btField) => btField.name === 'style',\n )\n if (!styleField) {\n throw new Error(\n \"A field with name 'style' is not defined in the block type (required).\",\n )\n }\n const textStyles =\n styleField.type.options?.list &&\n styleField.type.options.list?.filter(\n (style: {value: string}) => style.value,\n )\n if (!textStyles || textStyles.length === 0) {\n throw new Error(\n 'The style fields need at least one style ' +\n \"defined. I.e: {title: 'Normal', value: 'normal'}.\",\n )\n }\n return textStyles\n}\n\nfunction resolveEnabledDecorators(spanType: ObjectSchemaType) {\n return (spanType as any).decorators\n}\n\nfunction resolveEnabledListItems(blockType: ObjectSchemaType) {\n const listField = blockType.fields?.find(\n (btField) => btField.name === 'listItem',\n )\n if (!listField) {\n throw new Error(\n \"A field with name 'listItem' is not defined in the block type (required).\",\n )\n }\n const listItems =\n listField.type.options?.list &&\n listField.type.options.list.filter((list: {value: string}) => list.value)\n if (!listItems) {\n throw new Error('The list field need at least to be an empty array')\n }\n return listItems\n}\n\nfunction findBlockType(type: SchemaType): BlockSchemaType | null {\n if (type.type) {\n return findBlockType(type.type)\n }\n\n if (type.name === 'block') {\n return type as BlockSchemaType\n }\n\n return null\n}\n","import {Schema as SanitySchema} from '@sanity/schema'\nimport {\n defineField,\n defineType,\n type BlockDecoratorDefinition,\n type ObjectSchemaType,\n} from '@sanity/types'\nimport startCase from 'lodash.startcase'\nimport type {PortableTextMemberSchemaTypes} from '../types/editor'\nimport {getPortableTextMemberSchemaTypes} from '../utils/getPortableTextMemberSchemaTypes'\n\n/**\n * @alpha\n */\nexport type BaseDefinition = {\n name: string\n title?: string\n icon?: BlockDecoratorDefinition['icon']\n}\n\n/**\n * @alpha\n */\nexport type SchemaDefinition<\n TBaseDefinition extends BaseDefinition = BaseDefinition,\n> = {\n decorators?: ReadonlyArray<TBaseDefinition>\n blockObjects?: ReadonlyArray<TBaseDefinition>\n inlineObjects?: ReadonlyArray<TBaseDefinition>\n annotations?: ReadonlyArray<TBaseDefinition>\n lists?: ReadonlyArray<TBaseDefinition>\n styles?: ReadonlyArray<TBaseDefinition>\n}\n\n/**\n * @alpha\n */\nexport function defineSchema<const TSchemaDefinition extends SchemaDefinition>(\n definition: TSchemaDefinition,\n): TSchemaDefinition {\n return definition\n}\n\nexport function compileSchemaDefinition<\n TSchemaDefinition extends SchemaDefinition,\n>(definition?: TSchemaDefinition) {\n const blockObjects =\n definition?.blockObjects?.map((blockObject) =>\n defineType({\n type: 'object',\n // Very naive way to work around `SanitySchema.compile` adding default\n // fields to objects with the name `image`\n name: blockObject.name === 'image' ? 'tmp-image' : blockObject.name,\n title: blockObject.title,\n icon: blockObject.icon,\n fields: [],\n }),\n ) ?? []\n const inlineObjects =\n definition?.inlineObjects?.map((inlineObject) =>\n defineType({\n type: 'object',\n name: inlineObject.name,\n title: inlineObject.title,\n icon: inlineObject.icon,\n fields: [],\n }),\n ) ?? []\n\n const portableTextSchema = defineField({\n type: 'array',\n name: 'portable-text',\n of: [\n ...blockObjects.map((blockObject) => ({type: blockObject.name})),\n {\n type: 'block',\n name: 'block',\n of: inlineObjects.map((inlineObject) => ({type: inlineObject.name})),\n marks: {\n decorators:\n definition?.decorators?.map((decorator) => ({\n title: decorator.title ?? startCase(decorator.name),\n value: decorator.name,\n icon: decorator.icon,\n })) ?? [],\n annotations:\n definition?.annotations?.map((annotation) => ({\n name: annotation.name,\n type: 'object',\n title: annotation.title,\n icon: annotation.icon,\n })) ?? [],\n },\n lists:\n definition?.lists?.map((list) => ({\n value: list.name,\n title: list.title ?? startCase(list.name),\n icon: list.icon,\n })) ?? [],\n styles:\n definition?.styles?.map((style) => ({\n value: style.name,\n title: style.title ?? startCase(style.name),\n icon: style.icon,\n })) ?? [],\n },\n ],\n })\n\n const schema = SanitySchema.compile({\n types: [portableTextSchema, ...blockObjects, ...inlineObjects],\n }).get('portable-text')\n\n const pteSchema = getPortableTextMemberSchemaTypes(schema)\n\n return {\n ...pteSchema,\n blockObjects: pteSchema.blockObjects.map((blockObject) =>\n blockObject.name === 'tmp-image'\n ? ({\n ...blockObject,\n name: 'image',\n type: {\n ...blockObject.type,\n name: 'image',\n },\n } as ObjectSchemaType)\n : blockObject,\n ),\n } satisfies PortableTextMemberSchemaTypes\n}\n","import debug from 'debug'\n\nconst rootName = 'sanity-pte:'\n\nexport default debug(rootName)\nexport function debugWithName(name: string): debug.Debugger {\n const namespace = `${rootName}${name}`\n if (debug && debug.enabled(namespace)) {\n return debug(namespace)\n }\n return debug(rootName)\n}\n","import {isKeySegment, type Path} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport {\n Editor,\n Element,\n type Descendant,\n type Point,\n type Path as SlatePath,\n} from 'slate'\nimport type {\n EditorSelectionPoint,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport type {ObjectWithKeyAndType} from './ranges'\n\nexport function createKeyedPath(\n point: Point,\n value: ObjectWithKeyAndType[] | undefined,\n types: PortableTextMemberSchemaTypes,\n): Path | null {\n const blockPath = [point.path[0]]\n if (!value) {\n return null\n }\n const block = value[blockPath[0]]\n if (!block) {\n return null\n }\n const keyedBlockPath = [{_key: block._key}]\n if (block._type !== types.block.name) {\n return keyedBlockPath as Path\n }\n let keyedChildPath: Path | undefined\n const childPath = point.path.slice(0, 2)\n const child = Array.isArray(block.children) && block.children[childPath[1]]\n if (child) {\n keyedChildPath = ['children', {_key: child._key}]\n }\n return (\n keyedChildPath ? [...keyedBlockPath, ...keyedChildPath] : keyedBlockPath\n ) as Path\n}\n\nexport function createArrayedPath(\n point: EditorSelectionPoint,\n editor: Editor,\n): SlatePath {\n if (!editor) {\n return []\n }\n const [block, blockPath] = Array.from(\n Editor.nodes(editor, {\n at: [],\n match: (n) =>\n isKeySegment(point.path[0]) &&\n (n as Descendant)._key === point.path[0]._key,\n }),\n )[0] || [undefined, undefined]\n if (!block || !Element.isElement(block)) {\n return []\n }\n if (editor.isVoid(block)) {\n return [blockPath[0], 0]\n }\n const childPath = [point.path[2]]\n const childIndex = block.children.findIndex((child) =>\n isEqual([{_key: child._key}], childPath),\n )\n if (childIndex >= 0 && block.children[childIndex]) {\n const child = block.children[childIndex]\n if (Element.isElement(child) && editor.isVoid(child)) {\n return blockPath.concat(childIndex).concat(0)\n }\n return blockPath.concat(childIndex)\n }\n return blockPath\n}\n","import {Point, Range, type BaseRange, type Editor, type Operation} from 'slate'\nimport type {\n EditorSelection,\n EditorSelectionPoint,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport {createArrayedPath, createKeyedPath} from './paths'\n\nexport interface ObjectWithKeyAndType {\n _key: string\n _type: string\n children?: ObjectWithKeyAndType[]\n}\n\nexport function toPortableTextRange(\n value: ObjectWithKeyAndType[] | undefined,\n range: BaseRange | Partial<BaseRange> | null,\n types: PortableTextMemberSchemaTypes,\n): EditorSelection {\n if (!range) {\n return null\n }\n let anchor: EditorSelectionPoint | null = null\n let focus: EditorSelectionPoint | null = null\n const anchorPath = range.anchor && createKeyedPath(range.anchor, value, types)\n if (anchorPath && range.anchor) {\n anchor = {\n path: anchorPath,\n offset: range.anchor.offset,\n }\n }\n const focusPath = range.focus && createKeyedPath(range.focus, value, types)\n if (focusPath && range.focus) {\n focus = {\n path: focusPath,\n offset: range.focus.offset,\n }\n }\n const backward = Boolean(\n Range.isRange(range) ? Range.isBackward(range) : undefined,\n )\n return anchor && focus ? {anchor, focus, backward} : null\n}\n\nexport function toSlateRange(\n selection: EditorSelection,\n editor: Editor,\n): Range | null {\n if (!selection || !editor) {\n return null\n }\n const anchor = {\n path: createArrayedPath(selection.anchor, editor),\n offset: selection.anchor.offset,\n }\n const focus = {\n path: createArrayedPath(selection.focus, editor),\n offset: selection.focus.offset,\n }\n if (focus.path.length === 0 || anchor.path.length === 0) {\n return null\n }\n const range = anchor && focus ? {anchor, focus} : null\n return range\n}\n\nexport function moveRangeByOperation(\n range: Range,\n operation: Operation,\n): Range | null {\n const anchor = Point.transform(range.anchor, operation)\n const focus = Point.transform(range.focus, operation)\n\n if (anchor === null || focus === null) {\n return null\n }\n\n if (Point.equals(anchor, range.anchor) && Point.equals(focus, range.focus)) {\n return range\n }\n\n return {anchor, focus}\n}\n","import type {Path, PortableTextBlock} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport type {EditorSelection, EditorSelectionPoint} from '../types/editor'\n\nexport function normalizePoint(\n point: EditorSelectionPoint,\n value: PortableTextBlock[],\n): EditorSelectionPoint | null {\n if (!point || !value) {\n return null\n }\n const newPath: Path = []\n let newOffset: number = point.offset || 0\n const blockKey =\n typeof point.path[0] === 'object' &&\n '_key' in point.path[0] &&\n point.path[0]._key\n const childKey =\n typeof point.path[2] === 'object' &&\n '_key' in point.path[2] &&\n point.path[2]._key\n const block: PortableTextBlock | undefined = value.find(\n (blk) => blk._key === blockKey,\n )\n if (block) {\n newPath.push({_key: block._key})\n } else {\n return null\n }\n if (block && point.path[1] === 'children') {\n if (\n !block.children ||\n (Array.isArray(block.children) && block.children.length === 0)\n ) {\n return null\n }\n const child =\n Array.isArray(block.children) &&\n block.children.find((cld) => cld._key === childKey)\n if (child) {\n newPath.push('children')\n newPath.push({_key: child._key})\n newOffset =\n child.text && child.text.length >= point.offset\n ? point.offset\n : (child.text && child.text.length) || 0\n } else {\n return null\n }\n }\n return {path: newPath, offset: newOffset}\n}\n\nexport function normalizeSelection(\n selection: EditorSelection,\n value: PortableTextBlock[] | undefined,\n): EditorSelection | null {\n if (!selection || !value || value.length === 0) {\n return null\n }\n let newAnchor: EditorSelectionPoint | null = null\n let newFocus: EditorSelectionPoint | null = null\n const {anchor, focus} = selection\n if (\n anchor &&\n value.find((blk) => isEqual({_key: blk._key}, anchor.path[0]))\n ) {\n newAnchor = normalizePoint(anchor, value)\n }\n if (focus && value.find((blk) => isEqual({_key: blk._key}, focus.path[0]))) {\n newFocus = normalizePoint(focus, value)\n }\n if (newAnchor && newFocus) {\n return {anchor: newAnchor, focus: newFocus, backward: selection.backward}\n }\n return null\n}\n","import type {\n PathSegment,\n PortableTextBlock,\n PortableTextChild,\n PortableTextObject,\n PortableTextTextBlock,\n} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport {Element, Text, type Descendant, type Node} from 'slate'\nimport type {PortableTextMemberSchemaTypes} from '../types/editor'\n\nexport const EMPTY_MARKDEFS: PortableTextObject[] = []\n\nexport const VOID_CHILD_KEY = 'void-child'\n\ntype Partial<T> = {\n [P in keyof T]?: T[P]\n}\n\nfunction keepObjectEquality(\n object: PortableTextBlock | PortableTextChild,\n keyMap: Record<string, PortableTextBlock | PortableTextChild>,\n) {\n const value = keyMap[object._key]\n if (value && isEqual(object, value)) {\n return value\n }\n keyMap[object._key] = object\n return object\n}\n\nexport function toSlateValue(\n value: PortableTextBlock[] | undefined,\n {schemaTypes}: {schemaTypes: PortableTextMemberSchemaTypes},\n keyMap: Record<string, any> = {},\n): Descendant[] {\n if (value && Array.isArray(value)) {\n return value.map((block) => {\n const {_type, _key, ...rest} = block\n const voidChildren = [\n {_key: VOID_CHILD_KEY, _type: 'span', text: '', marks: []},\n ]\n const isPortableText = block && block._type === schemaTypes.block.name\n if (isPortableText) {\n const textBlock = block as PortableTextTextBlock\n let hasInlines = false\n const hasMissingStyle = typeof textBlock.style === 'undefined'\n const hasMissingMarkDefs = typeof textBlock.markDefs === 'undefined'\n const hasMissingChildren = typeof textBlock.children === 'undefined'\n\n const children = (textBlock.children || []).map((child) => {\n const {_type: cType, _key: cKey, ...cRest} = child\n // Return 'slate' version of inline object where the actual\n // value is stored in the `value` property.\n // In slate, inline objects are represented as regular\n // children with actual text node in order to be able to\n // be selected the same way as the rest of the (text) content.\n if (cType !== 'span') {\n hasInlines = true\n return keepObjectEquality(\n {\n _type: cType,\n _key: cKey,\n children: voidChildren,\n value: cRest,\n __inline: true,\n },\n keyMap,\n )\n }\n // Original child object (span)\n return child\n })\n // Return original block\n if (\n !hasMissingStyle &&\n !hasMissingMarkDefs &&\n !hasMissingChildren &&\n !hasInlines &&\n Element.isElement(block)\n ) {\n // Original object\n return block\n }\n // TODO: remove this when we have a better way to handle missing style\n if (hasMissingStyle) {\n rest.style = schemaTypes.styles[0].value\n }\n return keepObjectEquality({_type, _key, ...rest, children}, keyMap)\n }\n return keepObjectEquality(\n {\n _type,\n _key,\n children: voidChildren,\n value: rest,\n },\n keyMap,\n )\n }) as Descendant[]\n }\n return []\n}\n\nexport function fromSlateValue(\n value: Descendant[],\n textBlockType: string,\n keyMap: Record<string, PortableTextBlock | PortableTextChild> = {},\n): PortableTextBlock[] {\n return value.map((block) => {\n const {_key, _type} = block\n if (!_key || !_type) {\n throw new Error('Not a valid block')\n }\n if (\n _type === textBlockType &&\n 'children' in block &&\n Array.isArray(block.children) &&\n _key\n ) {\n let hasInlines = false\n const children = block.children.map((child) => {\n const {_type: _cType} = child\n if ('value' in child && _cType !== 'span') {\n hasInlines = true\n const {\n value: v,\n _key: k,\n _type: t,\n __inline: _i,\n children: _c,\n ...rest\n } = child\n return keepObjectEquality(\n {...rest, ...v, _key: k as string, _type: t as string},\n keyMap,\n )\n }\n return child\n })\n if (!hasInlines) {\n return block as PortableTextBlock // Original object\n }\n return keepObjectEquality(\n {...block, children, _key, _type},\n keyMap,\n ) as PortableTextBlock\n }\n const blockValue = 'value' in block && block.value\n return keepObjectEquality(\n {_key, _type, ...(typeof blockValue === 'object' ? blockValue : {})},\n keyMap,\n ) as PortableTextBlock\n })\n}\n\nexport function isEqualToEmptyEditor(\n children: Descendant[] | PortableTextBlock[],\n schemaTypes: PortableTextMemberSchemaTypes,\n): boolean {\n return (\n children === undefined ||\n (children && Array.isArray(children) && children.length === 0) ||\n (children &&\n Array.isArray(children) &&\n children.length === 1 &&\n Element.isElement(children[0]) &&\n children[0]._type === schemaTypes.block.name &&\n 'style' in children[0] &&\n children[0].style === schemaTypes.styles[0].value &&\n !('listItem' in children[0]) &&\n Array.isArray(children[0].children) &&\n children[0].children.length === 1 &&\n Text.isText(children[0].children[0]) &&\n children[0].children[0]._type === 'span' &&\n !children[0].children[0].marks?.join('') &&\n children[0].children[0].text === '')\n )\n}\n\nexport function findBlockAndIndexFromPath(\n firstPathSegment: PathSegment,\n children: (Node | Partial<Node>)[],\n): [Element | undefined, number | undefined] {\n let blockIndex = -1\n const isNumber = Number.isInteger(Number(firstPathSegment))\n if (isNumber) {\n blockIndex = Number(firstPathSegment)\n } else if (children) {\n blockIndex = children.findIndex(\n (blk) =>\n Element.isElement(blk) && isEqual({_key: blk._key}, firstPathSegment),\n )\n }\n if (blockIndex > -1) {\n return [children[blockIndex] as Element, blockIndex]\n }\n return [undefined, -1]\n}\n\nexport function findChildAndIndexFromPath(\n secondPathSegment: PathSegment,\n block: Element,\n): [Element | Text | undefined, number] {\n let childIndex = -1\n const isNumber = Number.isInteger(Number(secondPathSegment))\n if (isNumber) {\n childIndex = Number(secondPathSegment)\n } else {\n childIndex = block.children.findIndex((child) =>\n isEqual({_key: child._key}, secondPathSegment),\n )\n }\n if (childIndex > -1) {\n return [block.children[childIndex] as Element | Text, childIndex]\n }\n return [undefined, -1]\n}\n\nexport function getValueOrInitialValue(\n value: unknown,\n initialValue: PortableTextBlock[],\n): PortableTextBlock[] | undefined {\n if (value && Array.isArray(value) && value.length > 0) {\n return value\n }\n return initialValue\n}\n","import type {Editor, Element, Range} from 'slate'\nimport type {EditorSelection} from '..'\n\n// Is the editor currently receiving remote changes that are being applied to the content?\nexport const IS_PROCESSING_REMOTE_CHANGES: WeakMap<Editor, boolean> =\n new WeakMap()\n// Is the editor currently producing local changes that are not yet submitted?\nexport const IS_PROCESSING_LOCAL_CHANGES: WeakMap<Editor, boolean> =\n new WeakMap()\n\n// Is the editor dragging something?\nexport const IS_DRAGGING: WeakMap<Editor, boolean> = new WeakMap()\n// Is the editor dragging a element?\nexport const IS_DRAGGING_BLOCK_ELEMENT: WeakMap<Editor, Element> = new WeakMap()\n\n// When dragging elements, this will be the target element\nexport const IS_DRAGGING_ELEMENT_TARGET: WeakMap<Editor, Element> =\n new WeakMap()\n// Target position for dragging over a block\nexport const IS_DRAGGING_BLOCK_TARGET_POSITION: WeakMap<\n Editor,\n 'top' | 'bottom'\n> = new WeakMap()\n\nexport const KEY_TO_SLATE_ELEMENT: WeakMap<Editor, any | undefined> =\n new WeakMap()\nexport const KEY_TO_VALUE_ELEMENT: WeakMap<Editor, any | undefined> =\n new WeakMap()\n\n// Keep object relation to slate range in the portable-text-range\nexport const SLATE_TO_PORTABLE_TEXT_RANGE = new WeakMap<\n Range,\n EditorSelection\n>()\n","import type {PortableTextBlock, PortableTextChild} from '@sanity/types'\n\ntype Props = {\n value: PortableTextBlock | PortableTextChild\n}\n\nconst DefaultObject = (props: Props): JSX.Element => {\n return (\n <div>\n <pre>{JSON.stringify(props.value, null, 2)}</pre>\n </div>\n )\n}\n\nDefaultObject.displayName = 'DefaultObject'\n\nexport default DefaultObject\n","import {styled} from 'styled-components'\n\nexport const DefaultBlockObject = styled.div<{selected: boolean}>`\n user-select: none;\n border: ${(props) => {\n if (props.selected) {\n return '1px solid blue'\n }\n return '1px solid transparent'\n }};\n`\n\nexport const DefaultInlineObject = styled.span<{selected: boolean}>`\n background: #999;\n border: ${(props) => {\n if (props.selected) {\n return '1px solid blue'\n }\n return '1px solid transparent'\n }};\n`\n\ntype ListItemProps = {listLevel: number; listStyle: string}\n\nexport const DefaultListItem = styled.div<ListItemProps>`\n &.pt-list-item {\n width: fit-content;\n position: relative;\n display: block;\n\n /* Important 'transform' in order to force refresh the ::before and ::after rules\n in Webkit: https://stackoverflow.com/a/21947628/831480\n */\n transform: translateZ(0);\n margin-left: ${(props: ListItemProps) => getLeftPositionForListLevel(props.listLevel)};\n }\n &.pt-list-item > .pt-list-item-inner {\n display: flex;\n margin: 0;\n padding: 0;\n &:before {\n justify-content: flex-start;\n vertical-align: top;\n }\n }\n &.pt-list-item-bullet > .pt-list-item-inner:before {\n content: '${(props: ListItemProps) =>\n getContentForListLevelAndStyle(props.listLevel, props.listStyle)}';\n font-size: 0.4375rem; /* 7px */\n line-height: 1.5rem; /* Same as body text */\n /* Optical alignment */\n position: relative;\n }\n }\n &.pt-list-item-bullet > .pt-list-item-inner {\n &:before {\n min-width: 1.5rem; /* Make sure space between bullet and text never shrinks */\n }\n }\n &.pt-list-item-number {\n counter-increment: ${(props: {listLevel: number}) =>\n getCounterIncrementForListLevel(props.listLevel)};\n counter-reset: ${(props: {listLevel: number}) => getCounterResetForListLevel(props.listLevel)};\n }\n & + :not(.pt-list-item-number) {\n counter-reset: listItemNumber;\n }\n &.pt-list-item-number > .pt-list-item-inner:before {\n content: ${(props) => getCounterContentForListLevel(props.listLevel)};\n min-width: 1.5rem; /* Make sure space between number and text never shrinks */\n /* Optical alignment */\n position: relative;\n top: 1px;\n }\n`\n\nexport const DefaultListItemInner = styled.div``\n\nfunction getLeftPositionForListLevel(level: number) {\n switch (Number(level)) {\n case 1:\n return '1.5em'\n case 2:\n return '3em'\n case 3:\n return '4.5em'\n case 4:\n return '6em'\n case 5:\n return '7.5em'\n case 6:\n return '9em'\n case 7:\n return '10.5em'\n case 8:\n return '12em'\n case 9:\n return '13.5em'\n case 10:\n return '15em'\n default:\n return '0em'\n }\n}\n\nconst bullets = ['●', '○', '■']\n\nfunction getContentForListLevelAndStyle(level: number, style: string) {\n const normalizedLevel = (level - 1) % 3\n if (style === 'bullet') {\n return bullets[normalizedLevel]\n }\n return '*'\n}\n\nfunction getCounterIncrementForListLevel(level: number) {\n switch (level) {\n case 1:\n return 'listItemNumber'\n case 2:\n return 'listItemAlpha'\n case 3:\n return 'listItemRoman'\n case 4:\n return 'listItemNumberNext'\n case 5:\n return 'listItemLetterNext'\n case 6:\n return 'listItemRomanNext'\n case 7:\n return 'listItemNumberNextNext'\n case 8:\n return 'listItemAlphaNextNext'\n case 9:\n return 'listItemRomanNextNext'\n default:\n return 'listItemNumberNextNextNext'\n }\n}\n\nfunction getCounterResetForListLevel(level: number) {\n switch (level) {\n case 1:\n return 'listItemAlpha'\n case 2:\n return 'listItemRoman'\n case 3:\n return 'listItemNumberNext'\n case 4:\n return 'listItemLetterNext'\n case 5:\n return 'listItemRomanNext'\n case 6:\n return 'listItemNumberNextNext'\n case 7:\n return 'listItemAlphaNextNext'\n case 8:\n return 'listItemRomanNextNext'\n case 9:\n return 'listItemNumberNextNextNext'\n default:\n return 'listItemNumberNextNextNext'\n }\n}\n\nfunction getCounterContentForListLevel(level: number) {\n switch (level) {\n case 1:\n return `counter(listItemNumber) '. '`\n case 2:\n return `counter(listItemAlpha, lower-alpha) '. '`\n case 3:\n return `counter(listItemRoman, lower-roman) '. '`\n case 4:\n return `counter(listItemNumberNext) '. '`\n case 5:\n return `counter(listItemLetterNext, lower-alpha) '. '`\n case 6:\n return `counter(listItemRomanNext, lower-roman) '. '`\n case 7:\n return `counter(listItemNumberNextNext) '. '`\n case 8:\n return `counter(listItemAlphaNextNext, lower-alpha) '. '`\n case 9:\n return `counter(listItemRomanNextNext, lower-roman) '. '`\n default:\n return `counter(listItemNumberNextNextNext) '. '`\n }\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type DragEvent,\n type MutableRefObject,\n type ReactNode,\n} from 'react'\nimport {Editor, Path, Transforms, type Element as SlateElement} from 'slate'\nimport {ReactEditor, useSlateStatic} from 'slate-react'\nimport {debugWithName} from '../../utils/debug'\nimport {\n IS_DRAGGING,\n IS_DRAGGING_BLOCK_ELEMENT,\n IS_DRAGGING_BLOCK_TARGET_POSITION,\n IS_DRAGGING_ELEMENT_TARGET,\n} from '../../utils/weakMaps'\n\nconst debug = debugWithName('components:DraggableBlock')\nconst debugRenders = false\n\n/**\n * @internal\n */\nexport interface DraggableBlockProps {\n children: ReactNode\n element: SlateElement\n readOnly: boolean\n blockRef: MutableRefObject<HTMLDivElement | null>\n}\n\n/**\n * Implements drag and drop functionality on editor block nodes\n * @internal\n */\nexport const DraggableBlock = ({\n children,\n element,\n readOnly,\n blockRef,\n}: DraggableBlockProps) => {\n const editor = useSlateStatic()\n const dragGhostRef: MutableRefObject<undefined | HTMLElement> = useRef()\n const [isDragOver, setIsDragOver] = useState(false)\n const isVoid = useMemo(\n () => Editor.isVoid(editor, element),\n [editor, element],\n )\n const isInline = useMemo(\n () => Editor.isInline(editor, element),\n [editor, element],\n )\n\n const [blockElement, setBlockElement] = useState<HTMLElement | null>(null)\n\n useEffect(\n () =>\n setBlockElement(\n blockRef ? blockRef.current : ReactEditor.toDOMNode(editor, element),\n ),\n [editor, element, blockRef],\n )\n\n // Note: this is called not for the dragging block, but for the targets when the block is dragged over them\n const handleDragOver = useCallback(\n (event: DragEvent) => {\n const isMyDragOver = IS_DRAGGING_BLOCK_ELEMENT.get(editor)\n // debug('Drag over', blockElement)\n if (!isMyDragOver || !blockElement) {\n return\n }\n event.preventDefault()\n event.dataTransfer.dropEffect = 'move'\n IS_DRAGGING_ELEMENT_TARGET.set(editor, element)\n const elementRect = blockElement.getBoundingClientRect()\n const offset = elementRect.top\n const height = elementRect.height\n const Y = event.pageY\n const loc = Math.abs(offset - Y)\n let position: 'top' | 'bottom' = 'bottom'\n if (element === editor.children[0]) {\n position = 'top'\n } else if (loc < height / 2) {\n position = 'top'\n IS_DRAGGING_BLOCK_TARGET_POSITION.set(editor, position)\n } else {\n position = 'bottom'\n IS_DRAGGING_BLOCK_TARGET_POSITION.set(editor, position)\n }\n if (isMyDragOver === element) {\n event.dataTransfer.dropEffect = 'none'\n return\n }\n setIsDragOver(true)\n },\n [blockElement, editor, element],\n )\n\n // Note: this is called not for the dragging block, but for the targets when the block is dragged over them\n const handleDragLeave = useCallback(() => {\n setIsDragOver(false)\n }, [])\n\n // Note: this is called for the dragging block\n const handleDragEnd = useCallback(\n (event: DragEvent) => {\n const targetBlock = IS_DRAGGING_ELEMENT_TARGET.get(editor)\n if (targetBlock) {\n IS_DRAGGING.set(editor, false)\n event.preventDefault()\n event.stopPropagation()\n IS_DRAGGING_ELEMENT_TARGET.delete(editor)\n if (dragGhostRef.current) {\n debug('Removing drag ghost')\n document.body.removeChild(dragGhostRef.current)\n }\n const dragPosition = IS_DRAGGING_BLOCK_TARGET_POSITION.get(editor)\n IS_DRAGGING_BLOCK_TARGET_POSITION.delete(editor)\n let targetPath = ReactEditor.findPath(editor, targetBlock)\n const myPath = ReactEditor.findPath(editor, element)\n const isBefore = Path.isBefore(myPath, targetPath)\n if (dragPosition === 'bottom' && !isBefore) {\n // If it is already at the bottom, don't do anything.\n if (targetPath[0] >= editor.children.length - 1) {\n debug('target is already at the bottom, not moving')\n return\n }\n const originalPath = targetPath\n targetPath = Path.next(targetPath)\n debug(\n `Adjusting targetPath from ${JSON.stringify(originalPath)} to ${JSON.stringify(\n targetPath,\n )}`,\n )\n }\n if (\n dragPosition === 'top' &&\n isBefore &&\n targetPath[0] !== editor.children.length - 1\n ) {\n const originalPath = targetPath\n targetPath = Path.previous(targetPath)\n debug(\n `Adjusting targetPath from ${JSON.stringify(originalPath)} to ${JSON.stringify(\n targetPath,\n )}`,\n )\n }\n if (Path.equals(targetPath, myPath)) {\n event.preventDefault()\n debug('targetPath and myPath is the same, not moving')\n return\n }\n debug(\n `Moving element ${element._key} from path ${JSON.stringify(myPath)} to ${JSON.stringify(\n targetPath,\n )} (${dragPosition})`,\n )\n Transforms.moveNodes(editor, {at: myPath, to: targetPath})\n editor.onChange()\n return\n }\n debug('No target element, not doing anything')\n },\n [editor, element],\n )\n // Note: this is called not for the dragging block, but for the drop target\n const handleDrop = useCallback(\n (event: DragEvent) => {\n if (IS_DRAGGING_BLOCK_ELEMENT.get(editor)) {\n debug('On drop (prevented)', element)\n event.preventDefault()\n event.stopPropagation()\n setIsDragOver(false)\n }\n },\n [editor, element],\n )\n // Note: this is called for the dragging block\n const handleDrag = useCallback(\n (event: DragEvent) => {\n if (!isVoid) {\n IS_DRAGGING_BLOCK_ELEMENT.delete(editor)\n return\n }\n IS_DRAGGING.set(editor, true)\n IS_DRAGGING_BLOCK_ELEMENT.set(editor, element)\n event.stopPropagation() // Stop propagation so that leafs don't get this and take focus/selection!\n\n const target = event.target\n\n if (target instanceof HTMLElement) {\n target.style.opacity = '1'\n }\n },\n [editor, element, isVoid],\n )\n\n // Note: this is called for the dragging block\n const handleDragStart = useCallback(\n (event: DragEvent) => {\n if (!isVoid || isInline) {\n debug('Not dragging block')\n IS_DRAGGING_BLOCK_ELEMENT.delete(editor)\n IS_DRAGGING.set(editor, false)\n return\n }\n debug('Drag start')\n IS_DRAGGING.set(editor, true)\n if (event.dataTransfer) {\n event.dataTransfer.setData('application/portable-text', 'something')\n event.dataTransfer.effectAllowed = 'move'\n }\n // Clone blockElement so that it will not be visually clipped by scroll-containers etc.\n // The application that uses the portable-text-editor may indicate the element used as\n // drag ghost by adding a truthy data attribute 'data-pt-drag-ghost-element' to a HTML element.\n if (blockElement && blockElement instanceof HTMLElement) {\n let dragGhost = blockElement.cloneNode(true) as HTMLElement\n const customGhost = dragGhost.querySelector(\n '[data-pt-drag-ghost-element]',\n )\n if (customGhost) {\n dragGhost = customGhost as HTMLElement\n }\n\n // Set the `data-dragged` attribute so the consumer can style the element while it’s dragged\n dragGhost.setAttribute('data-dragged', '')\n\n if (document.body) {\n dragGhostRef.current = dragGhost\n dragGhost.style.position = 'absolute'\n dragGhost.style.left = '-99999px'\n dragGhost.style.boxSizing = 'border-box'\n document.body.appendChild(dragGhost)\n const rect = blockElement.getBoundingClientRect()\n const x = event.clientX - rect.left\n const y = event.clientY - rect.top\n dragGhost.style.width = `${rect.width}px`\n dragGhost.style.height = `${rect.height}px`\n event.dataTransfer.setDragImage(dragGhost, x, y)\n }\n }\n handleDrag(event)\n },\n [blockElement, editor, handleDrag, isInline, isVoid],\n )\n\n const isDraggingOverFirstBlock =\n isDragOver && editor.children[0] === IS_DRAGGING_ELEMENT_TARGET.get(editor)\n const isDraggingOverLastBlock =\n isDragOver &&\n editor.children[editor.children.length - 1] ===\n IS_DRAGGING_ELEMENT_TARGET.get(editor)\n const dragPosition = IS_DRAGGING_BLOCK_TARGET_POSITION.get(editor)\n\n const isDraggingOverTop =\n isDraggingOverFirstBlock ||\n (isDragOver &&\n !isDraggingOverFirstBlock &&\n !isDraggingOverLastBlock &&\n dragPosition === 'top')\n const isDraggingOverBottom =\n isDraggingOverLastBlock ||\n (isDragOver &&\n !isDraggingOverFirstBlock &&\n !isDraggingOverLastBlock &&\n dragPosition === 'bottom')\n\n const dropIndicator = useMemo(\n () => (\n <div\n className=\"pt-drop-indicator\"\n style={{\n position: 'absolute',\n width: '100%',\n height: 1,\n borderBottom: '1px solid currentColor',\n zIndex: 5,\n }}\n />\n ),\n [],\n )\n\n if (readOnly) {\n return <>{children}</>\n }\n\n if (debugRenders) {\n debug('render')\n }\n\n return (\n <div\n draggable={isVoid}\n onDragStart={handleDragStart}\n onDrag={handleDrag}\n onDragOver={handleDragOver}\n onDragLeave={handleDragLeave}\n onDragEnd={handleDragEnd}\n onDrop={handleDrop}\n >\n {isDraggingOverTop && dropIndicator}\n {children}\n {isDraggingOverBottom && dropIndicator}\n </div>\n )\n}\n\nDraggableBlock.displayName = 'DraggableBlock'\n","import type {\n Path,\n PortableTextChild,\n PortableTextObject,\n PortableTextTextBlock,\n} from '@sanity/types'\nimport {useMemo, useRef, type FunctionComponent, type ReactElement} from 'react'\nimport {Editor, Range, Element as SlateElement} from 'slate'\nimport {\n ReactEditor,\n useSelected,\n useSlateStatic,\n type RenderElementProps,\n} from 'slate-react'\nimport type {\n BlockRenderProps,\n PortableTextMemberSchemaTypes,\n RenderBlockFunction,\n RenderChildFunction,\n RenderListItemFunction,\n RenderStyleFunction,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue} from '../../utils/values'\nimport {KEY_TO_VALUE_ELEMENT} from '../../utils/weakMaps'\nimport ObjectNode from '../nodes/DefaultObject'\nimport {\n DefaultBlockObject,\n DefaultListItem,\n DefaultListItemInner,\n} from '../nodes/index'\nimport {DraggableBlock} from './DraggableBlock'\n\nconst debug = debugWithName('components:Element')\nconst debugRenders = false\nconst EMPTY_ANNOTATIONS: PortableTextObject[] = []\n\n/**\n * @internal\n */\nexport interface ElementProps {\n attributes: RenderElementProps['attributes']\n children: ReactElement\n element: SlateElement\n schemaTypes: PortableTextMemberSchemaTypes\n readOnly: boolean\n renderBlock?: RenderBlockFunction\n renderChild?: RenderChildFunction\n renderListItem?: RenderListItemFunction\n renderStyle?: RenderStyleFunction\n spellCheck?: boolean\n}\n\nconst inlineBlockStyle = {display: 'inline-block'}\n\n/**\n * Renders Portable Text block and inline object nodes in Slate\n * @internal\n */\nexport const Element: FunctionComponent<ElementProps> = ({\n attributes,\n children,\n element,\n schemaTypes,\n readOnly,\n renderBlock,\n renderChild,\n renderListItem,\n renderStyle,\n spellCheck,\n}) => {\n const editor = useSlateStatic()\n const selected = useSelected()\n const blockRef = useRef<HTMLDivElement | null>(null)\n const inlineBlockObjectRef = useRef(null)\n const focused =\n (selected && editor.selection && Range.isCollapsed(editor.selection)) ||\n false\n\n const value = useMemo(\n () =>\n fromSlateValue(\n [element],\n schemaTypes.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0],\n [editor, element, schemaTypes.block.name],\n )\n\n let renderedBlock = children\n\n let className: string | undefined\n\n const blockPath: Path = useMemo(() => [{_key: element._key}], [element])\n\n if (typeof element._type !== 'string') {\n throw new Error(`Expected element to have a _type property`)\n }\n\n if (typeof element._key !== 'string') {\n throw new Error(`Expected element to have a _key property`)\n }\n\n // Test for inline objects first\n if (editor.isInline(element)) {\n const path = ReactEditor.findPath(editor, element)\n const [block] = Editor.node(editor, path, {depth: 1})\n const schemaType = schemaTypes.inlineObjects.find(\n (_type) => _type.name === element._type,\n )\n if (!schemaType) {\n throw new Error('Could not find type for inline block element')\n }\n if (SlateElement.isElement(block)) {\n const elmPath: Path = [\n {_key: block._key},\n 'children',\n {_key: element._key},\n ]\n if (debugRenders) {\n debug(`Render ${element._key} (inline object)`)\n }\n return (\n <span {...attributes}>\n {/* Note that children must follow immediately or cut and selections will not work properly in Chrome. */}\n {children}\n <span\n draggable={!readOnly}\n className=\"pt-inline-object\"\n data-testid=\"pt-inline-object\"\n ref={inlineBlockObjectRef}\n key={element._key}\n style={inlineBlockStyle}\n contentEditable={false}\n >\n {renderChild &&\n renderChild({\n annotations: EMPTY_ANNOTATIONS, // These inline objects currently doesn't support annotations. This is a limitation of the current PT spec/model.\n children: <ObjectNode value={value} />,\n editorElementRef: inlineBlockObjectRef,\n focused,\n path: elmPath,\n schemaType,\n selected,\n type: schemaType,\n value: value as PortableTextChild,\n })}\n {!renderChild && <ObjectNode value={value} />}\n </span>\n </span>\n )\n }\n throw new Error('Block not found!')\n }\n\n // If not inline, it's either a block (text) or a block object (non-text)\n // NOTE: text blocks aren't draggable with DraggableBlock (yet?)\n if (element._type === schemaTypes.block.name) {\n className = `pt-block pt-text-block`\n const isListItem = 'listItem' in element\n if (debugRenders) {\n debug(`Render ${element._key} (text block)`)\n }\n const style = ('style' in element && element.style) || 'normal'\n className = `pt-block pt-text-block pt-text-block-style-${style}`\n const blockStyleType = schemaTypes.styles.find(\n (item) => item.value === style,\n )\n if (renderStyle && blockStyleType) {\n renderedBlock = renderStyle({\n block: element as PortableTextTextBlock,\n children,\n focused,\n selected,\n value: style,\n path: blockPath,\n schemaType: blockStyleType,\n editorElementRef: blockRef,\n })\n }\n let level: number | undefined\n if (isListItem) {\n if (typeof element.level === 'number') {\n level = element.level\n }\n className += ` pt-list-item pt-list-item-${element.listItem} pt-list-item-level-${level || 1}`\n }\n if (editor.isListBlock(value) && isListItem && element.listItem) {\n const listType = schemaTypes.lists.find(\n (item) => item.value === element.listItem,\n )\n if (renderListItem && listType) {\n renderedBlock = renderListItem({\n block: value,\n children: renderedBlock,\n focused,\n selected,\n value: element.listItem,\n path: blockPath,\n schemaType: listType,\n level: value.level || 1,\n editorElementRef: blockRef,\n })\n } else {\n renderedBlock = (\n <DefaultListItem\n listStyle={value.listItem || schemaTypes.lists[0].value}\n listLevel={value.level || 1}\n >\n <DefaultListItemInner>{renderedBlock}</DefaultListItemInner>\n </DefaultListItem>\n )\n }\n }\n const renderProps: Omit<BlockRenderProps, 'type'> = Object.defineProperty(\n {\n children: renderedBlock,\n editorElementRef: blockRef,\n focused,\n level,\n listItem: isListItem ? element.listItem : undefined,\n path: blockPath,\n selected,\n style,\n schemaType: schemaTypes.block,\n value,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaTypes.block\n },\n },\n )\n\n const propsOrDefaultRendered = renderBlock\n ? renderBlock(renderProps as BlockRenderProps)\n : children\n return (\n <div\n key={element._key}\n {...attributes}\n className={className}\n spellCheck={spellCheck}\n >\n <DraggableBlock\n element={element}\n readOnly={readOnly}\n blockRef={blockRef}\n >\n <div ref={blockRef}>{propsOrDefaultRendered}</div>\n </DraggableBlock>\n </div>\n )\n }\n const schemaType = schemaTypes.blockObjects.find(\n (_type) => _type.name === element._type,\n )\n if (!schemaType) {\n throw new Error(\n `Could not find schema type for block element of _type ${element._type}`,\n )\n }\n if (debugRenders) {\n debug(`Render ${element._key} (object block)`)\n }\n className = 'pt-block pt-object-block'\n const block = fromSlateValue(\n [element],\n schemaTypes.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0]\n let renderedBlockFromProps: JSX.Element | undefined\n if (renderBlock) {\n const _props: Omit<BlockRenderProps, 'type'> = Object.defineProperty(\n {\n children: <ObjectNode value={value} />,\n editorElementRef: blockRef,\n focused,\n path: blockPath,\n schemaType,\n selected,\n value: block,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaType\n },\n },\n )\n renderedBlockFromProps = renderBlock(_props as BlockRenderProps)\n }\n return (\n <div key={element._key} {...attributes} className={className}>\n {children}\n <DraggableBlock element={element} readOnly={readOnly} blockRef={blockRef}>\n {renderedBlockFromProps && (\n <div ref={blockRef} contentEditable={false}>\n {renderedBlockFromProps}\n </div>\n )}\n {!renderedBlockFromProps && (\n <DefaultBlockObject selected={selected}>\n <ObjectNode value={value} />\n </DefaultBlockObject>\n )}\n </DraggableBlock>\n </div>\n )\n}\n\nElement.displayName = 'Element'\n","import {createContext, useContext} from 'react'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\n/**\n * A React context for sharing the editor object.\n */\nexport const PortableTextEditorContext =\n createContext<PortableTextEditor | null>(null)\n\n/**\n * @public\n * Get the current editor object from the React context.\n */\nexport const usePortableTextEditor = (): PortableTextEditor => {\n const editor = useContext(PortableTextEditorContext)\n\n if (!editor) {\n throw new Error(\n `The \\`usePortableTextEditor\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n\n return editor\n}\n","import type {PortableTextObject} from '@sanity/types'\nimport {useCallback, type ReactNode} from 'react'\n\ntype Props = {\n annotation: PortableTextObject\n children: ReactNode\n}\nexport function DefaultAnnotation(props: Props) {\n const handleClick = useCallback(\n () => alert(JSON.stringify(props.annotation)),\n [props.annotation],\n )\n return (\n <span style={{color: 'blue'}} onClick={handleClick}>\n {props.children}\n </span>\n )\n}\n\nDefaultAnnotation.displayName = 'DefaultAnnotation'\n","import {Schema} from '@sanity/schema'\n\nexport function compileType(rawType: any) {\n return Schema.compile({\n name: 'blockTypeSchema',\n types: [rawType],\n }).get(rawType.name)\n}\n","import {insert, set, setIfMissing, unset} from '@portabletext/patches'\nimport {\n isPortableTextTextBlock,\n type PortableTextBlock,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport {flatten, isPlainObject, uniq} from 'lodash'\nimport type {\n InvalidValueResolution,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\n\nexport interface Validation {\n valid: boolean\n resolution: InvalidValueResolution | null\n value: PortableTextBlock[] | undefined\n}\n\nexport function validateValue(\n value: PortableTextBlock[] | undefined,\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\n): Validation {\n let resolution: InvalidValueResolution | null = null\n let valid = true\n const validChildTypes = [\n types.span.name,\n ...types.inlineObjects.map((t) => t.name),\n ]\n const validBlockTypes = [\n types.block.name,\n ...types.blockObjects.map((t) => t.name),\n ]\n\n // Undefined is allowed\n if (value === undefined) {\n return {valid: true, resolution: null, value}\n }\n // Only lengthy arrays are allowed in the editor.\n if (!Array.isArray(value) || value.length === 0) {\n return {\n valid: false,\n resolution: {\n patches: [unset([])],\n description:\n 'Editor value must be an array of Portable Text blocks, or undefined.',\n action: 'Unset the value',\n item: value,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.not-an-array.description',\n action: 'inputs.portable-text.invalid-value.not-an-array.action',\n },\n },\n value,\n }\n }\n if (\n value.some((blk: PortableTextBlock, index: number): boolean => {\n // Is the block an object?\n if (!isPlainObject(blk)) {\n resolution = {\n patches: [unset([index])],\n description: `Block must be an object, got ${String(blk)}`,\n action: `Unset invalid item`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.not-an-object.description',\n action: 'inputs.portable-text.invalid-value.not-an-object.action',\n values: {index},\n },\n }\n return true\n }\n // Test that every block has a _key prop\n if (!blk._key || typeof blk._key !== 'string') {\n resolution = {\n patches: [set({...blk, _key: keyGenerator()}, [index])],\n description: `Block at index ${index} is missing required _key.`,\n action: 'Set the block with a random _key value',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-key.description',\n action: 'inputs.portable-text.invalid-value.missing-key.action',\n values: {index},\n },\n }\n return true\n }\n // Test that every block has valid _type\n if (!blk._type || !validBlockTypes.includes(blk._type)) {\n // Special case where block type is set to default 'block', but the block type is named something else according to the schema.\n if (blk._type === 'block') {\n const currentBlockTypeName = types.block.name\n resolution = {\n patches: [\n set({...blk, _type: currentBlockTypeName}, [{_key: blk._key}]),\n ],\n description: `Block with _key '${blk._key}' has invalid type name '${blk._type}'. According to the schema, the block type name is '${currentBlockTypeName}'`,\n action: `Use type '${currentBlockTypeName}'`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.incorrect-block-type.description',\n action:\n 'inputs.portable-text.invalid-value.incorrect-block-type.action',\n values: {key: blk._key, expectedTypeName: currentBlockTypeName},\n },\n }\n return true\n }\n\n // If the block has no `_type`, but aside from that is a valid Portable Text block\n if (\n !blk._type &&\n isPortableTextTextBlock({...blk, _type: types.block.name})\n ) {\n resolution = {\n patches: [\n set({...blk, _type: types.block.name}, [{_key: blk._key}]),\n ],\n description: `Block with _key '${blk._key}' is missing a type name. According to the schema, the block type name is '${types.block.name}'`,\n action: `Use type '${types.block.name}'`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-block-type.description',\n action:\n 'inputs.portable-text.invalid-value.missing-block-type.action',\n values: {key: blk._key, expectedTypeName: types.block.name},\n },\n }\n return true\n }\n\n if (!blk._type) {\n resolution = {\n patches: [unset([{_key: blk._key}])],\n description: `Block with _key '${blk._key}' is missing an _type property`,\n action: 'Remove the block',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-type.description',\n action: 'inputs.portable-text.invalid-value.missing-type.action',\n values: {key: blk._key},\n },\n }\n return true\n }\n\n resolution = {\n patches: [unset([{_key: blk._key}])],\n description: `Block with _key '${blk._key}' has invalid _type '${blk._type}'`,\n action: 'Remove the block',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.disallowed-type.description',\n action: 'inputs.portable-text.invalid-value.disallowed-type.action',\n values: {key: blk._key, typeName: blk._type},\n },\n }\n return true\n }\n\n // Test regular text blocks\n if (blk._type === types.block.name) {\n const textBlock = blk as PortableTextTextBlock\n // Test that it has a valid children property (array)\n if (textBlock.children && !Array.isArray(textBlock.children)) {\n resolution = {\n patches: [set({children: []}, [{_key: textBlock._key}])],\n description: `Text block with _key '${textBlock._key}' has a invalid required property 'children'.`,\n action: 'Reset the children property',\n item: textBlock,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-or-invalid-children.description',\n action:\n 'inputs.portable-text.invalid-value.missing-or-invalid-children.action',\n values: {key: textBlock._key},\n },\n }\n return true\n }\n // Test that children is set and lengthy\n if (\n textBlock.children === undefined ||\n (Array.isArray(textBlock.children) && textBlock.children.length === 0)\n ) {\n const newSpan = {\n _type: types.span.name,\n _key: keyGenerator(),\n text: '',\n marks: [],\n }\n resolution = {\n autoResolve: true,\n patches: [\n setIfMissing([], [{_key: blk._key}, 'children']),\n insert([newSpan], 'after', [{_key: blk._key}, 'children', 0]),\n ],\n description: `Children for text block with _key '${blk._key}' is empty.`,\n action: 'Insert an empty text',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.empty-children.description',\n action:\n 'inputs.portable-text.invalid-value.empty-children.action',\n values: {key: blk._key},\n },\n }\n return true\n }\n\n const allUsedMarks = uniq(\n flatten(\n textBlock.children\n .filter((cld) => cld._type === types.span.name)\n .map((cld) => cld.marks || []),\n ) as string[],\n )\n\n // Test that all markDefs are in use (remove orphaned markDefs)\n if (Array.isArray(blk.markDefs) && blk.markDefs.length > 0) {\n const unusedMarkDefs: string[] = uniq(\n blk.markDefs\n .map((def) => def._key)\n .filter((key) => !allUsedMarks.includes(key)),\n )\n if (unusedMarkDefs.length > 0) {\n resolution = {\n autoResolve: true,\n patches: unusedMarkDefs.map((markDefKey) =>\n unset([{_key: blk._key}, 'markDefs', {_key: markDefKey}]),\n ),\n description: `Block contains orphaned data (unused mark definitions): ${unusedMarkDefs.join(\n ', ',\n )}.`,\n action: 'Remove unused mark definition item',\n item: blk,\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.orphaned-mark-defs.description',\n action:\n 'inputs.portable-text.invalid-value.orphaned-mark-defs.action',\n values: {\n key: blk._key,\n unusedMarkDefs: unusedMarkDefs.map((m) => m.toString()),\n },\n },\n }\n return true\n }\n }\n\n // Test that every annotation mark used has a definition\n const annotationMarks = allUsedMarks.filter(\n (mark) => !types.decorators.map((dec) => dec.value).includes(mark),\n )\n const orphanedMarks = annotationMarks.filter(\n (mark) =>\n textBlock.markDefs === undefined ||\n !textBlock.markDefs.find((def) => def._key === mark),\n )\n if (orphanedMarks.length > 0) {\n const spanChildren = textBlock.children.filter(\n (cld) =>\n cld._type === types.span.name &&\n Array.isArray(cld.marks) &&\n cld.marks.some((mark) => orphanedMarks.includes(mark)),\n ) as PortableTextSpan[]\n if (spanChildren) {\n const orphaned = orphanedMarks.join(', ')\n resolution = {\n autoResolve: true,\n patches: spanChildren.map((child) => {\n return set(\n (child.marks || []).filter(\n (cMrk) => !orphanedMarks.includes(cMrk),\n ),\n [{_key: blk._key}, 'children', {_key: child._key}, 'marks'],\n )\n }),\n description: `Block with _key '${blk._key}' contains marks (${orphaned}) not supported by the current content model.`,\n action: 'Remove invalid marks',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.orphaned-marks.description',\n action:\n 'inputs.portable-text.invalid-value.orphaned-marks.action',\n values: {\n key: blk._key,\n orphanedMarks: orphanedMarks.map((m) => m.toString()),\n },\n },\n }\n return true\n }\n }\n\n // Test every child\n if (\n textBlock.children.some((child, cIndex: number) => {\n if (!isPlainObject(child)) {\n resolution = {\n patches: [unset([{_key: blk._key}, 'children', cIndex])],\n description: `Child at index '${cIndex}' in block with key '${blk._key}' is not an object.`,\n action: 'Remove the item',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.non-object-child.description',\n action:\n 'inputs.portable-text.invalid-value.non-object-child.action',\n values: {key: blk._key, index: cIndex},\n },\n }\n return true\n }\n\n if (!child._key || typeof child._key !== 'string') {\n const newChild = {...child, _key: keyGenerator()}\n resolution = {\n autoResolve: true,\n patches: [\n set(newChild, [{_key: blk._key}, 'children', cIndex]),\n ],\n description: `Child at index ${cIndex} is missing required _key in block with _key ${blk._key}.`,\n action: 'Set a new random _key on the object',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-child-key.description',\n action:\n 'inputs.portable-text.invalid-value.missing-child-key.action',\n values: {key: blk._key, index: cIndex},\n },\n }\n return true\n }\n\n // Verify that children have valid types\n if (!child._type) {\n resolution = {\n patches: [\n unset([{_key: blk._key}, 'children', {_key: child._key}]),\n ],\n description: `Child with _key '${child._key}' in block with key '${blk._key}' is missing '_type' property.`,\n action: 'Remove the object',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-child-type.description',\n action:\n 'inputs.portable-text.invalid-value.missing-child-type.action',\n values: {key: blk._key, childKey: child._key},\n },\n }\n return true\n }\n\n if (!validChildTypes.includes(child._type)) {\n resolution = {\n patches: [\n unset([{_key: blk._key}, 'children', {_key: child._key}]),\n ],\n description: `Child with _key '${child._key}' in block with key '${blk._key}' has invalid '_type' property (${child._type}).`,\n action: 'Remove the object',\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.disallowed-child-type.description',\n action:\n 'inputs.portable-text.invalid-value.disallowed-child-type.action',\n values: {\n key: blk._key,\n childKey: child._key,\n childType: child._type,\n },\n },\n }\n return true\n }\n\n // Verify that spans have .text property that is a string\n if (\n child._type === types.span.name &&\n typeof child.text !== 'string'\n ) {\n resolution = {\n patches: [\n set({...child, text: ''}, [\n {_key: blk._key},\n 'children',\n {_key: child._key},\n ]),\n ],\n description: `Child with _key '${child._key}' in block with key '${blk._key}' has missing or invalid text property!`,\n action: `Write an empty text property to the object`,\n item: blk,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.invalid-span-text.description',\n action:\n 'inputs.portable-text.invalid-value.invalid-span-text.action',\n values: {key: blk._key, childKey: child._key},\n },\n }\n return true\n }\n return false\n })\n ) {\n valid = false\n }\n }\n return false\n })\n ) {\n valid = false\n }\n return {valid, resolution, value}\n}\n","import type {Editor} from 'slate'\nimport {\n IS_PROCESSING_LOCAL_CHANGES,\n IS_PROCESSING_REMOTE_CHANGES,\n} from './weakMaps'\n\nexport function withRemoteChanges(editor: Editor, fn: () => void): void {\n const prev = isChangingRemotely(editor) || false\n IS_PROCESSING_REMOTE_CHANGES.set(editor, true)\n fn()\n IS_PROCESSING_REMOTE_CHANGES.set(editor, prev)\n}\n\nexport function isChangingRemotely(editor: Editor): boolean | undefined {\n return IS_PROCESSING_REMOTE_CHANGES.get(editor)\n}\n\nexport function isChangingLocally(editor: Editor): boolean | undefined {\n return IS_PROCESSING_LOCAL_CHANGES.get(editor)\n}\n","import type {Editor} from 'slate'\n\nexport const PATCHING: WeakMap<Editor, boolean | undefined> = new WeakMap()\n\nexport function withoutPatching(editor: Editor, fn: () => void): void {\n const prev = isPatching(editor)\n PATCHING.set(editor, false)\n fn()\n PATCHING.set(editor, prev)\n}\n\nexport function isPatching(editor: Editor): boolean | undefined {\n return PATCHING.get(editor)\n}\n","function isHighSurrogate(char) {\n const charCode = char.charCodeAt(0);\n return charCode >= 55296 && charCode <= 56319;\n}\nfunction isLowSurrogate(char) {\n const charCode = char.charCodeAt(0);\n return charCode >= 56320 && charCode <= 57343;\n}\nfunction cloneDiff(diff) {\n const [type, patch] = diff;\n return [type, patch];\n}\nfunction getCommonOverlap(textA, textB) {\n let text1 = textA;\n let text2 = textB;\n const text1Length = text1.length;\n const text2Length = text2.length;\n if (text1Length === 0 || text2Length === 0) {\n return 0;\n }\n if (text1Length > text2Length) {\n text1 = text1.substring(text1Length - text2Length);\n } else if (text1Length < text2Length) {\n text2 = text2.substring(0, text1Length);\n }\n const textLength = Math.min(text1Length, text2Length);\n if (text1 === text2) {\n return textLength;\n }\n let best = 0;\n let length = 1;\n for (let found = 0; found !== -1;) {\n const pattern = text1.substring(textLength - length);\n found = text2.indexOf(pattern);\n if (found === -1) {\n return best;\n }\n length += found;\n if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) {\n best = length;\n length++;\n }\n }\n return best;\n}\nfunction getCommonPrefix(text1, text2) {\n if (!text1 || !text2 || text1[0] !== text2[0]) {\n return 0;\n }\n let pointerMin = 0;\n let pointerMax = Math.min(text1.length, text2.length);\n let pointerMid = pointerMax;\n let pointerStart = 0;\n while (pointerMin < pointerMid) {\n if (text1.substring(pointerStart, pointerMid) === text2.substring(pointerStart, pointerMid)) {\n pointerMin = pointerMid;\n pointerStart = pointerMin;\n } else {\n pointerMax = pointerMid;\n }\n pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);\n }\n return pointerMid;\n}\nfunction getCommonSuffix(text1, text2) {\n if (!text1 || !text2 || text1[text1.length - 1] !== text2[text2.length - 1]) {\n return 0;\n }\n let pointerMin = 0;\n let pointerMax = Math.min(text1.length, text2.length);\n let pointerMid = pointerMax;\n let pointerEnd = 0;\n while (pointerMin < pointerMid) {\n if (text1.substring(text1.length - pointerMid, text1.length - pointerEnd) === text2.substring(text2.length - pointerMid, text2.length - pointerEnd)) {\n pointerMin = pointerMid;\n pointerEnd = pointerMin;\n } else {\n pointerMax = pointerMid;\n }\n pointerMid = Math.floor((pointerMax - pointerMin) / 2 + pointerMin);\n }\n return pointerMid;\n}\nfunction cleanupSemantic(rawDiffs) {\n let diffs = rawDiffs.map(diff => cloneDiff(diff));\n let hasChanges = false;\n const equalities = [];\n let equalitiesLength = 0;\n let lastEquality = null;\n let pointer = 0;\n let lengthInsertions1 = 0;\n let lengthDeletions1 = 0;\n let lengthInsertions2 = 0;\n let lengthDeletions2 = 0;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] === DIFF_EQUAL) {\n equalities[equalitiesLength++] = pointer;\n lengthInsertions1 = lengthInsertions2;\n lengthDeletions1 = lengthDeletions2;\n lengthInsertions2 = 0;\n lengthDeletions2 = 0;\n lastEquality = diffs[pointer][1];\n } else {\n if (diffs[pointer][0] === DIFF_INSERT) {\n lengthInsertions2 += diffs[pointer][1].length;\n } else {\n lengthDeletions2 += diffs[pointer][1].length;\n }\n if (lastEquality && lastEquality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastEquality.length <= Math.max(lengthInsertions2, lengthDeletions2)) {\n diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]);\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n equalitiesLength--;\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n lengthInsertions1 = 0;\n lengthDeletions1 = 0;\n lengthInsertions2 = 0;\n lengthDeletions2 = 0;\n lastEquality = null;\n hasChanges = true;\n }\n }\n pointer++;\n }\n if (hasChanges) {\n diffs = cleanupMerge(diffs);\n }\n diffs = cleanupSemanticLossless(diffs);\n pointer = 1;\n while (pointer < diffs.length) {\n if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) {\n const deletion = diffs[pointer - 1][1];\n const insertion = diffs[pointer][1];\n const overlapLength1 = getCommonOverlap(deletion, insertion);\n const overlapLength2 = getCommonOverlap(insertion, deletion);\n if (overlapLength1 >= overlapLength2) {\n if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) {\n diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]);\n diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1);\n diffs[pointer + 1][1] = insertion.substring(overlapLength1);\n pointer++;\n }\n } else if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) {\n diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]);\n diffs[pointer - 1][0] = DIFF_INSERT;\n diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2);\n diffs[pointer + 1][0] = DIFF_DELETE;\n diffs[pointer + 1][1] = deletion.substring(overlapLength2);\n pointer++;\n }\n pointer++;\n }\n pointer++;\n }\n return diffs;\n}\nconst nonAlphaNumericRegex = /[^a-zA-Z0-9]/;\nconst whitespaceRegex = /\\s/;\nconst linebreakRegex = /[\\r\\n]/;\nconst blanklineEndRegex = /\\n\\r?\\n$/;\nconst blanklineStartRegex = /^\\r?\\n\\r?\\n/;\nfunction cleanupSemanticLossless(rawDiffs) {\n const diffs = rawDiffs.map(diff => cloneDiff(diff));\n function diffCleanupSemanticScore(one, two) {\n if (!one || !two) {\n return 6;\n }\n const char1 = one.charAt(one.length - 1);\n const char2 = two.charAt(0);\n const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex);\n const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex);\n const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex);\n const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex);\n const lineBreak1 = whitespace1 && char1.match(linebreakRegex);\n const lineBreak2 = whitespace2 && char2.match(linebreakRegex);\n const blankLine1 = lineBreak1 && one.match(blanklineEndRegex);\n const blankLine2 = lineBreak2 && two.match(blanklineStartRegex);\n if (blankLine1 || blankLine2) {\n return 5;\n } else if (lineBreak1 || lineBreak2) {\n return 4;\n } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n return 3;\n } else if (whitespace1 || whitespace2) {\n return 2;\n } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n return 1;\n }\n return 0;\n }\n let pointer = 1;\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {\n let equality1 = diffs[pointer - 1][1];\n let edit = diffs[pointer][1];\n let equality2 = diffs[pointer + 1][1];\n const commonOffset = getCommonSuffix(equality1, edit);\n if (commonOffset) {\n const commonString = edit.substring(edit.length - commonOffset);\n equality1 = equality1.substring(0, equality1.length - commonOffset);\n edit = commonString + edit.substring(0, edit.length - commonOffset);\n equality2 = commonString + equality2;\n }\n let bestEquality1 = equality1;\n let bestEdit = edit;\n let bestEquality2 = equality2;\n let bestScore = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);\n while (edit.charAt(0) === equality2.charAt(0)) {\n equality1 += edit.charAt(0);\n edit = edit.substring(1) + equality2.charAt(0);\n equality2 = equality2.substring(1);\n const score = diffCleanupSemanticScore(equality1, edit) + diffCleanupSemanticScore(edit, equality2);\n if (score >= bestScore) {\n bestScore = score;\n bestEquality1 = equality1;\n bestEdit = edit;\n bestEquality2 = equality2;\n }\n }\n if (diffs[pointer - 1][1] !== bestEquality1) {\n if (bestEquality1) {\n diffs[pointer - 1][1] = bestEquality1;\n } else {\n diffs.splice(pointer - 1, 1);\n pointer--;\n }\n diffs[pointer][1] = bestEdit;\n if (bestEquality2) {\n diffs[pointer + 1][1] = bestEquality2;\n } else {\n diffs.splice(pointer + 1, 1);\n pointer--;\n }\n }\n }\n pointer++;\n }\n return diffs;\n}\nfunction cleanupMerge(rawDiffs) {\n let diffs = rawDiffs.map(diff => cloneDiff(diff));\n diffs.push([DIFF_EQUAL, \"\"]);\n let pointer = 0;\n let countDelete = 0;\n let countInsert = 0;\n let textDelete = \"\";\n let textInsert = \"\";\n let commonlength;\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n countInsert++;\n textInsert += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_DELETE:\n countDelete++;\n textDelete += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_EQUAL:\n if (countDelete + countInsert > 1) {\n if (countDelete !== 0 && countInsert !== 0) {\n commonlength = getCommonPrefix(textInsert, textDelete);\n if (commonlength !== 0) {\n if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) {\n diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength);\n } else {\n diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]);\n pointer++;\n }\n textInsert = textInsert.substring(commonlength);\n textDelete = textDelete.substring(commonlength);\n }\n commonlength = getCommonSuffix(textInsert, textDelete);\n if (commonlength !== 0) {\n diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1];\n textInsert = textInsert.substring(0, textInsert.length - commonlength);\n textDelete = textDelete.substring(0, textDelete.length - commonlength);\n }\n }\n pointer -= countDelete + countInsert;\n diffs.splice(pointer, countDelete + countInsert);\n if (textDelete.length) {\n diffs.splice(pointer, 0, [DIFF_DELETE, textDelete]);\n pointer++;\n }\n if (textInsert.length) {\n diffs.splice(pointer, 0, [DIFF_INSERT, textInsert]);\n pointer++;\n }\n pointer++;\n } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {\n diffs[pointer - 1][1] += diffs[pointer][1];\n diffs.splice(pointer, 1);\n } else {\n pointer++;\n }\n countInsert = 0;\n countDelete = 0;\n textDelete = \"\";\n textInsert = \"\";\n break;\n default:\n throw new Error(\"Unknown diff operation\");\n }\n }\n if (diffs[diffs.length - 1][1] === \"\") {\n diffs.pop();\n }\n let hasChanges = false;\n pointer = 1;\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) {\n if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) {\n diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length);\n diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n diffs.splice(pointer - 1, 1);\n hasChanges = true;\n } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) {\n diffs[pointer - 1][1] += diffs[pointer + 1][1];\n diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1];\n diffs.splice(pointer + 1, 1);\n hasChanges = true;\n }\n }\n pointer++;\n }\n if (hasChanges) {\n diffs = cleanupMerge(diffs);\n }\n return diffs;\n}\nfunction trueCount() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return args.reduce((n, bool) => n + (bool ? 1 : 0), 0);\n}\nfunction cleanupEfficiency(rawDiffs) {\n let editCost = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;\n let diffs = rawDiffs.map(diff => cloneDiff(diff));\n let hasChanges = false;\n const equalities = [];\n let equalitiesLength = 0;\n let lastEquality = null;\n let pointer = 0;\n let preIns = false;\n let preDel = false;\n let postIns = false;\n let postDel = false;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] === DIFF_EQUAL) {\n if (diffs[pointer][1].length < editCost && (postIns || postDel)) {\n equalities[equalitiesLength++] = pointer;\n preIns = postIns;\n preDel = postDel;\n lastEquality = diffs[pointer][1];\n } else {\n equalitiesLength = 0;\n lastEquality = null;\n }\n postIns = false;\n postDel = false;\n } else {\n if (diffs[pointer][0] === DIFF_DELETE) {\n postDel = true;\n } else {\n postIns = true;\n }\n if (lastEquality && (preIns && preDel && postIns && postDel || lastEquality.length < editCost / 2 && trueCount(preIns, preDel, postIns, postDel) === 3)) {\n diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastEquality]);\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n equalitiesLength--;\n lastEquality = null;\n if (preIns && preDel) {\n postIns = true;\n postDel = true;\n equalitiesLength = 0;\n } else {\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n postIns = false;\n postDel = false;\n }\n hasChanges = true;\n }\n }\n pointer++;\n }\n if (hasChanges) {\n diffs = cleanupMerge(diffs);\n }\n return diffs;\n}\nfunction bisect(text1, text2, deadline) {\n const text1Length = text1.length;\n const text2Length = text2.length;\n const maxD = Math.ceil((text1Length + text2Length) / 2);\n const vOffset = maxD;\n const vLength = 2 * maxD;\n const v1 = new Array(vLength);\n const v2 = new Array(vLength);\n for (let x = 0; x < vLength; x++) {\n v1[x] = -1;\n v2[x] = -1;\n }\n v1[vOffset + 1] = 0;\n v2[vOffset + 1] = 0;\n const delta = text1Length - text2Length;\n const front = delta % 2 !== 0;\n let k1start = 0;\n let k1end = 0;\n let k2start = 0;\n let k2end = 0;\n for (let d = 0; d < maxD; d++) {\n if (Date.now() > deadline) {\n break;\n }\n for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n const k1Offset = vOffset + k1;\n let x1;\n if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) {\n x1 = v1[k1Offset + 1];\n } else {\n x1 = v1[k1Offset - 1] + 1;\n }\n let y1 = x1 - k1;\n while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) {\n x1++;\n y1++;\n }\n v1[k1Offset] = x1;\n if (x1 > text1Length) {\n k1end += 2;\n } else if (y1 > text2Length) {\n k1start += 2;\n } else if (front) {\n const k2Offset = vOffset + delta - k1;\n if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {\n const x2 = text1Length - v2[k2Offset];\n if (x1 >= x2) {\n return bisectSplit(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n const k2Offset = vOffset + k2;\n let x2;\n if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) {\n x2 = v2[k2Offset + 1];\n } else {\n x2 = v2[k2Offset - 1] + 1;\n }\n let y2 = x2 - k2;\n while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) {\n x2++;\n y2++;\n }\n v2[k2Offset] = x2;\n if (x2 > text1Length) {\n k2end += 2;\n } else if (y2 > text2Length) {\n k2start += 2;\n } else if (!front) {\n const k1Offset = vOffset + delta - k2;\n if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {\n const x1 = v1[k1Offset];\n const y1 = vOffset + x1 - k1Offset;\n x2 = text1Length - x2;\n if (x1 >= x2) {\n return bisectSplit(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n }\n return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];\n}\nfunction bisectSplit(text1, text2, x, y, deadline) {\n const text1a = text1.substring(0, x);\n const text2a = text2.substring(0, y);\n const text1b = text1.substring(x);\n const text2b = text2.substring(y);\n const diffs = doDiff(text1a, text2a, {\n checkLines: false,\n deadline\n });\n const diffsb = doDiff(text1b, text2b, {\n checkLines: false,\n deadline\n });\n return diffs.concat(diffsb);\n}\nfunction findHalfMatch(text1, text2) {\n let timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n if (timeout <= 0) {\n return null;\n }\n const longText = text1.length > text2.length ? text1 : text2;\n const shortText = text1.length > text2.length ? text2 : text1;\n if (longText.length < 4 || shortText.length * 2 < longText.length) {\n return null;\n }\n const halfMatch1 = halfMatchI(longText, shortText, Math.ceil(longText.length / 4));\n const halfMatch2 = halfMatchI(longText, shortText, Math.ceil(longText.length / 2));\n let halfMatch;\n if (halfMatch1 && halfMatch2) {\n halfMatch = halfMatch1[4].length > halfMatch2[4].length ? halfMatch1 : halfMatch2;\n } else if (!halfMatch1 && !halfMatch2) {\n return null;\n } else if (!halfMatch2) {\n halfMatch = halfMatch1;\n } else if (!halfMatch1) {\n halfMatch = halfMatch2;\n }\n if (!halfMatch) {\n throw new Error(\"Unable to find a half match.\");\n }\n let text1A;\n let text1B;\n let text2A;\n let text2B;\n if (text1.length > text2.length) {\n text1A = halfMatch[0];\n text1B = halfMatch[1];\n text2A = halfMatch[2];\n text2B = halfMatch[3];\n } else {\n text2A = halfMatch[0];\n text2B = halfMatch[1];\n text1A = halfMatch[2];\n text1B = halfMatch[3];\n }\n const midCommon = halfMatch[4];\n return [text1A, text1B, text2A, text2B, midCommon];\n}\nfunction halfMatchI(longText, shortText, i) {\n const seed = longText.slice(i, i + Math.floor(longText.length / 4));\n let j = -1;\n let bestCommon = \"\";\n let bestLongTextA;\n let bestLongTextB;\n let bestShortTextA;\n let bestShortTextB;\n while ((j = shortText.indexOf(seed, j + 1)) !== -1) {\n const prefixLength = getCommonPrefix(longText.slice(i), shortText.slice(j));\n const suffixLength = getCommonSuffix(longText.slice(0, i), shortText.slice(0, j));\n if (bestCommon.length < suffixLength + prefixLength) {\n bestCommon = shortText.slice(j - suffixLength, j) + shortText.slice(j, j + prefixLength);\n bestLongTextA = longText.slice(0, i - suffixLength);\n bestLongTextB = longText.slice(i + prefixLength);\n bestShortTextA = shortText.slice(0, j - suffixLength);\n bestShortTextB = shortText.slice(j + prefixLength);\n }\n }\n if (bestCommon.length * 2 >= longText.length) {\n return [bestLongTextA || \"\", bestLongTextB || \"\", bestShortTextA || \"\", bestShortTextB || \"\", bestCommon || \"\"];\n }\n return null;\n}\nfunction charsToLines(diffs, lineArray) {\n for (let x = 0; x < diffs.length; x++) {\n const chars = diffs[x][1];\n const text = [];\n for (let y = 0; y < chars.length; y++) {\n text[y] = lineArray[chars.charCodeAt(y)];\n }\n diffs[x][1] = text.join(\"\");\n }\n}\nfunction linesToChars(textA, textB) {\n const lineArray = [];\n const lineHash = {};\n lineArray[0] = \"\";\n function diffLinesToMunge(text) {\n let chars = \"\";\n let lineStart = 0;\n let lineEnd = -1;\n let lineArrayLength = lineArray.length;\n while (lineEnd < text.length - 1) {\n lineEnd = text.indexOf(\"\\n\", lineStart);\n if (lineEnd === -1) {\n lineEnd = text.length - 1;\n }\n let line = text.slice(lineStart, lineEnd + 1);\n if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) {\n chars += String.fromCharCode(lineHash[line]);\n } else {\n if (lineArrayLength === maxLines) {\n line = text.slice(lineStart);\n lineEnd = text.length;\n }\n chars += String.fromCharCode(lineArrayLength);\n lineHash[line] = lineArrayLength;\n lineArray[lineArrayLength++] = line;\n }\n lineStart = lineEnd + 1;\n }\n return chars;\n }\n let maxLines = 4e4;\n const chars1 = diffLinesToMunge(textA);\n maxLines = 65535;\n const chars2 = diffLinesToMunge(textB);\n return {\n chars1,\n chars2,\n lineArray\n };\n}\nfunction doLineModeDiff(textA, textB, opts) {\n let text1 = textA;\n let text2 = textB;\n const a = linesToChars(text1, text2);\n text1 = a.chars1;\n text2 = a.chars2;\n const linearray = a.lineArray;\n let diffs = doDiff(text1, text2, {\n checkLines: false,\n deadline: opts.deadline\n });\n charsToLines(diffs, linearray);\n diffs = cleanupSemantic(diffs);\n diffs.push([DIFF_EQUAL, \"\"]);\n let pointer = 0;\n let countDelete = 0;\n let countInsert = 0;\n let textDelete = \"\";\n let textInsert = \"\";\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n countInsert++;\n textInsert += diffs[pointer][1];\n break;\n case DIFF_DELETE:\n countDelete++;\n textDelete += diffs[pointer][1];\n break;\n case DIFF_EQUAL:\n if (countDelete >= 1 && countInsert >= 1) {\n diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert);\n pointer = pointer - countDelete - countInsert;\n const aa = doDiff(textDelete, textInsert, {\n checkLines: false,\n deadline: opts.deadline\n });\n for (let j = aa.length - 1; j >= 0; j--) {\n diffs.splice(pointer, 0, aa[j]);\n }\n pointer += aa.length;\n }\n countInsert = 0;\n countDelete = 0;\n textDelete = \"\";\n textInsert = \"\";\n break;\n default:\n throw new Error(\"Unknown diff operation.\");\n }\n pointer++;\n }\n diffs.pop();\n return diffs;\n}\nfunction computeDiff(text1, text2, opts) {\n let diffs;\n if (!text1) {\n return [[DIFF_INSERT, text2]];\n }\n if (!text2) {\n return [[DIFF_DELETE, text1]];\n }\n const longtext = text1.length > text2.length ? text1 : text2;\n const shorttext = text1.length > text2.length ? text2 : text1;\n const i = longtext.indexOf(shorttext);\n if (i !== -1) {\n diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]];\n if (text1.length > text2.length) {\n diffs[0][0] = DIFF_DELETE;\n diffs[2][0] = DIFF_DELETE;\n }\n return diffs;\n }\n if (shorttext.length === 1) {\n return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];\n }\n const halfMatch = findHalfMatch(text1, text2);\n if (halfMatch) {\n const text1A = halfMatch[0];\n const text1B = halfMatch[1];\n const text2A = halfMatch[2];\n const text2B = halfMatch[3];\n const midCommon = halfMatch[4];\n const diffsA = doDiff(text1A, text2A, opts);\n const diffsB = doDiff(text1B, text2B, opts);\n return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB);\n }\n if (opts.checkLines && text1.length > 100 && text2.length > 100) {\n return doLineModeDiff(text1, text2, opts);\n }\n return bisect(text1, text2, opts.deadline);\n}\nconst DIFF_DELETE = -1;\nconst DIFF_INSERT = 1;\nconst DIFF_EQUAL = 0;\nfunction diff(textA, textB, opts) {\n if (textA === null || textB === null) {\n throw new Error(\"Null input. (diff)\");\n }\n const diffs = doDiff(textA, textB, createInternalOpts(opts || {}));\n adjustDiffForSurrogatePairs(diffs);\n return diffs;\n}\nfunction doDiff(textA, textB, options) {\n let text1 = textA;\n let text2 = textB;\n if (text1 === text2) {\n return text1 ? [[DIFF_EQUAL, text1]] : [];\n }\n let commonlength = getCommonPrefix(text1, text2);\n const commonprefix = text1.substring(0, commonlength);\n text1 = text1.substring(commonlength);\n text2 = text2.substring(commonlength);\n commonlength = getCommonSuffix(text1, text2);\n const commonsuffix = text1.substring(text1.length - commonlength);\n text1 = text1.substring(0, text1.length - commonlength);\n text2 = text2.substring(0, text2.length - commonlength);\n let diffs = computeDiff(text1, text2, options);\n if (commonprefix) {\n diffs.unshift([DIFF_EQUAL, commonprefix]);\n }\n if (commonsuffix) {\n diffs.push([DIFF_EQUAL, commonsuffix]);\n }\n diffs = cleanupMerge(diffs);\n return diffs;\n}\nfunction createDeadLine(timeout) {\n let t = 1;\n if (typeof timeout !== \"undefined\") {\n t = timeout <= 0 ? Number.MAX_VALUE : timeout;\n }\n return Date.now() + t * 1e3;\n}\nfunction createInternalOpts(opts) {\n return {\n checkLines: true,\n deadline: createDeadLine(opts.timeout || 1),\n ...opts\n };\n}\nfunction combineChar(data, char, dir) {\n return dir === 1 ? data + char : char + data;\n}\nfunction splitChar(data, dir) {\n return dir === 1 ? [data.substring(0, data.length - 1), data[data.length - 1]] : [data.substring(1), data[0]];\n}\nfunction hasSharedChar(diffs, i, j, dir) {\n return dir === 1 ? diffs[i][1][diffs[i][1].length - 1] === diffs[j][1][diffs[j][1].length - 1] : diffs[i][1][0] === diffs[j][1][0];\n}\nfunction deisolateChar(diffs, i, dir) {\n const inv = dir === 1 ? -1 : 1;\n let insertIdx = null;\n let deleteIdx = null;\n let j = i + dir;\n for (; j >= 0 && j < diffs.length && (insertIdx === null || deleteIdx === null); j += dir) {\n const [op, text2] = diffs[j];\n if (text2.length === 0) {\n continue;\n }\n if (op === DIFF_INSERT) {\n if (insertIdx === null) {\n insertIdx = j;\n }\n continue;\n } else if (op === DIFF_DELETE) {\n if (deleteIdx === null) {\n deleteIdx = j;\n }\n continue;\n } else if (op === DIFF_EQUAL) {\n if (insertIdx === null && deleteIdx === null) {\n const [rest, char2] = splitChar(diffs[i][1], dir);\n diffs[i][1] = rest;\n diffs[j][1] = combineChar(diffs[j][1], char2, inv);\n return;\n }\n break;\n }\n }\n if (insertIdx !== null && deleteIdx !== null && hasSharedChar(diffs, insertIdx, deleteIdx, dir)) {\n const [insertText, insertChar] = splitChar(diffs[insertIdx][1], inv);\n const [deleteText] = splitChar(diffs[deleteIdx][1], inv);\n diffs[insertIdx][1] = insertText;\n diffs[deleteIdx][1] = deleteText;\n diffs[i][1] = combineChar(diffs[i][1], insertChar, dir);\n return;\n }\n const [text, char] = splitChar(diffs[i][1], dir);\n diffs[i][1] = text;\n if (insertIdx === null) {\n diffs.splice(j, 0, [DIFF_INSERT, char]);\n if (deleteIdx !== null && deleteIdx >= j) deleteIdx++;\n } else {\n diffs[insertIdx][1] = combineChar(diffs[insertIdx][1], char, inv);\n }\n if (deleteIdx === null) {\n diffs.splice(j, 0, [DIFF_DELETE, char]);\n } else {\n diffs[deleteIdx][1] = combineChar(diffs[deleteIdx][1], char, inv);\n }\n}\nfunction adjustDiffForSurrogatePairs(diffs) {\n for (let i = 0; i < diffs.length; i++) {\n const [diffType, diffText] = diffs[i];\n if (diffText.length === 0) continue;\n const firstChar = diffText[0];\n const lastChar = diffText[diffText.length - 1];\n if (isHighSurrogate(lastChar) && diffType === DIFF_EQUAL) {\n deisolateChar(diffs, i, 1);\n }\n if (isLowSurrogate(firstChar) && diffType === DIFF_EQUAL) {\n deisolateChar(diffs, i, -1);\n }\n }\n for (let i = 0; i < diffs.length; i++) {\n if (diffs[i][1].length === 0) {\n diffs.splice(i, 1);\n }\n }\n}\nconst DEFAULT_OPTIONS = {\n /**\n * At what point is no match declared (0.0 = perfection, 1.0 = very loose).\n */\n threshold: 0.5,\n /**\n * How far to search for a match (0 = exact location, 1000+ = broad match).\n * A match this many characters away from the expected location will add\n * 1.0 to the score (0.0 is a perfect match).\n */\n distance: 1e3\n};\nfunction applyDefaults(options) {\n return {\n ...DEFAULT_OPTIONS,\n ...options\n };\n}\nconst MAX_BITS$1 = 32;\nfunction bitap(text, pattern, loc) {\n let opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n if (pattern.length > MAX_BITS$1) {\n throw new Error(\"Pattern too long for this browser.\");\n }\n const options = applyDefaults(opts);\n const s = getAlphabetFromPattern(pattern);\n function getBitapScore(e, x) {\n const accuracy = e / pattern.length;\n const proximity = Math.abs(loc - x);\n if (!options.distance) {\n return proximity ? 1 : accuracy;\n }\n return accuracy + proximity / options.distance;\n }\n let scoreThreshold = options.threshold;\n let bestLoc = text.indexOf(pattern, loc);\n if (bestLoc !== -1) {\n scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold);\n bestLoc = text.lastIndexOf(pattern, loc + pattern.length);\n if (bestLoc !== -1) {\n scoreThreshold = Math.min(getBitapScore(0, bestLoc), scoreThreshold);\n }\n }\n const matchmask = 1 << pattern.length - 1;\n bestLoc = -1;\n let binMin;\n let binMid;\n let binMax = pattern.length + text.length;\n let lastRd = [];\n for (let d = 0; d < pattern.length; d++) {\n binMin = 0;\n binMid = binMax;\n while (binMin < binMid) {\n if (getBitapScore(d, loc + binMid) <= scoreThreshold) {\n binMin = binMid;\n } else {\n binMax = binMid;\n }\n binMid = Math.floor((binMax - binMin) / 2 + binMin);\n }\n binMax = binMid;\n let start = Math.max(1, loc - binMid + 1);\n const finish = Math.min(loc + binMid, text.length) + pattern.length;\n const rd = new Array(finish + 2);\n rd[finish + 1] = (1 << d) - 1;\n for (let j = finish; j >= start; j--) {\n const charMatch = s[text.charAt(j - 1)];\n if (d === 0) {\n rd[j] = (rd[j + 1] << 1 | 1) & charMatch;\n } else {\n rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((lastRd[j + 1] | lastRd[j]) << 1 | 1) | lastRd[j + 1];\n }\n if (rd[j] & matchmask) {\n const score = getBitapScore(d, j - 1);\n if (score <= scoreThreshold) {\n scoreThreshold = score;\n bestLoc = j - 1;\n if (bestLoc > loc) {\n start = Math.max(1, 2 * loc - bestLoc);\n } else {\n break;\n }\n }\n }\n }\n if (getBitapScore(d + 1, loc) > scoreThreshold) {\n break;\n }\n lastRd = rd;\n }\n return bestLoc;\n}\nfunction getAlphabetFromPattern(pattern) {\n const s = {};\n for (let i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] = 0;\n }\n for (let i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] |= 1 << pattern.length - i - 1;\n }\n return s;\n}\nfunction match(text, pattern, searchLocation) {\n if (text === null || pattern === null || searchLocation === null) {\n throw new Error(\"Null input. (match())\");\n }\n const loc = Math.max(0, Math.min(searchLocation, text.length));\n if (text === pattern) {\n return 0;\n } else if (!text.length) {\n return -1;\n } else if (text.substring(loc, loc + pattern.length) === pattern) {\n return loc;\n }\n return bitap(text, pattern, loc);\n}\nfunction createPatchObject(start1, start2) {\n return {\n diffs: [],\n start1,\n start2,\n utf8Start1: start1,\n utf8Start2: start2,\n length1: 0,\n length2: 0,\n utf8Length1: 0,\n utf8Length2: 0\n };\n}\nfunction diffText1(diffs) {\n const text = [];\n for (let x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) {\n text[x] = diffs[x][1];\n }\n }\n return text.join(\"\");\n}\nfunction diffText2(diffs) {\n const text = [];\n for (let x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_DELETE) {\n text[x] = diffs[x][1];\n }\n }\n return text.join(\"\");\n}\nfunction countUtf8Bytes(str) {\n let bytes = 0;\n for (let i = 0; i < str.length; i++) {\n const codePoint = str.codePointAt(i);\n if (typeof codePoint === \"undefined\") {\n throw new Error(\"Failed to get codepoint\");\n }\n bytes += utf8len(codePoint);\n }\n return bytes;\n}\nfunction adjustIndiciesToUcs2(patches, base) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n let byteOffset = 0;\n let idx = 0;\n function advanceTo(target) {\n for (; byteOffset < target;) {\n const codePoint = base.codePointAt(idx);\n if (typeof codePoint === \"undefined\") {\n return idx;\n }\n byteOffset += utf8len(codePoint);\n if (codePoint > 65535) {\n idx += 2;\n } else {\n idx += 1;\n }\n }\n if (!options.allowExceedingIndices && byteOffset !== target) {\n throw new Error(\"Failed to determine byte offset\");\n }\n return idx;\n }\n const adjusted = [];\n for (const patch of patches) {\n adjusted.push({\n diffs: patch.diffs.map(diff => cloneDiff(diff)),\n start1: advanceTo(patch.start1),\n start2: advanceTo(patch.start2),\n utf8Start1: patch.utf8Start1,\n utf8Start2: patch.utf8Start2,\n length1: patch.length1,\n length2: patch.length2,\n utf8Length1: patch.utf8Length1,\n utf8Length2: patch.utf8Length2\n });\n }\n return adjusted;\n}\nfunction utf8len(codePoint) {\n if (codePoint <= 127) return 1;\n if (codePoint <= 2047) return 2;\n if (codePoint <= 65535) return 3;\n return 4;\n}\nconst MAX_BITS = 32;\nconst DEFAULT_MARGIN = 4;\nconst DEFAULT_OPTS = {\n margin: 4\n};\nfunction getDefaultOpts() {\n let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return {\n ...DEFAULT_OPTS,\n ...opts\n };\n}\nfunction make(a, b, options) {\n if (typeof a === \"string\" && typeof b === \"string\") {\n let diffs = diff(a, b, {\n checkLines: true\n });\n if (diffs.length > 2) {\n diffs = cleanupSemantic(diffs);\n diffs = cleanupEfficiency(diffs);\n }\n return _make(a, diffs, getDefaultOpts(options));\n }\n if (a && Array.isArray(a) && typeof b === \"undefined\") {\n return _make(diffText1(a), a, getDefaultOpts(options));\n }\n if (typeof a === \"string\" && b && Array.isArray(b)) {\n return _make(a, b, getDefaultOpts(options));\n }\n throw new Error(\"Unknown call format to make()\");\n}\nfunction _make(textA, diffs, options) {\n if (diffs.length === 0) {\n return [];\n }\n const patches = [];\n let patch = createPatchObject(0, 0);\n let patchDiffLength = 0;\n let charCount1 = 0;\n let charCount2 = 0;\n let utf8Count1 = 0;\n let utf8Count2 = 0;\n let prepatchText = textA;\n let postpatchText = textA;\n for (let x = 0; x < diffs.length; x++) {\n const currentDiff = diffs[x];\n const [diffType, diffText] = currentDiff;\n const diffTextLength = diffText.length;\n const diffByteLength = countUtf8Bytes(diffText);\n if (!patchDiffLength && diffType !== DIFF_EQUAL) {\n patch.start1 = charCount1;\n patch.start2 = charCount2;\n patch.utf8Start1 = utf8Count1;\n patch.utf8Start2 = utf8Count2;\n }\n switch (diffType) {\n case DIFF_INSERT:\n patch.diffs[patchDiffLength++] = currentDiff;\n patch.length2 += diffTextLength;\n patch.utf8Length2 += diffByteLength;\n postpatchText = postpatchText.substring(0, charCount2) + diffText + postpatchText.substring(charCount2);\n break;\n case DIFF_DELETE:\n patch.length1 += diffTextLength;\n patch.utf8Length1 += diffByteLength;\n patch.diffs[patchDiffLength++] = currentDiff;\n postpatchText = postpatchText.substring(0, charCount2) + postpatchText.substring(charCount2 + diffTextLength);\n break;\n case DIFF_EQUAL:\n if (diffTextLength <= 2 * options.margin && patchDiffLength && diffs.length !== x + 1) {\n patch.diffs[patchDiffLength++] = currentDiff;\n patch.length1 += diffTextLength;\n patch.length2 += diffTextLength;\n patch.utf8Length1 += diffByteLength;\n patch.utf8Length2 += diffByteLength;\n } else if (diffTextLength >= 2 * options.margin) {\n if (patchDiffLength) {\n addContext(patch, prepatchText, options);\n patches.push(patch);\n patch = createPatchObject(-1, -1);\n patchDiffLength = 0;\n prepatchText = postpatchText;\n charCount1 = charCount2;\n utf8Count1 = utf8Count2;\n }\n }\n break;\n default:\n throw new Error(\"Unknown diff type\");\n }\n if (diffType !== DIFF_INSERT) {\n charCount1 += diffTextLength;\n utf8Count1 += diffByteLength;\n }\n if (diffType !== DIFF_DELETE) {\n charCount2 += diffTextLength;\n utf8Count2 += diffByteLength;\n }\n }\n if (patchDiffLength) {\n addContext(patch, prepatchText, options);\n patches.push(patch);\n }\n return patches;\n}\nfunction addContext(patch, text, opts) {\n if (text.length === 0) {\n return;\n }\n let pattern = text.substring(patch.start2, patch.start2 + patch.length1);\n let padding = 0;\n while (text.indexOf(pattern) !== text.lastIndexOf(pattern) && pattern.length < MAX_BITS - opts.margin - opts.margin) {\n padding += opts.margin;\n pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding);\n }\n padding += opts.margin;\n let prefixStart = patch.start2 - padding;\n if (prefixStart >= 1 && isLowSurrogate(text[prefixStart])) {\n prefixStart--;\n }\n const prefix = text.substring(prefixStart, patch.start2);\n if (prefix) {\n patch.diffs.unshift([DIFF_EQUAL, prefix]);\n }\n const prefixLength = prefix.length;\n const prefixUtf8Length = countUtf8Bytes(prefix);\n let suffixEnd = patch.start2 + patch.length1 + padding;\n if (suffixEnd < text.length && isLowSurrogate(text[suffixEnd])) {\n suffixEnd++;\n }\n const suffix = text.substring(patch.start2 + patch.length1, suffixEnd);\n if (suffix) {\n patch.diffs.push([DIFF_EQUAL, suffix]);\n }\n const suffixLength = suffix.length;\n const suffixUtf8Length = countUtf8Bytes(suffix);\n patch.start1 -= prefixLength;\n patch.start2 -= prefixLength;\n patch.utf8Start1 -= prefixUtf8Length;\n patch.utf8Start2 -= prefixUtf8Length;\n patch.length1 += prefixLength + suffixLength;\n patch.length2 += prefixLength + suffixLength;\n patch.utf8Length1 += prefixUtf8Length + suffixUtf8Length;\n patch.utf8Length2 += prefixUtf8Length + suffixUtf8Length;\n}\nfunction levenshtein(diffs) {\n let leven = 0;\n let insertions = 0;\n let deletions = 0;\n for (let x = 0; x < diffs.length; x++) {\n const op = diffs[x][0];\n const data = diffs[x][1];\n switch (op) {\n case DIFF_INSERT:\n insertions += data.length;\n break;\n case DIFF_DELETE:\n deletions += data.length;\n break;\n case DIFF_EQUAL:\n leven += Math.max(insertions, deletions);\n insertions = 0;\n deletions = 0;\n break;\n default:\n throw new Error(\"Unknown diff operation.\");\n }\n }\n leven += Math.max(insertions, deletions);\n return leven;\n}\nfunction xIndex(diffs, loc) {\n let chars1 = 0;\n let chars2 = 0;\n let lastChars1 = 0;\n let lastChars2 = 0;\n let x;\n for (x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) {\n chars1 += diffs[x][1].length;\n }\n if (diffs[x][0] !== DIFF_DELETE) {\n chars2 += diffs[x][1].length;\n }\n if (chars1 > loc) {\n break;\n }\n lastChars1 = chars1;\n lastChars2 = chars2;\n }\n if (diffs.length !== x && diffs[x][0] === DIFF_DELETE) {\n return lastChars2;\n }\n return lastChars2 + (loc - lastChars1);\n}\nfunction addPadding(patches) {\n let margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_MARGIN;\n const paddingLength = margin;\n let nullPadding = \"\";\n for (let x = 1; x <= paddingLength; x++) {\n nullPadding += String.fromCharCode(x);\n }\n for (const p of patches) {\n p.start1 += paddingLength;\n p.start2 += paddingLength;\n p.utf8Start1 += paddingLength;\n p.utf8Start2 += paddingLength;\n }\n let patch = patches[0];\n let diffs = patch.diffs;\n if (diffs.length === 0 || diffs[0][0] !== DIFF_EQUAL) {\n diffs.unshift([DIFF_EQUAL, nullPadding]);\n patch.start1 -= paddingLength;\n patch.start2 -= paddingLength;\n patch.utf8Start1 -= paddingLength;\n patch.utf8Start2 -= paddingLength;\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n patch.utf8Length1 += paddingLength;\n patch.utf8Length2 += paddingLength;\n } else if (paddingLength > diffs[0][1].length) {\n const firstDiffLength = diffs[0][1].length;\n const extraLength = paddingLength - firstDiffLength;\n diffs[0][1] = nullPadding.substring(firstDiffLength) + diffs[0][1];\n patch.start1 -= extraLength;\n patch.start2 -= extraLength;\n patch.utf8Start1 -= extraLength;\n patch.utf8Start2 -= extraLength;\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n patch.utf8Length1 += extraLength;\n patch.utf8Length2 += extraLength;\n }\n patch = patches[patches.length - 1];\n diffs = patch.diffs;\n if (diffs.length === 0 || diffs[diffs.length - 1][0] !== DIFF_EQUAL) {\n diffs.push([DIFF_EQUAL, nullPadding]);\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n patch.utf8Length1 += paddingLength;\n patch.utf8Length2 += paddingLength;\n } else if (paddingLength > diffs[diffs.length - 1][1].length) {\n const extraLength = paddingLength - diffs[diffs.length - 1][1].length;\n diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n patch.utf8Length1 += extraLength;\n patch.utf8Length2 += extraLength;\n }\n return nullPadding;\n}\nfunction splitMax(patches) {\n let margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_MARGIN;\n const patchSize = MAX_BITS;\n for (let x = 0; x < patches.length; x++) {\n if (patches[x].length1 <= patchSize) {\n continue;\n }\n const bigpatch = patches[x];\n patches.splice(x--, 1);\n let start1 = bigpatch.start1;\n let start2 = bigpatch.start2;\n let preContext = \"\";\n while (bigpatch.diffs.length !== 0) {\n const patch = createPatchObject(start1 - preContext.length, start2 - preContext.length);\n let empty = true;\n if (preContext !== \"\") {\n const precontextByteCount = countUtf8Bytes(preContext);\n patch.length1 = preContext.length;\n patch.utf8Length1 = precontextByteCount;\n patch.length2 = preContext.length;\n patch.utf8Length2 = precontextByteCount;\n patch.diffs.push([DIFF_EQUAL, preContext]);\n }\n while (bigpatch.diffs.length !== 0 && patch.length1 < patchSize - margin) {\n const diffType = bigpatch.diffs[0][0];\n let diffText = bigpatch.diffs[0][1];\n let diffTextByteCount = countUtf8Bytes(diffText);\n if (diffType === DIFF_INSERT) {\n patch.length2 += diffText.length;\n patch.utf8Length2 += diffTextByteCount;\n start2 += diffText.length;\n const diff = bigpatch.diffs.shift();\n if (diff) {\n patch.diffs.push(diff);\n }\n empty = false;\n } else if (diffType === DIFF_DELETE && patch.diffs.length === 1 && patch.diffs[0][0] === DIFF_EQUAL && diffText.length > 2 * patchSize) {\n patch.length1 += diffText.length;\n patch.utf8Length1 += diffTextByteCount;\n start1 += diffText.length;\n empty = false;\n patch.diffs.push([diffType, diffText]);\n bigpatch.diffs.shift();\n } else {\n diffText = diffText.substring(0, patchSize - patch.length1 - margin);\n diffTextByteCount = countUtf8Bytes(diffText);\n patch.length1 += diffText.length;\n patch.utf8Length1 += diffTextByteCount;\n start1 += diffText.length;\n if (diffType === DIFF_EQUAL) {\n patch.length2 += diffText.length;\n patch.utf8Length2 += diffTextByteCount;\n start2 += diffText.length;\n } else {\n empty = false;\n }\n patch.diffs.push([diffType, diffText]);\n if (diffText === bigpatch.diffs[0][1]) {\n bigpatch.diffs.shift();\n } else {\n bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diffText.length);\n }\n }\n }\n preContext = diffText2(patch.diffs);\n preContext = preContext.substring(preContext.length - margin);\n const postContext = diffText1(bigpatch.diffs).substring(0, margin);\n const postContextByteCount = countUtf8Bytes(postContext);\n if (postContext !== \"\") {\n patch.length1 += postContext.length;\n patch.length2 += postContext.length;\n patch.utf8Length1 += postContextByteCount;\n patch.utf8Length2 += postContextByteCount;\n if (patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {\n patch.diffs[patch.diffs.length - 1][1] += postContext;\n } else {\n patch.diffs.push([DIFF_EQUAL, postContext]);\n }\n }\n if (!empty) {\n patches.splice(++x, 0, patch);\n }\n }\n }\n}\nfunction apply(patches, originalText) {\n let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (typeof patches === \"string\") {\n throw new Error(\"Patches must be an array - pass the patch to `parsePatch()` first\");\n }\n let text = originalText;\n if (patches.length === 0) {\n return [text, []];\n }\n const parsed = adjustIndiciesToUcs2(patches, text, {\n allowExceedingIndices: opts.allowExceedingIndices\n });\n const margin = opts.margin || DEFAULT_MARGIN;\n const deleteThreshold = opts.deleteThreshold || 0.4;\n const nullPadding = addPadding(parsed, margin);\n text = nullPadding + text + nullPadding;\n splitMax(parsed, margin);\n let delta = 0;\n const results = [];\n for (let x = 0; x < parsed.length; x++) {\n const expectedLoc = parsed[x].start2 + delta;\n const text1 = diffText1(parsed[x].diffs);\n let startLoc;\n let endLoc = -1;\n if (text1.length > MAX_BITS) {\n startLoc = match(text, text1.substring(0, MAX_BITS), expectedLoc);\n if (startLoc !== -1) {\n endLoc = match(text, text1.substring(text1.length - MAX_BITS), expectedLoc + text1.length - MAX_BITS);\n if (endLoc === -1 || startLoc >= endLoc) {\n startLoc = -1;\n }\n }\n } else {\n startLoc = match(text, text1, expectedLoc);\n }\n if (startLoc === -1) {\n results[x] = false;\n delta -= parsed[x].length2 - parsed[x].length1;\n } else {\n results[x] = true;\n delta = startLoc - expectedLoc;\n let text2;\n if (endLoc === -1) {\n text2 = text.substring(startLoc, startLoc + text1.length);\n } else {\n text2 = text.substring(startLoc, endLoc + MAX_BITS);\n }\n if (text1 === text2) {\n text = text.substring(0, startLoc) + diffText2(parsed[x].diffs) + text.substring(startLoc + text1.length);\n } else {\n let diffs = diff(text1, text2, {\n checkLines: false\n });\n if (text1.length > MAX_BITS && levenshtein(diffs) / text1.length > deleteThreshold) {\n results[x] = false;\n } else {\n diffs = cleanupSemanticLossless(diffs);\n let index1 = 0;\n let index2 = 0;\n for (let y = 0; y < parsed[x].diffs.length; y++) {\n const mod = parsed[x].diffs[y];\n if (mod[0] !== DIFF_EQUAL) {\n index2 = xIndex(diffs, index1);\n }\n if (mod[0] === DIFF_INSERT) {\n text = text.substring(0, startLoc + index2) + mod[1] + text.substring(startLoc + index2);\n } else if (mod[0] === DIFF_DELETE) {\n text = text.substring(0, startLoc + index2) + text.substring(startLoc + xIndex(diffs, index1 + mod[1].length));\n }\n if (mod[0] !== DIFF_DELETE) {\n index1 += mod[1].length;\n }\n }\n }\n }\n }\n }\n text = text.substring(nullPadding.length, text.length - nullPadding.length);\n return [text, results];\n}\nfunction stringify(patches) {\n return patches.map(stringifyPatch).join(\"\");\n}\nfunction stringifyPatch(patch) {\n const {\n utf8Length1,\n utf8Length2,\n utf8Start1,\n utf8Start2,\n diffs\n } = patch;\n let coords1;\n if (utf8Length1 === 0) {\n coords1 = \"\".concat(utf8Start1, \",0\");\n } else if (utf8Length1 === 1) {\n coords1 = \"\".concat(utf8Start1 + 1);\n } else {\n coords1 = \"\".concat(utf8Start1 + 1, \",\").concat(utf8Length1);\n }\n let coords2;\n if (utf8Length2 === 0) {\n coords2 = \"\".concat(utf8Start2, \",0\");\n } else if (utf8Length2 === 1) {\n coords2 = \"\".concat(utf8Start2 + 1);\n } else {\n coords2 = \"\".concat(utf8Start2 + 1, \",\").concat(utf8Length2);\n }\n const text = [\"@@ -\".concat(coords1, \" +\").concat(coords2, \" @@\\n\")];\n let op;\n for (let x = 0; x < diffs.length; x++) {\n switch (diffs[x][0]) {\n case DIFF_INSERT:\n op = \"+\";\n break;\n case DIFF_DELETE:\n op = \"-\";\n break;\n case DIFF_EQUAL:\n op = \" \";\n break;\n default:\n throw new Error(\"Unknown patch operation.\");\n }\n text[x + 1] = \"\".concat(op + encodeURI(diffs[x][1]), \"\\n\");\n }\n return text.join(\"\").replace(/%20/g, \" \");\n}\nconst patchHeader = /^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$/;\nfunction parse(textline) {\n if (!textline) {\n return [];\n }\n const patches = [];\n const lines = textline.split(\"\\n\");\n let textPointer = 0;\n while (textPointer < lines.length) {\n const m = lines[textPointer].match(patchHeader);\n if (!m) {\n throw new Error(\"Invalid patch string: \".concat(lines[textPointer]));\n }\n const patch = createPatchObject(toInt(m[1]), toInt(m[3]));\n patches.push(patch);\n if (m[2] === \"\") {\n patch.start1--;\n patch.utf8Start1--;\n patch.length1 = 1;\n patch.utf8Length1 = 1;\n } else if (m[2] === \"0\") {\n patch.length1 = 0;\n patch.utf8Length1 = 0;\n } else {\n patch.start1--;\n patch.utf8Start1--;\n patch.utf8Length1 = toInt(m[2]);\n patch.length1 = patch.utf8Length1;\n }\n if (m[4] === \"\") {\n patch.start2--;\n patch.utf8Start2--;\n patch.length2 = 1;\n patch.utf8Length2 = 1;\n } else if (m[4] === \"0\") {\n patch.length2 = 0;\n patch.utf8Length2 = 0;\n } else {\n patch.start2--;\n patch.utf8Start2--;\n patch.utf8Length2 = toInt(m[4]);\n patch.length2 = patch.utf8Length2;\n }\n textPointer++;\n while (textPointer < lines.length) {\n const currentLine = lines[textPointer];\n const sign = currentLine.charAt(0);\n if (sign === \"@\") {\n break;\n }\n if (sign === \"\") {\n textPointer++;\n continue;\n }\n let line;\n try {\n line = decodeURI(currentLine.slice(1));\n } catch (ex) {\n throw new Error(\"Illegal escape in parse: \".concat(currentLine));\n }\n const utf8Diff = countUtf8Bytes(line) - line.length;\n if (sign === \"-\") {\n patch.diffs.push([DIFF_DELETE, line]);\n patch.length1 -= utf8Diff;\n } else if (sign === \"+\") {\n patch.diffs.push([DIFF_INSERT, line]);\n patch.length2 -= utf8Diff;\n } else if (sign === \" \") {\n patch.diffs.push([DIFF_EQUAL, line]);\n patch.length1 -= utf8Diff;\n patch.length2 -= utf8Diff;\n } else {\n throw new Error(\"Invalid patch mode \\\"\".concat(sign, \"\\\" in: \").concat(line));\n }\n textPointer++;\n }\n }\n return patches;\n}\nfunction toInt(num) {\n return parseInt(num, 10);\n}\nexport { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, adjustIndiciesToUcs2, apply as applyPatches, cleanupEfficiency, cleanupSemantic, diff as makeDiff, make as makePatches, match, parse as parsePatch, stringifyPatch, stringify as stringifyPatches };\n//# sourceMappingURL=index.js.map\n","import type {Editor} from 'slate'\n\nconst IS_UDOING: WeakMap<Editor, boolean | undefined> = new WeakMap()\nconst IS_REDOING: WeakMap<Editor, boolean | undefined> = new WeakMap()\n\nexport function withUndoing(editor: Editor, fn: () => void) {\n const prev = isUndoing(editor)\n IS_UDOING.set(editor, true)\n fn()\n IS_UDOING.set(editor, prev)\n}\n\nexport function isUndoing(editor: Editor) {\n return IS_UDOING.get(editor) ?? false\n}\n\nexport function setIsUndoing(editor: Editor, isUndoing: boolean) {\n IS_UDOING.set(editor, isUndoing)\n}\n\nexport function withRedoing(editor: Editor, fn: () => void) {\n const prev = isRedoing(editor)\n IS_REDOING.set(editor, true)\n fn()\n IS_REDOING.set(editor, prev)\n}\n\nexport function isRedoing(editor: Editor) {\n return IS_REDOING.get(editor) ?? false\n}\n\nexport function setIsRedoing(editor: Editor, isRedoing: boolean) {\n IS_REDOING.set(editor, isRedoing)\n}\n","/**\n * This plugin will make the editor support undo/redo on the local state only.\n * The undo/redo steps are rebased against incoming patches since the step occurred.\n */\n\nimport type {Patch} from '@portabletext/patches'\nimport {\n DIFF_DELETE,\n DIFF_EQUAL,\n DIFF_INSERT,\n parsePatch,\n} from '@sanity/diff-match-patch'\nimport type {ObjectSchemaType, PortableTextBlock} from '@sanity/types'\nimport {flatten, isEqual} from 'lodash'\nimport {\n Editor,\n Operation,\n Path,\n Transforms,\n type Descendant,\n type SelectionOperation,\n} from 'slate'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue} from '../../utils/values'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {\n isRedoing,\n isUndoing,\n setIsRedoing,\n setIsUndoing,\n withRedoing,\n withUndoing,\n} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withUndoRedo')\nconst debugVerbose = debug.enabled && false\n\nconst SAVING = new WeakMap<Editor, boolean | undefined>()\nconst REMOTE_PATCHES = new WeakMap<\n Editor,\n {\n patch: Patch\n time: Date\n snapshot: PortableTextBlock[] | undefined\n previousSnapshot: PortableTextBlock[] | undefined\n }[]\n>()\nconst UNDO_STEP_LIMIT = 1000\n\nconst isSaving = (editor: Editor): boolean | undefined => {\n const state = SAVING.get(editor)\n return state === undefined ? true : state\n}\n\nexport interface Options {\n editorActor: EditorActor\n blockSchemaType: ObjectSchemaType\n subscriptions: Array<() => () => void>\n}\n\nconst getRemotePatches = (editor: Editor) => {\n if (!REMOTE_PATCHES.get(editor)) {\n REMOTE_PATCHES.set(editor, [])\n }\n return REMOTE_PATCHES.get(editor) || []\n}\n\nexport function createWithUndoRedo(\n options: Options,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n const {editorActor, blockSchemaType} = options\n\n return (editor: PortableTextSlateEditor) => {\n let previousSnapshot: PortableTextBlock[] | undefined = fromSlateValue(\n editor.children,\n blockSchemaType.name,\n )\n const remotePatches = getRemotePatches(editor)\n\n options.subscriptions.push(() => {\n debug('Subscribing to patches')\n const sub = editorActor.on('patches', ({patches, snapshot}) => {\n let reset = false\n patches.forEach((patch) => {\n if (!reset && patch.origin !== 'local' && remotePatches) {\n if (patch.type === 'unset' && patch.path.length === 0) {\n debug(\n 'Someone else cleared the content, resetting undo/redo history',\n )\n editor.history = {undos: [], redos: []}\n remotePatches.splice(0, remotePatches.length)\n SAVING.set(editor, true)\n reset = true\n return\n }\n remotePatches.push({\n patch,\n time: new Date(),\n snapshot,\n previousSnapshot,\n })\n }\n })\n previousSnapshot = snapshot\n })\n return () => {\n debug('Unsubscribing to patches')\n sub.unsubscribe()\n }\n })\n\n editor.history = {undos: [], redos: []}\n const {apply} = editor\n editor.apply = (op: Operation) => {\n if (editorActor.getSnapshot().context.readOnly) {\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(op)\n return\n }\n\n const {operations, history} = editor\n const {undos} = history\n const step = undos[undos.length - 1]\n const lastOp =\n step && step.operations && step.operations[step.operations.length - 1]\n const overwrite = shouldOverwrite(op, lastOp)\n const save = isSaving(editor)\n\n let merge = true\n if (save) {\n if (!step) {\n merge = false\n } else if (operations.length === 0) {\n merge = shouldMerge(op, lastOp) || overwrite\n }\n\n if (step && merge) {\n step.operations.push(op)\n } else {\n const newStep = {\n operations: [\n ...(editor.selection === null\n ? []\n : [createSelectOperation(editor)]),\n op,\n ],\n timestamp: new Date(),\n }\n undos.push(newStep)\n debug('Created new undo step', step)\n }\n\n while (undos.length > UNDO_STEP_LIMIT) {\n undos.shift()\n }\n\n if (shouldClear(op)) {\n history.redos = []\n }\n }\n apply(op)\n }\n\n editor.undo = () => {\n if (editorActor.getSnapshot().context.readOnly) {\n return\n }\n const {undos} = editor.history\n if (undos.length > 0) {\n const step = undos[undos.length - 1]\n debug('Undoing', step)\n if (step.operations.length > 0) {\n const otherPatches = remotePatches.filter(\n (item) => item.time >= step.timestamp,\n )\n let transformedOperations = step.operations\n otherPatches.forEach((item) => {\n transformedOperations = flatten(\n transformedOperations.map((op) =>\n transformOperation(\n editor,\n item.patch,\n op,\n item.snapshot,\n item.previousSnapshot,\n ),\n ),\n )\n })\n const reversedOperations = transformedOperations\n .map(Operation.inverse)\n .reverse()\n\n try {\n Editor.withoutNormalizing(editor, () => {\n withUndoing(editor, () => {\n withoutSaving(editor, () => {\n reversedOperations.forEach((op) => {\n editor.apply(op)\n })\n })\n })\n })\n editor.normalize()\n editor.onChange()\n } catch (err) {\n debug('Could not perform undo step', err)\n remotePatches.splice(0, remotePatches.length)\n Transforms.deselect(editor)\n editor.history = {undos: [], redos: []}\n SAVING.set(editor, true)\n setIsUndoing(editor, false)\n editor.onChange()\n return\n }\n editor.history.redos.push(step)\n editor.history.undos.pop()\n }\n }\n }\n\n editor.redo = () => {\n if (editorActor.getSnapshot().context.readOnly) {\n return\n }\n const {redos} = editor.history\n if (redos.length > 0) {\n const step = redos[redos.length - 1]\n debug('Redoing', step)\n if (step.operations.length > 0) {\n const otherPatches = remotePatches.filter(\n (item) => item.time >= step.timestamp,\n )\n let transformedOperations = step.operations\n otherPatches.forEach((item) => {\n transformedOperations = flatten(\n transformedOperations.map((op) =>\n transformOperation(\n editor,\n item.patch,\n op,\n item.snapshot,\n item.previousSnapshot,\n ),\n ),\n )\n })\n try {\n Editor.withoutNormalizing(editor, () => {\n withRedoing(editor, () => {\n withoutSaving(editor, () => {\n transformedOperations.forEach((op) => {\n editor.apply(op)\n })\n })\n })\n })\n editor.normalize()\n editor.onChange()\n } catch (err) {\n debug('Could not perform redo step', err)\n remotePatches.splice(0, remotePatches.length)\n Transforms.deselect(editor)\n editor.history = {undos: [], redos: []}\n SAVING.set(editor, true)\n setIsRedoing(editor, false)\n editor.onChange()\n return\n }\n editor.history.undos.push(step)\n editor.history.redos.pop()\n }\n }\n }\n\n // Plugin return\n return editor\n }\n}\n\n/**\n * This will adjust the operation paths and offsets according to the\n * remote patches by other editors since the step operations was performed.\n */\nfunction transformOperation(\n editor: PortableTextSlateEditor,\n patch: Patch,\n operation: Operation,\n snapshot: PortableTextBlock[] | undefined,\n previousSnapshot: PortableTextBlock[] | undefined,\n): Operation[] {\n if (debugVerbose) {\n debug(\n `Adjusting '${operation.type}' operation paths for '${patch.type}' patch`,\n )\n debug(`Operation ${JSON.stringify(operation)}`)\n debug(`Patch ${JSON.stringify(patch)}`)\n }\n\n const transformedOperation = {...operation}\n\n if (patch.type === 'insert' && patch.path.length === 1) {\n const insertBlockIndex = (snapshot || []).findIndex((blk) =>\n isEqual({_key: blk._key}, patch.path[0]),\n )\n debug(\n `Adjusting block path (+${patch.items.length}) for '${transformedOperation.type}' operation and patch '${patch.type}'`,\n )\n return [\n adjustBlockPath(\n transformedOperation,\n patch.items.length,\n insertBlockIndex,\n ),\n ]\n }\n\n if (patch.type === 'unset' && patch.path.length === 1) {\n const unsetBlockIndex = (previousSnapshot || []).findIndex((blk) =>\n isEqual({_key: blk._key}, patch.path[0]),\n )\n // If this operation is targeting the same block that got removed, return empty\n if (\n 'path' in transformedOperation &&\n Array.isArray(transformedOperation.path) &&\n transformedOperation.path[0] === unsetBlockIndex\n ) {\n debug('Skipping transformation that targeted removed block')\n return []\n }\n if (debugVerbose) {\n debug(`Selection ${JSON.stringify(editor.selection)}`)\n debug(\n `Adjusting block path (-1) for '${transformedOperation.type}' operation and patch '${patch.type}'`,\n )\n }\n return [adjustBlockPath(transformedOperation, -1, unsetBlockIndex)]\n }\n\n // Someone reset the whole value\n if (patch.type === 'unset' && patch.path.length === 0) {\n debug(\n `Adjusting selection for unset everything patch and ${operation.type} operation`,\n )\n return []\n }\n\n if (patch.type === 'diffMatchPatch') {\n const operationTargetBlock = findOperationTargetBlock(\n editor,\n transformedOperation,\n )\n if (\n !operationTargetBlock ||\n !isEqual({_key: operationTargetBlock._key}, patch.path[0])\n ) {\n return [transformedOperation]\n }\n const diffPatches = parsePatch(patch.value)\n diffPatches.forEach((diffPatch) => {\n let adjustOffsetBy = 0\n let changedOffset = diffPatch.utf8Start1\n const {diffs} = diffPatch\n diffs.forEach((diff, index) => {\n const [diffType, text] = diff\n if (diffType === DIFF_INSERT) {\n adjustOffsetBy += text.length\n changedOffset += text.length\n } else if (diffType === DIFF_DELETE) {\n adjustOffsetBy -= text.length\n changedOffset -= text.length\n } else if (diffType === DIFF_EQUAL) {\n // Only up to the point where there are no other changes\n if (!diffs.slice(index).every(([dType]) => dType === DIFF_EQUAL)) {\n changedOffset += text.length\n }\n }\n })\n // Adjust accordingly if someone inserted text in the same node before us\n if (transformedOperation.type === 'insert_text') {\n if (changedOffset < transformedOperation.offset) {\n transformedOperation.offset += adjustOffsetBy\n }\n }\n // Adjust accordingly if someone removed text in the same node before us\n if (transformedOperation.type === 'remove_text') {\n if (\n changedOffset <=\n transformedOperation.offset - transformedOperation.text.length\n ) {\n transformedOperation.offset += adjustOffsetBy\n }\n }\n // Adjust set_selection operation's points to new offset\n if (transformedOperation.type === 'set_selection') {\n const currentFocus = transformedOperation.properties?.focus\n ? {...transformedOperation.properties.focus}\n : undefined\n const currentAnchor = transformedOperation?.properties?.anchor\n ? {...transformedOperation.properties.anchor}\n : undefined\n const newFocus = transformedOperation?.newProperties?.focus\n ? {...transformedOperation.newProperties.focus}\n : undefined\n const newAnchor = transformedOperation?.newProperties?.anchor\n ? {...transformedOperation.newProperties.anchor}\n : undefined\n if ((currentFocus && currentAnchor) || (newFocus && newAnchor)) {\n const points = [currentFocus, currentAnchor, newFocus, newAnchor]\n points.forEach((point) => {\n if (point && changedOffset < point.offset) {\n point.offset += adjustOffsetBy\n }\n })\n if (currentFocus && currentAnchor) {\n transformedOperation.properties = {\n focus: currentFocus,\n anchor: currentAnchor,\n }\n }\n if (newFocus && newAnchor) {\n transformedOperation.newProperties = {\n focus: newFocus,\n anchor: newAnchor,\n }\n }\n }\n }\n })\n return [transformedOperation]\n }\n return [transformedOperation]\n}\n/**\n * Adjust the block path for a operation\n */\nfunction adjustBlockPath(\n operation: Operation,\n level: number,\n blockIndex: number,\n): Operation {\n const transformedOperation = {...operation}\n if (\n blockIndex >= 0 &&\n transformedOperation.type !== 'set_selection' &&\n Array.isArray(transformedOperation.path) &&\n transformedOperation.path[0] >= blockIndex + level &&\n transformedOperation.path[0] + level > -1\n ) {\n const newPath = [\n transformedOperation.path[0] + level,\n ...transformedOperation.path.slice(1),\n ]\n transformedOperation.path = newPath\n }\n if (transformedOperation.type === 'set_selection') {\n const currentFocus = transformedOperation.properties?.focus\n ? {...transformedOperation.properties.focus}\n : undefined\n const currentAnchor = transformedOperation?.properties?.anchor\n ? {...transformedOperation.properties.anchor}\n : undefined\n const newFocus = transformedOperation?.newProperties?.focus\n ? {...transformedOperation.newProperties.focus}\n : undefined\n const newAnchor = transformedOperation?.newProperties?.anchor\n ? {...transformedOperation.newProperties.anchor}\n : undefined\n if ((currentFocus && currentAnchor) || (newFocus && newAnchor)) {\n const points = [currentFocus, currentAnchor, newFocus, newAnchor]\n points.forEach((point) => {\n if (\n point &&\n point.path[0] >= blockIndex + level &&\n point.path[0] + level > -1\n ) {\n point.path = [point.path[0] + level, ...point.path.slice(1)]\n }\n })\n if (currentFocus && currentAnchor) {\n transformedOperation.properties = {\n focus: currentFocus,\n anchor: currentAnchor,\n }\n }\n if (newFocus && newAnchor) {\n transformedOperation.newProperties = {\n focus: newFocus,\n anchor: newAnchor,\n }\n }\n }\n }\n // // Assign fresh point objects (we don't want to mutate the original ones)\n return transformedOperation\n}\n\n// Helper functions for editor.apply above\n\nconst shouldMerge = (op: Operation, prev: Operation | undefined): boolean => {\n if (op.type === 'set_selection') {\n return true\n }\n\n // Text input\n if (\n prev &&\n op.type === 'insert_text' &&\n prev.type === 'insert_text' &&\n op.offset === prev.offset + prev.text.length &&\n Path.equals(op.path, prev.path) &&\n op.text !== ' ' // Tokenize between words\n ) {\n return true\n }\n\n // Text deletion\n if (\n prev &&\n op.type === 'remove_text' &&\n prev.type === 'remove_text' &&\n op.offset + op.text.length === prev.offset &&\n Path.equals(op.path, prev.path)\n ) {\n return true\n }\n\n // Don't merge\n return false\n}\n\nconst shouldOverwrite = (\n op: Operation,\n prev: Operation | undefined,\n): boolean => {\n if (prev && op.type === 'set_selection' && prev.type === 'set_selection') {\n return true\n }\n\n return false\n}\n\nconst shouldClear = (op: Operation): boolean => {\n if (op.type === 'set_selection') {\n return false\n }\n\n return true\n}\n\nexport function withoutSaving(editor: Editor, fn: () => void): void {\n const prev = isSaving(editor)\n SAVING.set(editor, false)\n fn()\n SAVING.set(editor, prev)\n}\n\nfunction createSelectOperation(editor: Editor): SelectionOperation {\n return {\n type: 'set_selection',\n properties: {...editor.selection},\n newProperties: {...editor.selection},\n }\n}\n\nfunction findOperationTargetBlock(\n editor: PortableTextSlateEditor,\n operation: Operation,\n): Descendant | undefined {\n let block: Descendant | undefined\n if (operation.type === 'set_selection' && editor.selection) {\n block = editor.children[editor.selection.focus.path[0]]\n } else if ('path' in operation) {\n block = editor.children[operation.path[0]]\n }\n return block\n}\n","import type {PortableTextBlock} from '@sanity/types'\nimport {debounce, isEqual} from 'lodash'\nimport {useCallback, useMemo, useRef} from 'react'\nimport {Editor, Text, Transforms, type Descendant, type Node} from 'slate'\nimport {useSlate} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {validateValue} from '../../utils/validateValue'\nimport {toSlateValue, VOID_CHILD_KEY} from '../../utils/values'\nimport {\n isChangingLocally,\n isChangingRemotely,\n withRemoteChanges,\n} from '../../utils/withChanges'\nimport {withoutPatching} from '../../utils/withoutPatching'\nimport type {EditorActor} from '../editor-machine'\nimport {withoutSaving} from '../plugins/createWithUndoRedo'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('hook:useSyncValue')\n\n/**\n * @internal\n */\nexport interface UseSyncValueProps {\n editorActor: EditorActor\n portableTextEditor: PortableTextEditor\n readOnly: boolean\n}\n\nconst CURRENT_VALUE = new WeakMap<\n PortableTextEditor,\n PortableTextBlock[] | undefined\n>()\n\n/**\n * Sync value with the editor state\n *\n * Normally nothing here should apply, and the editor and the real world are perfectly aligned.\n *\n * Inconsistencies could happen though, so we need to check the editor state when the value changes.\n *\n * For performance reasons, it makes sense to also do the content validation here, as we already\n * iterate over the value and can validate only the new content that is actually changed.\n *\n * @internal\n */\nexport function useSyncValue(\n props: UseSyncValueProps,\n): (\n value: PortableTextBlock[] | undefined,\n userCallbackFn?: () => void,\n) => void {\n const {editorActor, portableTextEditor, readOnly} = props\n const schemaTypes = editorActor.getSnapshot().context.schema\n const previousValue = useRef<PortableTextBlock[] | undefined>()\n const slateEditor = useSlate()\n const updateValueFunctionRef =\n useRef<(value: PortableTextBlock[] | undefined) => void>()\n\n const updateFromCurrentValue = useCallback(() => {\n const currentValue = CURRENT_VALUE.get(portableTextEditor)\n if (previousValue.current === currentValue) {\n debug('Value is the same object as previous, not need to sync')\n return\n }\n if (updateValueFunctionRef.current && currentValue) {\n debug('Updating the value debounced')\n updateValueFunctionRef.current(currentValue)\n }\n }, [portableTextEditor])\n const updateValueDebounced = useMemo(\n () =>\n debounce(updateFromCurrentValue, 1000, {trailing: true, leading: false}),\n [updateFromCurrentValue],\n )\n\n return useMemo(() => {\n const updateFunction = (value: PortableTextBlock[] | undefined) => {\n CURRENT_VALUE.set(portableTextEditor, value)\n const isProcessingLocalChanges = isChangingLocally(slateEditor)\n const isProcessingRemoteChanges = isChangingRemotely(slateEditor)\n if (!readOnly) {\n if (isProcessingLocalChanges) {\n debug('Has local changes, not syncing value right now')\n updateValueDebounced()\n return\n }\n if (isProcessingRemoteChanges) {\n debug('Has remote changes, not syncing value right now')\n updateValueDebounced()\n return\n }\n }\n\n let isChanged = false\n let isValid = true\n\n const hadSelection = !!slateEditor.selection\n\n // If empty value, remove everything in the editor and insert a placeholder block\n if (!value || value.length === 0) {\n debug('Value is empty')\n Editor.withoutNormalizing(slateEditor, () => {\n withoutSaving(slateEditor, () => {\n withoutPatching(slateEditor, () => {\n if (hadSelection) {\n Transforms.deselect(slateEditor)\n }\n const childrenLength = slateEditor.children.length\n slateEditor.children.forEach((_, index) => {\n Transforms.removeNodes(slateEditor, {\n at: [childrenLength - 1 - index],\n })\n })\n Transforms.insertNodes(\n slateEditor,\n slateEditor.pteCreateTextBlock({decorators: []}),\n {at: [0]},\n )\n // Add a new selection in the top of the document\n if (hadSelection) {\n Transforms.select(slateEditor, [0, 0])\n }\n })\n })\n })\n isChanged = true\n }\n // Remove, replace or add nodes according to what is changed.\n if (value && value.length > 0) {\n const slateValueFromProps = toSlateValue(value, {\n schemaTypes,\n })\n Editor.withoutNormalizing(slateEditor, () => {\n withRemoteChanges(slateEditor, () => {\n withoutSaving(slateEditor, () => {\n withoutPatching(slateEditor, () => {\n const childrenLength = slateEditor.children.length\n // Remove blocks that have become superfluous\n if (slateValueFromProps.length < childrenLength) {\n for (\n let i = childrenLength - 1;\n i > slateValueFromProps.length - 1;\n i--\n ) {\n Transforms.removeNodes(slateEditor, {\n at: [i],\n })\n }\n isChanged = true\n }\n // Go through all of the blocks and see if they need to be updated\n slateValueFromProps.forEach(\n (currentBlock, currentBlockIndex) => {\n const oldBlock = slateEditor.children[currentBlockIndex]\n const hasChanges =\n oldBlock && !isEqual(currentBlock, oldBlock)\n if (hasChanges && isValid) {\n const validationValue = [value[currentBlockIndex]]\n const validation = validateValue(\n validationValue,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n // Resolve validations that can be resolved automatically, without involving the user (but only if the value was changed)\n if (\n !validation.valid &&\n validation.resolution?.autoResolve &&\n validation.resolution?.patches.length > 0\n ) {\n // Only apply auto resolution if the value has been populated before and is different from the last one.\n if (\n !readOnly &&\n previousValue.current &&\n previousValue.current !== value\n ) {\n // Give a console warning about the fact that it did an auto resolution\n console.warn(\n `${validation.resolution.action} for block with _key '${validationValue[0]._key}'. ${validation.resolution?.description}`,\n )\n validation.resolution.patches.forEach((patch) => {\n editorActor.send({type: 'patch', patch})\n })\n }\n }\n if (\n validation.valid ||\n validation.resolution?.autoResolve\n ) {\n if (oldBlock._key === currentBlock._key) {\n if (debug.enabled)\n debug('Updating block', oldBlock, currentBlock)\n _updateBlock(\n slateEditor,\n currentBlock,\n oldBlock,\n currentBlockIndex,\n )\n } else {\n if (debug.enabled)\n debug('Replacing block', oldBlock, currentBlock)\n _replaceBlock(\n slateEditor,\n currentBlock,\n currentBlockIndex,\n )\n }\n isChanged = true\n } else {\n editorActor.send({\n type: 'invalid value',\n resolution: validation.resolution,\n value,\n })\n isValid = false\n }\n }\n if (!oldBlock && isValid) {\n const validationValue = [value[currentBlockIndex]]\n const validation = validateValue(\n validationValue,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n if (debug.enabled)\n debug(\n 'Validating and inserting new block in the end of the value',\n currentBlock,\n )\n if (\n validation.valid ||\n validation.resolution?.autoResolve\n ) {\n Transforms.insertNodes(slateEditor, currentBlock, {\n at: [currentBlockIndex],\n })\n } else {\n debug('Invalid', validation)\n editorActor.send({\n type: 'invalid value',\n resolution: validation.resolution,\n value,\n })\n isValid = false\n }\n }\n },\n )\n })\n })\n })\n })\n }\n\n if (!isValid) {\n debug('Invalid value, returning')\n return\n }\n if (isChanged) {\n debug('Server value changed, syncing editor')\n try {\n slateEditor.onChange()\n } catch (err) {\n console.error(err)\n editorActor.send({\n type: 'invalid value',\n resolution: null,\n value,\n })\n return\n }\n if (hadSelection && !slateEditor.selection) {\n Transforms.select(slateEditor, {\n anchor: {path: [0, 0], offset: 0},\n focus: {path: [0, 0], offset: 0},\n })\n slateEditor.onChange()\n }\n editorActor.send({type: 'value changed', value})\n } else {\n debug('Server value and editor value is equal, no need to sync.')\n }\n previousValue.current = value\n }\n updateValueFunctionRef.current = updateFunction\n return updateFunction\n }, [\n editorActor,\n portableTextEditor,\n readOnly,\n schemaTypes,\n slateEditor,\n updateValueDebounced,\n ])\n}\n\n/**\n * This code is moved out of the above algorithm to keep complexity down.\n * @internal\n */\nfunction _replaceBlock(\n slateEditor: PortableTextSlateEditor,\n currentBlock: Descendant,\n currentBlockIndex: number,\n) {\n // While replacing the block and the current selection focus is on the replaced block,\n // temporarily deselect the editor then optimistically try to restore the selection afterwards.\n const currentSelection = slateEditor.selection\n const selectionFocusOnBlock =\n currentSelection && currentSelection.focus.path[0] === currentBlockIndex\n if (selectionFocusOnBlock) {\n Transforms.deselect(slateEditor)\n }\n Transforms.removeNodes(slateEditor, {at: [currentBlockIndex]})\n Transforms.insertNodes(slateEditor, currentBlock, {at: [currentBlockIndex]})\n slateEditor.onChange()\n if (selectionFocusOnBlock) {\n Transforms.select(slateEditor, currentSelection)\n }\n}\n\n/**\n * This code is moved out of the above algorithm to keep complexity down.\n * @internal\n */\nfunction _updateBlock(\n slateEditor: PortableTextSlateEditor,\n currentBlock: Descendant,\n oldBlock: Descendant,\n currentBlockIndex: number,\n) {\n // Update the root props on the block\n Transforms.setNodes(slateEditor, currentBlock as Partial<Node>, {\n at: [currentBlockIndex],\n })\n // Text block's need to have their children updated as well (setNode does not target a node's children)\n if (\n slateEditor.isTextBlock(currentBlock) &&\n slateEditor.isTextBlock(oldBlock)\n ) {\n const oldBlockChildrenLength = oldBlock.children.length\n if (currentBlock.children.length < oldBlockChildrenLength) {\n // Remove any children that have become superfluous\n Array.from(\n Array(oldBlockChildrenLength - currentBlock.children.length),\n ).forEach((_, index) => {\n const childIndex = oldBlockChildrenLength - 1 - index\n if (childIndex > 0) {\n debug('Removing child')\n Transforms.removeNodes(slateEditor, {\n at: [currentBlockIndex, childIndex],\n })\n }\n })\n }\n currentBlock.children.forEach(\n (currentBlockChild, currentBlockChildIndex) => {\n const oldBlockChild = oldBlock.children[currentBlockChildIndex]\n const isChildChanged = !isEqual(currentBlockChild, oldBlockChild)\n const isTextChanged = !isEqual(\n currentBlockChild.text,\n oldBlockChild?.text,\n )\n const path = [currentBlockIndex, currentBlockChildIndex]\n if (isChildChanged) {\n // Update if this is the same child\n if (currentBlockChild._key === oldBlockChild?._key) {\n debug('Updating changed child', currentBlockChild, oldBlockChild)\n Transforms.setNodes(\n slateEditor,\n currentBlockChild as Partial<Node>,\n {\n at: path,\n },\n )\n const isSpanNode =\n Text.isText(currentBlockChild) &&\n currentBlockChild._type === 'span' &&\n Text.isText(oldBlockChild) &&\n oldBlockChild._type === 'span'\n if (isSpanNode && isTextChanged) {\n Transforms.delete(slateEditor, {\n at: {\n focus: {path, offset: 0},\n anchor: {path, offset: oldBlockChild.text.length},\n },\n })\n Transforms.insertText(slateEditor, currentBlockChild.text, {\n at: path,\n })\n slateEditor.onChange()\n } else if (!isSpanNode) {\n // If it's a inline block, also update the void text node key\n debug('Updating changed inline object child', currentBlockChild)\n Transforms.setNodes(\n slateEditor,\n {_key: VOID_CHILD_KEY},\n {\n at: [...path, 0],\n voids: true,\n },\n )\n }\n // Replace the child if _key's are different\n } else if (oldBlockChild) {\n debug('Replacing child', currentBlockChild)\n Transforms.removeNodes(slateEditor, {\n at: [currentBlockIndex, currentBlockChildIndex],\n })\n Transforms.insertNodes(slateEditor, currentBlockChild as Node, {\n at: [currentBlockIndex, currentBlockChildIndex],\n })\n slateEditor.onChange()\n // Insert it if it didn't exist before\n } else if (!oldBlockChild) {\n debug('Inserting new child', currentBlockChild)\n Transforms.insertNodes(slateEditor, currentBlockChild as Node, {\n at: [currentBlockIndex, currentBlockChildIndex],\n })\n slateEditor.onChange()\n }\n }\n },\n )\n }\n}\n","import type {Patch} from '@portabletext/patches'\nimport type {PortableTextBlock} from '@sanity/types'\nimport {useSelector} from '@xstate/react'\nimport {throttle} from 'lodash'\nimport {useCallback, useEffect, useRef} from 'react'\nimport {Editor} from 'slate'\nimport {useSlate} from 'slate-react'\nimport {useEffectEvent} from 'use-effect-event'\nimport type {EditorChange} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {IS_PROCESSING_LOCAL_CHANGES} from '../../utils/weakMaps'\nimport type {EditorActor} from '../editor-machine'\nimport {usePortableTextEditor} from '../hooks/usePortableTextEditor'\nimport {useSyncValue} from '../hooks/useSyncValue'\n\nconst debug = debugWithName('component:PortableTextEditor:Synchronizer')\nconst debugVerbose = debug.enabled && false\n\n// The editor will commit changes in a throttled fashion in order\n// not to overload the network and degrade performance while typing.\nconst FLUSH_PATCHES_THROTTLED_MS = process.env.NODE_ENV === 'test' ? 500 : 1000\n\n/**\n * @internal\n */\nexport interface SynchronizerProps {\n editorActor: EditorActor\n getValue: () => Array<PortableTextBlock> | undefined\n onChange: (change: EditorChange) => void\n value: Array<PortableTextBlock> | undefined\n}\n\n/**\n * Synchronizes the server value with the editor, and provides various contexts for the editor state.\n * @internal\n */\nexport function Synchronizer(props: SynchronizerProps) {\n const portableTextEditor = usePortableTextEditor()\n const readOnly = useSelector(props.editorActor, (s) => s.context.readOnly)\n const {editorActor, getValue, onChange, value} = props\n const pendingPatches = useRef<Patch[]>([])\n\n const syncValue = useSyncValue({\n editorActor,\n portableTextEditor,\n readOnly,\n })\n\n const slateEditor = useSlate()\n\n useEffect(() => {\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, false)\n }, [slateEditor])\n\n const onFlushPendingPatches = useCallback(() => {\n if (pendingPatches.current.length > 0) {\n debug('Flushing pending patches')\n if (debugVerbose) {\n debug(`Patches:\\n${JSON.stringify(pendingPatches.current, null, 2)}`)\n }\n const snapshot = getValue()\n editorActor.send({\n type: 'mutation',\n patches: pendingPatches.current,\n snapshot,\n })\n pendingPatches.current = []\n }\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, false)\n }, [editorActor, slateEditor, getValue])\n\n // Flush pending patches immediately on unmount\n useEffect(() => {\n return () => {\n onFlushPendingPatches()\n }\n }, [onFlushPendingPatches])\n\n // We want to ensure that _when_ `props.onChange` is called, it uses the current value.\n // But we don't want to have the `useEffect` run setup + teardown + setup every time the prop might change, as that's unnecessary.\n // So we use our own polyfill that lets us use an upcoming React hook that solves this exact problem.\n // https://19.react.dev/learn/separating-events-from-effects#declaring-an-effect-event\n const handleChange = useEffectEvent((change: EditorChange) =>\n onChange(change),\n )\n\n // Subscribe to, and handle changes from the editor\n useEffect(() => {\n const onFlushPendingPatchesThrottled = throttle(\n () => {\n // If the editor is normalizing (each operation) it means that it's not in the middle of a bigger transform,\n // and we can flush these changes immediately.\n if (Editor.isNormalizing(slateEditor)) {\n onFlushPendingPatches()\n return\n }\n // If it's in the middle of something, try again.\n onFlushPendingPatchesThrottled()\n },\n FLUSH_PATCHES_THROTTLED_MS,\n {\n leading: false,\n trailing: true,\n },\n )\n\n debug('Subscribing to editor changes')\n const sub = editorActor.on('*', (event) => {\n switch (event.type) {\n case 'patch':\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, true)\n pendingPatches.current.push(event.patch)\n onFlushPendingPatchesThrottled()\n handleChange(event)\n break\n case 'loading': {\n handleChange({type: 'loading', isLoading: true})\n break\n }\n case 'done loading': {\n handleChange({type: 'loading', isLoading: false})\n break\n }\n case 'focused': {\n handleChange({type: 'focus', event: event.event})\n break\n }\n case 'offline': {\n handleChange({type: 'connection', value: 'offline'})\n break\n }\n case 'online': {\n handleChange({type: 'connection', value: 'online'})\n break\n }\n case 'value changed': {\n handleChange({type: 'value', value: event.value})\n break\n }\n case 'invalid value': {\n handleChange({\n type: 'invalidValue',\n resolution: event.resolution,\n value: event.value,\n })\n break\n }\n case 'error': {\n handleChange({\n ...event,\n level: 'warning',\n })\n break\n }\n case 'annotation.add':\n case 'annotation.remove':\n case 'annotation.toggle':\n case 'focus':\n case 'patches':\n break\n default:\n handleChange(event)\n }\n })\n return () => {\n debug('Unsubscribing to changes')\n sub.unsubscribe()\n }\n }, [editorActor, handleChange, onFlushPendingPatches, slateEditor])\n\n // Sync the value when going online\n const handleOnline = useCallback(() => {\n debug('Editor is online, syncing from props.value')\n syncValue(value)\n }, [syncValue, value])\n\n // Notify about window online and offline status changes\n useEffect(() => {\n const subscription = editorActor.on('online', handleOnline)\n\n return () => {\n subscription.unsubscribe()\n }\n }, [handleOnline, editorActor])\n\n // This hook must be set up after setting up the subscription above, or it will not pick up validation errors from the useSyncValue hook.\n // This will cause the editor to not be able to signal a validation error and offer invalid value resolution of the initial value.\n const isInitialValueFromProps = useRef(true)\n useEffect(() => {\n debug('Value from props changed, syncing new value')\n syncValue(value)\n // Signal that we have our first value, and are ready to roll.\n if (isInitialValueFromProps.current) {\n editorActor.send({type: 'ready'})\n isInitialValueFromProps.current = false\n }\n }, [editorActor, syncValue, value])\n\n return null\n}\n\nSynchronizer.displayName = 'Synchronizer'\n","import {\n diffMatchPatch,\n insert,\n set,\n setIfMissing,\n unset,\n type InsertPosition,\n type Patch,\n} from '@portabletext/patches'\nimport type {Path, PortableTextSpan, PortableTextTextBlock} from '@sanity/types'\nimport {get, isUndefined, omitBy} from 'lodash'\nimport {\n Text,\n type Descendant,\n type InsertNodeOperation,\n type InsertTextOperation,\n type MergeNodeOperation,\n type MoveNodeOperation,\n type RemoveNodeOperation,\n type RemoveTextOperation,\n type SetNodeOperation,\n type SplitNodeOperation,\n} from 'slate'\nimport type {PatchFunctions} from '../editor/plugins/createWithPatches'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../types/editor'\nimport {debugWithName} from './debug'\nimport {fromSlateValue} from './values'\n\nconst debug = debugWithName('operationToPatches')\n\nexport function createOperationToPatches(\n types: PortableTextMemberSchemaTypes,\n): PatchFunctions {\n const textBlockName = types.block.name\n function insertTextPatch(\n editor: PortableTextSlateEditor,\n operation: InsertTextOperation,\n beforeValue: Descendant[],\n ) {\n if (debug.enabled) {\n debug('Operation', JSON.stringify(operation, null, 2))\n }\n const block =\n editor.isTextBlock(editor.children[operation.path[0]]) &&\n editor.children[operation.path[0]]\n if (!block) {\n throw new Error('Could not find block')\n }\n const textChild =\n editor.isTextBlock(block) &&\n editor.isTextSpan(block.children[operation.path[1]]) &&\n (block.children[operation.path[1]] as PortableTextSpan)\n if (!textChild) {\n throw new Error('Could not find child')\n }\n const path: Path = [\n {_key: block._key},\n 'children',\n {_key: textChild._key},\n 'text',\n ]\n const prevBlock = beforeValue[operation.path[0]]\n const prevChild =\n editor.isTextBlock(prevBlock) && prevBlock.children[operation.path[1]]\n const prevText = editor.isTextSpan(prevChild) ? prevChild.text : ''\n const patch = diffMatchPatch(prevText, textChild.text, path)\n return patch.value.length ? [patch] : []\n }\n\n function removeTextPatch(\n editor: PortableTextSlateEditor,\n operation: RemoveTextOperation,\n beforeValue: Descendant[],\n ) {\n const block = editor && editor.children[operation.path[0]]\n if (!block) {\n throw new Error('Could not find block')\n }\n const child =\n (editor.isTextBlock(block) && block.children[operation.path[1]]) ||\n undefined\n const textChild: PortableTextSpan | undefined = editor.isTextSpan(child)\n ? child\n : undefined\n if (child && !textChild) {\n throw new Error('Expected span')\n }\n if (!textChild) {\n throw new Error('Could not find child')\n }\n const path: Path = [\n {_key: block._key},\n 'children',\n {_key: textChild._key},\n 'text',\n ]\n const beforeBlock = beforeValue[operation.path[0]]\n const prevTextChild =\n editor.isTextBlock(beforeBlock) && beforeBlock.children[operation.path[1]]\n const prevText = editor.isTextSpan(prevTextChild) && prevTextChild.text\n const patch = diffMatchPatch(prevText || '', textChild.text, path)\n return patch.value ? [patch] : []\n }\n\n function setNodePatch(\n editor: PortableTextSlateEditor,\n operation: SetNodeOperation,\n ) {\n if (operation.path.length === 1) {\n const block = editor.children[operation.path[0]]\n if (typeof block._key !== 'string') {\n throw new Error('Expected block to have a _key')\n }\n const setNode = omitBy(\n {...editor.children[operation.path[0]], ...operation.newProperties},\n isUndefined,\n ) as unknown as Descendant\n return [\n set(fromSlateValue([setNode], textBlockName)[0], [{_key: block._key}]),\n ]\n } else if (operation.path.length === 2) {\n const block = editor.children[operation.path[0]]\n if (editor.isTextBlock(block)) {\n const child = block.children[operation.path[1]]\n if (child) {\n const blockKey = block._key\n const childKey = child._key\n const patches: Patch[] = []\n const keys = Object.keys(operation.newProperties)\n keys.forEach((keyName) => {\n // Special case for setting _key on a child. We have to target it by index and not the _key.\n if (keys.length === 1 && keyName === '_key') {\n const val = get(operation.newProperties, keyName)\n patches.push(\n set(val, [\n {_key: blockKey},\n 'children',\n block.children.indexOf(child),\n keyName,\n ]),\n )\n } else {\n const val = get(operation.newProperties, keyName)\n patches.push(\n set(val, [\n {_key: blockKey},\n 'children',\n {_key: childKey},\n keyName,\n ]),\n )\n }\n })\n return patches\n }\n throw new Error('Could not find a valid child')\n }\n throw new Error('Could not find a valid block')\n } else {\n throw new Error(\n `Unexpected path encountered: ${JSON.stringify(operation.path)}`,\n )\n }\n }\n\n function insertNodePatch(\n editor: PortableTextSlateEditor,\n operation: InsertNodeOperation,\n beforeValue: Descendant[],\n ): Patch[] {\n const block = beforeValue[operation.path[0]]\n const isTextBlock = editor.isTextBlock(block)\n if (operation.path.length === 1) {\n const position = operation.path[0] === 0 ? 'before' : 'after'\n const beforeBlock = beforeValue[operation.path[0] - 1]\n const targetKey =\n operation.path[0] === 0 ? block?._key : beforeBlock?._key\n if (targetKey) {\n return [\n insert(\n [fromSlateValue([operation.node as Descendant], textBlockName)[0]],\n position,\n [{_key: targetKey}],\n ),\n ]\n }\n return [\n setIfMissing(beforeValue, []),\n insert(\n [fromSlateValue([operation.node as Descendant], textBlockName)[0]],\n 'before',\n [operation.path[0]],\n ),\n ]\n } else if (\n isTextBlock &&\n operation.path.length === 2 &&\n editor.children[operation.path[0]]\n ) {\n const position =\n block.children.length === 0 || !block.children[operation.path[1] - 1]\n ? 'before'\n : 'after'\n const node = {...operation.node} as Descendant\n if (!node._type && Text.isText(node)) {\n node._type = 'span'\n node.marks = []\n }\n const blk = fromSlateValue(\n [\n {\n _key: 'bogus',\n _type: textBlockName,\n children: [node],\n },\n ],\n textBlockName,\n )[0] as PortableTextTextBlock\n const child = blk.children[0]\n return [\n insert([child], position, [\n {_key: block._key},\n 'children',\n block.children.length <= 1 || !block.children[operation.path[1] - 1]\n ? 0\n : {_key: block.children[operation.path[1] - 1]._key},\n ]),\n ]\n }\n debug(\n 'Something was inserted into a void block. Not producing editor patches.',\n )\n return []\n }\n\n function splitNodePatch(\n editor: PortableTextSlateEditor,\n operation: SplitNodeOperation,\n beforeValue: Descendant[],\n ) {\n const patches: Patch[] = []\n const splitBlock = editor.children[operation.path[0]]\n if (!editor.isTextBlock(splitBlock)) {\n throw new Error(\n `Block with path ${JSON.stringify(\n operation.path[0],\n )} is not a text block and can't be split`,\n )\n }\n if (operation.path.length === 1) {\n const oldBlock = beforeValue[operation.path[0]]\n if (editor.isTextBlock(oldBlock)) {\n const targetValue = fromSlateValue(\n [editor.children[operation.path[0] + 1]],\n textBlockName,\n )[0]\n if (targetValue) {\n patches.push(\n insert([targetValue], 'after', [{_key: splitBlock._key}]),\n )\n const spansToUnset = oldBlock.children.slice(operation.position)\n spansToUnset.forEach((span) => {\n const path = [{_key: oldBlock._key}, 'children', {_key: span._key}]\n patches.push(unset(path))\n })\n }\n }\n return patches\n }\n if (operation.path.length === 2) {\n const splitSpan = splitBlock.children[operation.path[1]]\n if (editor.isTextSpan(splitSpan)) {\n const targetSpans = (\n fromSlateValue(\n [\n {\n ...splitBlock,\n children: splitBlock.children.slice(\n operation.path[1] + 1,\n operation.path[1] + 2,\n ),\n } as Descendant,\n ],\n textBlockName,\n )[0] as PortableTextTextBlock\n ).children\n\n patches.push(\n insert(targetSpans, 'after', [\n {_key: splitBlock._key},\n 'children',\n {_key: splitSpan._key},\n ]),\n )\n patches.push(\n set(splitSpan.text, [\n {_key: splitBlock._key},\n 'children',\n {_key: splitSpan._key},\n 'text',\n ]),\n )\n }\n return patches\n }\n return patches\n }\n\n function removeNodePatch(\n editor: PortableTextSlateEditor,\n operation: RemoveNodeOperation,\n beforeValue: Descendant[],\n ) {\n const block = beforeValue[operation.path[0]]\n if (operation.path.length === 1) {\n // Remove a single block\n if (block && block._key) {\n return [unset([{_key: block._key}])]\n }\n throw new Error('Block not found')\n } else if (editor.isTextBlock(block) && operation.path.length === 2) {\n const spanToRemove = block.children[operation.path[1]]\n\n if (spanToRemove) {\n const spansMatchingKey = block.children.filter(\n (span) => span._key === operation.node._key,\n )\n\n if (spansMatchingKey.length > 1) {\n console.warn(\n `Multiple spans have \\`_key\\` ${operation.node._key}. It's ambiguous which one to remove.`,\n JSON.stringify(block, null, 2),\n )\n return []\n }\n\n return [\n unset([{_key: block._key}, 'children', {_key: spanToRemove._key}]),\n ]\n }\n debug('Span not found in editor trying to remove node')\n return []\n } else {\n debug('Not creating patch inside object block')\n return []\n }\n }\n\n function mergeNodePatch(\n editor: PortableTextSlateEditor,\n operation: MergeNodeOperation,\n beforeValue: Descendant[],\n ) {\n const patches: Patch[] = []\n\n const block = beforeValue[operation.path[0]]\n const updatedBlock = editor.children[operation.path[0]]\n\n if (operation.path.length === 1) {\n if (block?._key) {\n const newBlock = fromSlateValue(\n [editor.children[operation.path[0] - 1]],\n textBlockName,\n )[0]\n patches.push(set(newBlock, [{_key: newBlock._key}]))\n patches.push(unset([{_key: block._key}]))\n } else {\n throw new Error('Target key not found!')\n }\n } else if (\n editor.isTextBlock(block) &&\n editor.isTextBlock(updatedBlock) &&\n operation.path.length === 2\n ) {\n const updatedSpan =\n updatedBlock.children[operation.path[1] - 1] &&\n editor.isTextSpan(updatedBlock.children[operation.path[1] - 1])\n ? updatedBlock.children[operation.path[1] - 1]\n : undefined\n const removedSpan =\n block.children[operation.path[1]] &&\n editor.isTextSpan(block.children[operation.path[1]])\n ? block.children[operation.path[1]]\n : undefined\n\n if (updatedSpan) {\n const spansMatchingKey = block.children.filter(\n (span) => span._key === updatedSpan._key,\n )\n\n if (spansMatchingKey.length === 1) {\n patches.push(\n set(updatedSpan.text, [\n {_key: block._key},\n 'children',\n {_key: updatedSpan._key},\n 'text',\n ]),\n )\n } else {\n console.warn(\n `Multiple spans have \\`_key\\` ${updatedSpan._key}. It's ambiguous which one to update.`,\n JSON.stringify(block, null, 2),\n )\n }\n }\n\n if (removedSpan) {\n const spansMatchingKey = block.children.filter(\n (span) => span._key === removedSpan._key,\n )\n\n if (spansMatchingKey.length === 1) {\n patches.push(\n unset([{_key: block._key}, 'children', {_key: removedSpan._key}]),\n )\n } else {\n console.warn(\n `Multiple spans have \\`_key\\` ${removedSpan._key}. It's ambiguous which one to remove.`,\n JSON.stringify(block, null, 2),\n )\n }\n }\n } else {\n debug(\"Void nodes can't be merged, not creating any patches\")\n }\n return patches\n }\n\n function moveNodePatch(\n editor: PortableTextSlateEditor,\n operation: MoveNodeOperation,\n beforeValue: Descendant[],\n ) {\n const patches: Patch[] = []\n const block = beforeValue[operation.path[0]]\n const targetBlock = beforeValue[operation.newPath[0]]\n if (operation.path.length === 1) {\n const position: InsertPosition =\n operation.path[0] > operation.newPath[0] ? 'before' : 'after'\n patches.push(unset([{_key: block._key}]))\n patches.push(\n insert([fromSlateValue([block], textBlockName)[0]], position, [\n {_key: targetBlock._key},\n ]),\n )\n } else if (\n operation.path.length === 2 &&\n editor.isTextBlock(block) &&\n editor.isTextBlock(targetBlock)\n ) {\n const child = block.children[operation.path[1]]\n const targetChild = targetBlock.children[operation.newPath[1]]\n const position =\n operation.newPath[1] === targetBlock.children.length\n ? 'after'\n : 'before'\n const childToInsert = (\n fromSlateValue([block], textBlockName)[0] as PortableTextTextBlock\n ).children[operation.path[1]]\n patches.push(unset([{_key: block._key}, 'children', {_key: child._key}]))\n patches.push(\n insert([childToInsert], position, [\n {_key: targetBlock._key},\n 'children',\n {_key: targetChild._key},\n ]),\n )\n }\n return patches\n }\n\n return {\n insertNodePatch,\n insertTextPatch,\n mergeNodePatch,\n moveNodePatch,\n removeNodePatch,\n removeTextPatch,\n setNodePatch,\n splitNodePatch,\n }\n}\n","import type {Editor} from 'slate'\nimport type {EditorActor} from '../editor-machine'\n\nexport function createWithEventListeners(\n editorActor: EditorActor,\n subscriptions: Array<() => () => void>,\n) {\n return function withEventListeners(editor: Editor) {\n if (editorActor.getSnapshot().context.maxBlocks !== undefined) {\n return editor\n }\n\n subscriptions.push(() => {\n const subscription = editorActor.on('*', (event) => {\n switch (event.type) {\n case 'annotation.add': {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'annotation.add',\n annotation: event.annotation,\n },\n editor,\n })\n break\n }\n case 'annotation.remove': {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'annotation.remove',\n annotation: event.annotation,\n },\n editor,\n })\n break\n }\n case 'annotation.toggle': {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'annotation.toggle',\n annotation: event.annotation,\n },\n editor,\n })\n break\n }\n case 'focus': {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'focus',\n },\n editor,\n })\n break\n }\n }\n })\n\n return () => {\n subscription.unsubscribe()\n }\n })\n\n editor.addMark = (mark) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.add',\n decorator: mark,\n },\n editor,\n })\n return\n }\n\n editor.removeMark = (mark) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.remove',\n decorator: mark,\n },\n editor,\n })\n return\n }\n\n editor.deleteBackward = (unit) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'delete backward',\n unit,\n },\n editor,\n })\n return\n }\n\n editor.deleteForward = (unit) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'delete forward',\n unit,\n },\n editor,\n })\n return\n }\n\n editor.insertBreak = () => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'insert break',\n },\n editor,\n })\n return\n }\n\n editor.insertSoftBreak = () => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'insert soft break',\n },\n editor,\n })\n return\n }\n\n editor.insertText = (text, options) => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'insert text',\n text,\n options,\n },\n editor,\n })\n return\n }\n\n return editor\n }\n}\n","import type {PortableTextSlateEditor} from '../../types/editor'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\n/**\n * This plugin makes sure that the PTE maxBlocks prop is respected\n *\n */\nexport function createWithMaxBlocks(editorActor: EditorActor) {\n return function withMaxBlocks(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {apply} = editor\n editor.apply = (operation) => {\n if (editorActor.getSnapshot().context.readOnly) {\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(operation)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(operation)\n return\n }\n\n const rows = editorActor.getSnapshot().context.maxBlocks ?? -1\n if (rows > 0 && editor.children.length >= rows) {\n if (\n (operation.type === 'insert_node' ||\n operation.type === 'split_node') &&\n operation.path.length === 1\n ) {\n return\n }\n }\n apply(operation)\n }\n return editor\n }\n}\n","import {Editor, Element, Node, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\n/**\n * This plugin makes sure that every new node in the editor get a new _key prop when created\n *\n */\nexport function createWithObjectKeys(\n editorActor: EditorActor,\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n return function withKeys(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {apply, normalizeNode} = editor\n\n // The default behavior is to always generate a new key here.\n // For example, when undoing and redoing we want to retain the keys, but\n // when we create a new bold span by splitting a non-bold-span we want the produced node to get a new key.\n editor.apply = (operation) => {\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(operation)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(operation)\n return\n }\n\n if (operation.type === 'split_node') {\n apply({\n ...operation,\n properties: {\n ...operation.properties,\n _key: editorActor.getSnapshot().context.keyGenerator(),\n },\n })\n\n return\n }\n\n if (operation.type === 'insert_node') {\n if (!Editor.isEditor(operation.node)) {\n apply({\n ...operation,\n node: {\n ...operation.node,\n _key: editorActor.getSnapshot().context.keyGenerator(),\n },\n })\n\n return\n }\n }\n\n apply(operation)\n }\n\n editor.normalizeNode = (entry) => {\n const [node, path] = entry\n if (Element.isElement(node) && node._type === schemaTypes.block.name) {\n // Set key on block itself\n if (!node._key) {\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {_key: editorActor.getSnapshot().context.keyGenerator()},\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n // Set keys on it's children\n for (const [child, childPath] of Node.children(editor, path)) {\n if (!child._key) {\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {_key: editorActor.getSnapshot().context.keyGenerator()},\n {at: childPath},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n normalizeNode(entry)\n }\n\n return editor\n }\n}\n","import {\n applyAll,\n type DiffMatchPatch,\n type InsertPatch,\n type Patch,\n type SetPatch,\n type UnsetPatch,\n} from '@portabletext/patches'\nimport {\n cleanupEfficiency,\n DIFF_DELETE,\n DIFF_EQUAL,\n DIFF_INSERT,\n applyPatches as diffMatchPatchApplyPatches,\n makeDiff,\n parsePatch,\n} from '@sanity/diff-match-patch'\nimport type {\n KeyedSegment,\n Path,\n PathSegment,\n PortableTextBlock,\n PortableTextChild,\n} from '@sanity/types'\nimport {\n Element,\n Text,\n Transforms,\n type Descendant,\n type Node,\n type Path as SlatePath,\n} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../types/editor'\nimport {debugWithName} from './debug'\nimport {toSlateValue} from './values'\nimport {KEY_TO_SLATE_ELEMENT} from './weakMaps'\n\nconst debug = debugWithName('applyPatches')\nconst debugVerbose = debug.enabled && true\n\n/**\n * Creates a function that can apply a patch onto a PortableTextSlateEditor.\n */\nexport function createApplyPatch(\n schemaTypes: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor, patch: Patch) => boolean {\n return (editor: PortableTextSlateEditor, patch: Patch): boolean => {\n let changed = false\n\n // Save some CPU cycles by not stringifying unless enabled\n if (debugVerbose) {\n debug(\n '\\n\\nNEW PATCH =============================================================',\n )\n debug(JSON.stringify(patch, null, 2))\n }\n\n try {\n switch (patch.type) {\n case 'insert':\n changed = insertPatch(editor, patch, schemaTypes)\n break\n case 'unset':\n changed = unsetPatch(editor, patch)\n break\n case 'set':\n changed = setPatch(editor, patch)\n break\n case 'diffMatchPatch':\n changed = diffMatchPatch(editor, patch)\n break\n default:\n debug('Unhandled patch', patch.type)\n }\n } catch (err) {\n console.error(err)\n }\n\n return changed\n }\n}\n\n/**\n * Apply a remote diff match patch to the current PTE instance.\n * Note meant for external consumption, only exported for testing purposes.\n *\n * @param editor - Portable text slate editor instance\n * @param patch - The PTE diff match patch operation to apply\n * @returns true if the patch was applied, false otherwise\n * @internal\n */\nexport function diffMatchPatch(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection' | 'onChange'\n >,\n patch: DiffMatchPatch,\n): boolean {\n const {block, child, childPath} = findBlockAndChildFromPath(\n editor,\n patch.path,\n )\n if (!block) {\n debug('Block not found')\n return false\n }\n if (!child || !childPath) {\n debug('Child not found')\n return false\n }\n const isSpanTextDiffMatchPatch =\n block &&\n editor.isTextBlock(block) &&\n patch.path.length === 4 &&\n patch.path[1] === 'children' &&\n patch.path[3] === 'text'\n\n if (!isSpanTextDiffMatchPatch || !Text.isText(child)) {\n return false\n }\n\n const patches = parsePatch(patch.value)\n const [newValue] = diffMatchPatchApplyPatches(patches, child.text, {\n allowExceedingIndices: true,\n })\n const diff = cleanupEfficiency(makeDiff(child.text, newValue), 5)\n\n debugState(editor, 'before')\n let offset = 0\n for (const [op, text] of diff) {\n if (op === DIFF_INSERT) {\n editor.apply({type: 'insert_text', path: childPath, offset, text})\n offset += text.length\n } else if (op === DIFF_DELETE) {\n editor.apply({type: 'remove_text', path: childPath, offset: offset, text})\n } else if (op === DIFF_EQUAL) {\n offset += text.length\n }\n }\n debugState(editor, 'after')\n\n return true\n}\n\nfunction insertPatch(\n editor: PortableTextSlateEditor,\n patch: InsertPatch,\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n const {\n block: targetBlock,\n child: targetChild,\n blockPath: targetBlockPath,\n childPath: targetChildPath,\n } = findBlockAndChildFromPath(editor, patch.path)\n if (!targetBlock || !targetBlockPath) {\n debug('Block not found')\n return false\n }\n if (patch.path.length > 1 && patch.path[1] !== 'children') {\n debug('Ignoring patch targeting void value')\n return false\n }\n // Insert blocks\n if (patch.path.length === 1) {\n const {items, position} = patch\n const blocksToInsert = toSlateValue(\n items as PortableTextBlock[],\n {schemaTypes},\n KEY_TO_SLATE_ELEMENT.get(editor),\n ) as Descendant[]\n const targetBlockIndex = targetBlockPath[0]\n const normalizedIdx =\n position === 'after' ? targetBlockIndex + 1 : targetBlockIndex\n debug(`Inserting blocks at path [${normalizedIdx}]`)\n debugState(editor, 'before')\n Transforms.insertNodes(editor, blocksToInsert, {at: [normalizedIdx]})\n debugState(editor, 'after')\n return true\n }\n // Insert children\n const {items, position} = patch\n if (!targetChild || !targetChildPath) {\n debug('Child not found')\n return false\n }\n const childrenToInsert =\n targetBlock &&\n toSlateValue(\n [{...targetBlock, children: items as PortableTextChild[]}],\n {schemaTypes},\n KEY_TO_SLATE_ELEMENT.get(editor),\n )\n const targetChildIndex = targetChildPath[1]\n const normalizedIdx =\n position === 'after' ? targetChildIndex + 1 : targetChildIndex\n const childInsertPath = [targetChildPath[0], normalizedIdx]\n debug(`Inserting children at path ${childInsertPath}`)\n debugState(editor, 'before')\n if (childrenToInsert && Element.isElement(childrenToInsert[0])) {\n Transforms.insertNodes(editor, childrenToInsert[0].children, {\n at: childInsertPath,\n })\n }\n debugState(editor, 'after')\n return true\n}\n\nfunction setPatch(editor: PortableTextSlateEditor, patch: SetPatch) {\n let value = patch.value\n if (typeof patch.path[3] === 'string') {\n value = {}\n value[patch.path[3]] = patch.value\n }\n const {block, blockPath, child, childPath} = findBlockAndChildFromPath(\n editor,\n patch.path,\n )\n\n if (!block) {\n debug('Block not found')\n return false\n }\n const isTextBlock = editor.isTextBlock(block)\n\n // Ignore patches targeting nested void data, like 'markDefs'\n if (isTextBlock && patch.path.length > 1 && patch.path[1] !== 'children') {\n debug('Ignoring setting void value')\n return false\n }\n\n debugState(editor, 'before')\n\n // If this is targeting a text block child\n if (isTextBlock && child && childPath) {\n if (Text.isText(value) && Text.isText(child)) {\n const newText = child.text\n const oldText = value.text\n if (oldText !== newText) {\n debug('Setting text property')\n editor.apply({\n type: 'remove_text',\n path: childPath,\n offset: 0,\n text: newText,\n })\n editor.apply({\n type: 'insert_text',\n path: childPath,\n offset: 0,\n text: value.text,\n })\n // call OnChange here to emit the new selection\n // the user's selection might be interfering with\n editor.onChange()\n }\n } else {\n debug('Setting non-text property')\n editor.apply({\n type: 'set_node',\n path: childPath,\n properties: {},\n newProperties: value as Partial<Node>,\n })\n }\n return true\n } else if (Element.isElement(block) && patch.path.length === 1 && blockPath) {\n debug('Setting block property')\n const {children, ...nextRest} = value as unknown as PortableTextBlock\n const {children: prevChildren, ...prevRest} = block || {children: undefined}\n // Set any block properties\n editor.apply({\n type: 'set_node',\n path: blockPath,\n properties: {...prevRest},\n newProperties: nextRest,\n })\n // Replace the children in the block\n // Note that children must be explicitly inserted, and can't be set with set_node\n debug('Setting children')\n block.children.forEach((c, cIndex) => {\n editor.apply({\n type: 'remove_node',\n path: blockPath.concat(block.children.length - 1 - cIndex),\n node: c,\n })\n })\n if (Array.isArray(children)) {\n children.forEach((c, cIndex) => {\n editor.apply({\n type: 'insert_node',\n path: blockPath.concat(cIndex),\n node: c,\n })\n })\n }\n } else if (block && 'value' in block) {\n const newVal = applyAll([block.value], [patch])[0]\n Transforms.setNodes(editor, {...block, value: newVal}, {at: blockPath})\n return true\n }\n debugState(editor, 'after')\n return true\n}\n\nfunction unsetPatch(editor: PortableTextSlateEditor, patch: UnsetPatch) {\n // Value\n if (patch.path.length === 0) {\n debug('Removing everything')\n debugState(editor, 'before')\n const previousSelection = editor.selection\n Transforms.deselect(editor)\n editor.children.forEach((_child, i) => {\n Transforms.removeNodes(editor, {at: [i]})\n })\n Transforms.insertNodes(editor, editor.pteCreateTextBlock({decorators: []}))\n if (previousSelection) {\n Transforms.select(editor, {\n anchor: {path: [0, 0], offset: 0},\n focus: {path: [0, 0], offset: 0},\n })\n }\n // call OnChange here to emit the new selection\n editor.onChange()\n debugState(editor, 'after')\n return true\n }\n const {block, blockPath, child, childPath} = findBlockAndChildFromPath(\n editor,\n patch.path,\n )\n\n // Single blocks\n if (patch.path.length === 1) {\n if (!block || !blockPath) {\n debug('Block not found')\n return false\n }\n const blockIndex = blockPath[0]\n debug(`Removing block at path [${blockIndex}]`)\n debugState(editor, 'before')\n\n Transforms.removeNodes(editor, {at: [blockIndex]})\n debugState(editor, 'after')\n return true\n }\n\n // Unset on text block children\n if (\n editor.isTextBlock(block) &&\n patch.path[1] === 'children' &&\n patch.path.length === 3\n ) {\n if (!child || !childPath) {\n debug('Child not found')\n return false\n }\n debug(`Unsetting child at path ${JSON.stringify(childPath)}`)\n debugState(editor, 'before')\n if (debugVerbose) {\n debug(`Removing child at path ${JSON.stringify(childPath)}`)\n }\n Transforms.removeNodes(editor, {at: childPath})\n debugState(editor, 'after')\n return true\n }\n return false\n}\n\nfunction isKeyedSegment(segment: PathSegment): segment is KeyedSegment {\n return typeof segment === 'object' && '_key' in segment\n}\n\nfunction debugState(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection'\n >,\n stateName: string,\n) {\n if (!debugVerbose) {\n return\n }\n\n debug(`Children ${stateName}:`, JSON.stringify(editor.children, null, 2))\n debug(`Selection ${stateName}: `, JSON.stringify(editor.selection, null, 2))\n}\n\nfunction findBlockFromPath(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection' | 'onChange'\n >,\n path: Path,\n): {block?: Descendant; path?: SlatePath} {\n let blockIndex = -1\n const block = editor.children.find((node: Descendant, index: number) => {\n const isMatch = isKeyedSegment(path[0])\n ? node._key === path[0]._key\n : index === path[0]\n if (isMatch) {\n blockIndex = index\n }\n return isMatch\n })\n if (!block) {\n return {}\n }\n return {block, path: [blockIndex] as SlatePath}\n}\n\nfunction findBlockAndChildFromPath(\n editor: Pick<\n PortableTextSlateEditor,\n 'children' | 'isTextBlock' | 'apply' | 'selection' | 'onChange'\n >,\n path: Path,\n): {\n child?: Descendant\n childPath?: SlatePath\n block?: Descendant\n blockPath?: SlatePath\n} {\n const {block, path: blockPath} = findBlockFromPath(editor, path)\n if (!(Element.isElement(block) && path[1] === 'children')) {\n return {block, blockPath, child: undefined, childPath: undefined}\n }\n let childIndex = -1\n const child = block.children.find((node, index: number) => {\n const isMatch = isKeyedSegment(path[2])\n ? node._key === path[2]._key\n : index === path[2]\n if (isMatch) {\n childIndex = index\n }\n return isMatch\n })\n if (!child) {\n return {block, blockPath, child: undefined, childPath: undefined}\n }\n return {\n block,\n child,\n blockPath,\n childPath: blockPath?.concat(childIndex) as SlatePath,\n }\n}\n","import {insert, setIfMissing, unset, type Patch} from '@portabletext/patches'\nimport {\n Editor,\n type Descendant,\n type InsertNodeOperation,\n type InsertTextOperation,\n type MergeNodeOperation,\n type MoveNodeOperation,\n type Operation,\n type RemoveNodeOperation,\n type RemoveTextOperation,\n type SetNodeOperation,\n type SplitNodeOperation,\n} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {createApplyPatch} from '../../utils/applyPatch'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue, isEqualToEmptyEditor} from '../../utils/values'\nimport {\n IS_PROCESSING_REMOTE_CHANGES,\n KEY_TO_VALUE_ELEMENT,\n} from '../../utils/weakMaps'\nimport {withRemoteChanges} from '../../utils/withChanges'\nimport {\n isPatching,\n PATCHING,\n withoutPatching,\n} from '../../utils/withoutPatching'\nimport type {EditorActor} from '../editor-machine'\nimport {withoutSaving} from './createWithUndoRedo'\n\nconst debug = debugWithName('plugin:withPatches')\nconst debugVerbose = false\n\nexport interface PatchFunctions {\n insertNodePatch: (\n editor: PortableTextSlateEditor,\n operation: InsertNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n insertTextPatch: (\n editor: PortableTextSlateEditor,\n operation: InsertTextOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n mergeNodePatch: (\n editor: PortableTextSlateEditor,\n operation: MergeNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n moveNodePatch: (\n editor: PortableTextSlateEditor,\n operation: MoveNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n removeNodePatch: (\n editor: PortableTextSlateEditor,\n operation: RemoveNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n removeTextPatch: (\n editor: PortableTextSlateEditor,\n operation: RemoveTextOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n setNodePatch: (\n editor: PortableTextSlateEditor,\n operation: SetNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n splitNodePatch: (\n editor: PortableTextSlateEditor,\n operation: SplitNodeOperation,\n previousChildren: Descendant[],\n ) => Patch[]\n}\n\ninterface Options {\n editorActor: EditorActor\n patchFunctions: PatchFunctions\n schemaTypes: PortableTextMemberSchemaTypes\n subscriptions: Array<() => () => void>\n}\n\nexport function createWithPatches({\n editorActor,\n patchFunctions,\n schemaTypes,\n subscriptions,\n}: Options): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n // The previous editor children are needed to figure out the _key of deleted nodes\n // The editor.children would no longer contain that information if the node is already deleted.\n let previousChildren: Descendant[]\n\n const applyPatch = createApplyPatch(schemaTypes)\n\n return function withPatches(editor: PortableTextSlateEditor) {\n IS_PROCESSING_REMOTE_CHANGES.set(editor, false)\n PATCHING.set(editor, true)\n previousChildren = [...editor.children]\n\n const {apply} = editor\n let bufferedPatches: Patch[] = []\n\n const handleBufferedRemotePatches = () => {\n if (bufferedPatches.length === 0) {\n return\n }\n const patches = bufferedPatches\n bufferedPatches = []\n let changed = false\n withRemoteChanges(editor, () => {\n Editor.withoutNormalizing(editor, () => {\n withoutPatching(editor, () => {\n withoutSaving(editor, () => {\n patches.forEach((patch) => {\n if (debug.enabled)\n debug(`Handling remote patch ${JSON.stringify(patch)}`)\n changed = applyPatch(editor, patch)\n })\n })\n })\n })\n if (changed) {\n editor.normalize()\n editor.onChange()\n }\n })\n }\n\n const handlePatches = ({patches}: {patches: Patch[]}) => {\n const remotePatches = patches.filter((p) => p.origin !== 'local')\n if (remotePatches.length === 0) {\n return\n }\n bufferedPatches = bufferedPatches.concat(remotePatches)\n handleBufferedRemotePatches()\n }\n\n subscriptions.push(() => {\n debug('Subscribing to remote patches')\n const sub = editorActor.on('patches', handlePatches)\n return () => {\n debug('Unsubscribing to remote patches')\n sub.unsubscribe()\n }\n })\n\n editor.apply = (operation: Operation): void | Editor => {\n if (editorActor.getSnapshot().context.readOnly) {\n apply(operation)\n return editor\n }\n let patches: Patch[] = []\n\n // Update previous children here before we apply\n previousChildren = editor.children\n\n const editorWasEmpty = isEqualToEmptyEditor(previousChildren, schemaTypes)\n\n // Apply the operation\n apply(operation)\n\n const editorIsEmpty = isEqualToEmptyEditor(editor.children, schemaTypes)\n\n if (!isPatching(editor)) {\n if (debugVerbose && debug.enabled)\n debug(\n `Editor is not producing patch for operation ${operation.type}`,\n operation,\n )\n return editor\n }\n\n // If the editor was empty and now isn't, insert the placeholder into it.\n if (\n editorWasEmpty &&\n !editorIsEmpty &&\n operation.type !== 'set_selection'\n ) {\n patches.push(insert(previousChildren, 'before', [0]))\n }\n\n switch (operation.type) {\n case 'insert_text':\n patches = [\n ...patches,\n ...patchFunctions.insertTextPatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'remove_text':\n patches = [\n ...patches,\n ...patchFunctions.removeTextPatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'remove_node':\n patches = [\n ...patches,\n ...patchFunctions.removeNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'split_node':\n patches = [\n ...patches,\n ...patchFunctions.splitNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'insert_node':\n patches = [\n ...patches,\n ...patchFunctions.insertNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'set_node':\n patches = [\n ...patches,\n ...patchFunctions.setNodePatch(editor, operation, previousChildren),\n ]\n break\n case 'merge_node':\n patches = [\n ...patches,\n ...patchFunctions.mergeNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n case 'move_node':\n patches = [\n ...patches,\n ...patchFunctions.moveNodePatch(\n editor,\n operation,\n previousChildren,\n ),\n ]\n break\n default:\n // Do nothing\n }\n\n // Unset the value if a operation made the editor empty\n if (\n !editorWasEmpty &&\n editorIsEmpty &&\n ['merge_node', 'set_node', 'remove_text', 'remove_node'].includes(\n operation.type,\n )\n ) {\n patches = [...patches, unset([])]\n editorActor.send({\n type: 'unset',\n previousValue: fromSlateValue(\n previousChildren,\n schemaTypes.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n })\n }\n\n // Prepend patches with setIfMissing if going from empty editor to something involving a patch.\n if (editorWasEmpty && patches.length > 0) {\n patches = [setIfMissing([], []), ...patches]\n }\n\n // Emit all patches\n if (patches.length > 0) {\n patches.forEach((patch) => {\n editorActor.send({\n type: 'patch',\n patch: {...patch, origin: 'local'},\n })\n })\n }\n return editor\n }\n return editor\n }\n}\n","import {Editor, Path} from 'slate'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport {debugWithName} from '../../utils/debug'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPlaceholderBlock')\n\n/**\n * Keep a \"placeholder\" block present when the editor is empty\n *\n */\nexport function createWithPlaceholderBlock(\n editorActor: EditorActor,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n return function withPlaceholderBlock(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {apply} = editor\n\n editor.apply = (op) => {\n if (editorActor.getSnapshot().context.readOnly) {\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(op)\n return\n }\n\n if (op.type === 'remove_node') {\n const node = op.node as SlateTextBlock | VoidElement\n if (op.path[0] === 0 && Editor.isVoid(editor, node)) {\n // Check next path, if it exists, do nothing\n const nextPath = Path.next(op.path)\n // Is removing the first block which is a void (not a text block), add a new empty text block in it, if there is no other element in the next path\n if (!editor.children[nextPath[0]]) {\n debug('Adding placeholder block')\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n )\n }\n }\n }\n apply(op)\n }\n return editor\n }\n}\n","import {Editor, Path, Text as SlateText, Transforms, type Node} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextBlockStyle')\n\nexport function createWithPortableTextBlockStyle(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n const defaultStyle = types.styles[0].value\n return function withPortableTextBlockStyle(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n // Extend Slate's default normalization to reset split node to normal style\n // if there is no text at the right end of the split.\n const {normalizeNode} = editor\n\n editor.normalizeNode = (nodeEntry) => {\n const [, path] = nodeEntry\n\n for (const op of editor.operations) {\n if (\n op.type === 'split_node' &&\n op.path.length === 1 &&\n editor.isTextBlock(op.properties) &&\n op.properties.style !== defaultStyle &&\n op.path[0] === path[0] &&\n !Path.equals(path, op.path)\n ) {\n const [child] = Editor.node(editor, [op.path[0] + 1, 0])\n if (SlateText.isText(child) && child.text === '') {\n debug(`Normalizing split node to ${defaultStyle} style`, op)\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {style: defaultStyle},\n {at: [op.path[0] + 1], voids: false},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n normalizeNode(nodeEntry)\n }\n\n editor.pteHasBlockStyle = (style: string): boolean => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node) && node.style === style,\n }),\n ]\n if (selectedBlocks.length > 0) {\n return true\n }\n return false\n }\n\n editor.pteToggleBlockStyle = (blockStyle: string): void => {\n if (!editor.selection) {\n return\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n }),\n ]\n selectedBlocks.forEach(([node, path]) => {\n if (editor.isTextBlock(node) && node.style === blockStyle) {\n debug(`Unsetting block style '${blockStyle}'`)\n Transforms.setNodes(\n editor,\n {...node, style: defaultStyle} as Partial<Node>,\n {\n at: path,\n },\n )\n } else {\n if (blockStyle) {\n debug(`Setting style '${blockStyle}'`)\n } else {\n debug('Setting default style', defaultStyle)\n }\n Transforms.setNodes(\n editor,\n {\n ...node,\n style: blockStyle || defaultStyle,\n } as Partial<Node>,\n {at: path},\n )\n }\n })\n editor.onChange()\n }\n return editor\n }\n}\n","import {Editor, Element, Text, Transforms, type Node} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\n\nconst debug = debugWithName('plugin:withPortableTextLists')\nconst MAX_LIST_LEVEL = 10\n\nexport function createWithPortableTextLists(\n types: PortableTextMemberSchemaTypes,\n) {\n return function withPortableTextLists(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n editor.pteToggleListItem = (listItemStyle: string) => {\n const isActive = editor.pteHasListStyle(listItemStyle)\n if (isActive) {\n debug(`Remove list item '${listItemStyle}'`)\n editor.pteUnsetListItem(listItemStyle)\n } else {\n debug(`Add list item '${listItemStyle}'`)\n editor.pteSetListItem(listItemStyle)\n }\n }\n\n editor.pteUnsetListItem = (listItemStyle: string) => {\n if (!editor.selection) {\n return\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) =>\n Element.isElement(node) && node._type === types.block.name,\n }),\n ]\n selectedBlocks.forEach(([node, path]) => {\n if (editor.isListBlock(node)) {\n const {listItem, level, ...rest} = node\n const newNode = {\n ...rest,\n listItem: undefined,\n level: undefined,\n } as Partial<Node>\n debug(`Unsetting list '${listItemStyle}'`)\n Transforms.setNodes(editor, newNode, {at: path})\n }\n })\n }\n\n editor.pteSetListItem = (listItemStyle: string) => {\n if (!editor.selection) {\n return\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n }),\n ]\n selectedBlocks.forEach(([node, path]) => {\n debug(`Setting list '${listItemStyle}'`)\n Transforms.setNodes(\n editor,\n {\n ...node,\n level: 1,\n listItem: listItemStyle || (types.lists[0] && types.lists[0].value),\n } as Partial<Node>,\n {at: path},\n )\n })\n }\n\n editor.pteEndList = () => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) =>\n Element.isElement(node) &&\n editor.isListBlock(node) &&\n node.children.length === 1 &&\n Text.isText(node.children[0]) &&\n node.children[0].text === '',\n }),\n ]\n if (selectedBlocks.length === 0) {\n return false\n }\n selectedBlocks.forEach(([node, path]) => {\n if (Element.isElement(node)) {\n debug('Unset list')\n Transforms.setNodes(\n editor,\n {\n ...node,\n level: undefined,\n listItem: undefined,\n },\n {at: path},\n )\n }\n })\n return true // Note: we are exiting the plugin chain by not returning editor (or hotkey plugin 'enter' will fire)\n }\n\n editor.pteIncrementBlockLevels = (reverse?: boolean): boolean => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => !!editor.isListBlock(node),\n }),\n ]\n if (selectedBlocks.length === 0) {\n return false\n }\n selectedBlocks.forEach(([node, path]) => {\n if (editor.isListBlock(node)) {\n let level = node.level || 1\n if (reverse) {\n level--\n debug(\n 'Decrementing list level',\n Math.min(MAX_LIST_LEVEL, Math.max(1, level)),\n )\n } else {\n level++\n debug(\n 'Incrementing list level',\n Math.min(MAX_LIST_LEVEL, Math.max(1, level)),\n )\n }\n Transforms.setNodes(\n editor,\n {level: Math.min(MAX_LIST_LEVEL, Math.max(1, level))},\n {at: path},\n )\n }\n })\n return true\n }\n\n editor.pteHasListStyle = (listStyle: string): boolean => {\n if (!editor.selection) {\n return false\n }\n const selectedBlocks = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n }),\n ]\n\n if (selectedBlocks.length > 0) {\n return selectedBlocks.every(\n ([node]) => editor.isListBlock(node) && node.listItem === listStyle,\n )\n }\n return false\n }\n\n return editor\n }\n}\n","function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == typeof i ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != typeof i) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction isPortableTextSpan(node) {\n return node._type === \"span\" && \"text\" in node && typeof node.text == \"string\" && (typeof node.marks > \"u\" || Array.isArray(node.marks) && node.marks.every(mark => typeof mark == \"string\"));\n}\nfunction isPortableTextBlock(node) {\n return (\n // A block doesn't _have_ to be named 'block' - to differentiate between\n // allowed child types and marks, one might name them differently\n typeof node._type == \"string\" &&\n // Toolkit-types like nested spans are @-prefixed\n node._type[0] !== \"@\" && (\n // `markDefs` isn't _required_ per say, but if it's there, it needs to be an array\n !(\"markDefs\" in node) || !node.markDefs || Array.isArray(node.markDefs) &&\n // Every mark definition needs to have an `_key` to be mappable in child spans\n node.markDefs.every(def => typeof def._key == \"string\")) &&\n // `children` is required and needs to be an array\n \"children\" in node && Array.isArray(node.children) &&\n // All children are objects with `_type` (usually spans, but can contain other stuff)\n node.children.every(child => typeof child == \"object\" && \"_type\" in child)\n );\n}\nfunction isPortableTextListItemBlock(block) {\n return isPortableTextBlock(block) && \"listItem\" in block && typeof block.listItem == \"string\" && (typeof block.level > \"u\" || typeof block.level == \"number\");\n}\nfunction isPortableTextToolkitList(block) {\n return block._type === \"@list\";\n}\nfunction isPortableTextToolkitSpan(span) {\n return span._type === \"@span\";\n}\nfunction isPortableTextToolkitTextNode(node) {\n return node._type === \"@text\";\n}\nconst knownDecorators = [\"strong\", \"em\", \"code\", \"underline\", \"strike-through\"];\nfunction sortMarksByOccurences(span, index, blockChildren) {\n if (!isPortableTextSpan(span) || !span.marks) return [];\n if (!span.marks.length) return [];\n const marks = span.marks.slice(),\n occurences = {};\n return marks.forEach(mark => {\n occurences[mark] = 1;\n for (let siblingIndex = index + 1; siblingIndex < blockChildren.length; siblingIndex++) {\n const sibling = blockChildren[siblingIndex];\n if (sibling && isPortableTextSpan(sibling) && Array.isArray(sibling.marks) && sibling.marks.indexOf(mark) !== -1) occurences[mark]++;else break;\n }\n }), marks.sort((markA, markB) => sortMarks(occurences, markA, markB));\n}\nfunction sortMarks(occurences, markA, markB) {\n const aOccurences = occurences[markA],\n bOccurences = occurences[markB];\n if (aOccurences !== bOccurences) return bOccurences - aOccurences;\n const aKnownPos = knownDecorators.indexOf(markA),\n bKnownPos = knownDecorators.indexOf(markB);\n return aKnownPos !== bKnownPos ? aKnownPos - bKnownPos : markA.localeCompare(markB);\n}\nfunction buildMarksTree(block) {\n var _a;\n const {\n children,\n markDefs = []\n } = block;\n if (!children || !children.length) return [];\n const sortedMarks = children.map(sortMarksByOccurences),\n rootNode = {\n _type: \"@span\",\n children: [],\n markType: \"<unknown>\"\n };\n let nodeStack = [rootNode];\n for (let i = 0; i < children.length; i++) {\n const span = children[i];\n if (!span) continue;\n const marksNeeded = sortedMarks[i] || [];\n let pos = 1;\n if (nodeStack.length > 1) for (pos; pos < nodeStack.length; pos++) {\n const mark = ((_a = nodeStack[pos]) == null ? void 0 : _a.markKey) || \"\",\n index = marksNeeded.indexOf(mark);\n if (index === -1) break;\n marksNeeded.splice(index, 1);\n }\n nodeStack = nodeStack.slice(0, pos);\n let currentNode = nodeStack[nodeStack.length - 1];\n if (currentNode) {\n for (const markKey of marksNeeded) {\n const markDef = markDefs.find(def => def._key === markKey),\n markType = markDef ? markDef._type : markKey,\n node = {\n _type: \"@span\",\n _key: span._key,\n children: [],\n markDef,\n markType,\n markKey\n };\n currentNode.children.push(node), nodeStack.push(node), currentNode = node;\n }\n if (isPortableTextSpan(span)) {\n const lines = span.text.split(`\n`);\n for (let line = lines.length; line-- > 1;) lines.splice(line, 0, `\n`);\n currentNode.children = currentNode.children.concat(lines.map(text => ({\n _type: \"@text\",\n text\n })));\n } else currentNode.children = currentNode.children.concat(span);\n }\n }\n return rootNode.children;\n}\nfunction nestLists(blocks, mode) {\n const tree = [];\n let currentList;\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (block) {\n if (!isPortableTextListItemBlock(block)) {\n tree.push(block), currentList = void 0;\n continue;\n }\n if (!currentList) {\n currentList = listFromBlock(block, i, mode), tree.push(currentList);\n continue;\n }\n if (blockMatchesList(block, currentList)) {\n currentList.children.push(block);\n continue;\n }\n if ((block.level || 1) > currentList.level) {\n const newList = listFromBlock(block, i, mode);\n if (mode === \"html\") {\n const lastListItem = currentList.children[currentList.children.length - 1],\n newLastChild = _objectSpread(_objectSpread({}, lastListItem), {}, {\n children: [...lastListItem.children, newList]\n });\n currentList.children[currentList.children.length - 1] = newLastChild;\n } else currentList.children.push(newList);\n currentList = newList;\n continue;\n }\n if ((block.level || 1) < currentList.level) {\n const matchingBranch = tree[tree.length - 1],\n match = matchingBranch && findListMatching(matchingBranch, block);\n if (match) {\n currentList = match, currentList.children.push(block);\n continue;\n }\n currentList = listFromBlock(block, i, mode), tree.push(currentList);\n continue;\n }\n if (block.listItem !== currentList.listItem) {\n const matchingBranch = tree[tree.length - 1],\n match = matchingBranch && findListMatching(matchingBranch, {\n level: block.level || 1\n });\n if (match && match.listItem === block.listItem) {\n currentList = match, currentList.children.push(block);\n continue;\n } else {\n currentList = listFromBlock(block, i, mode), tree.push(currentList);\n continue;\n }\n }\n console.warn(\"Unknown state encountered for block\", block), tree.push(block);\n }\n }\n return tree;\n}\nfunction blockMatchesList(block, list) {\n return (block.level || 1) === list.level && block.listItem === list.listItem;\n}\nfunction listFromBlock(block, index, mode) {\n return {\n _type: \"@list\",\n _key: `${block._key || `${index}`}-parent`,\n mode,\n level: block.level || 1,\n listItem: block.listItem,\n children: [block]\n };\n}\nfunction findListMatching(rootNode, matching) {\n const level = matching.level || 1,\n style = matching.listItem || \"normal\",\n filterOnType = typeof matching.listItem == \"string\";\n if (isPortableTextToolkitList(rootNode) && (rootNode.level || 1) === level && filterOnType && (rootNode.listItem || \"normal\") === style) return rootNode;\n if (!(\"children\" in rootNode)) return;\n const node = rootNode.children[rootNode.children.length - 1];\n return node && !isPortableTextSpan(node) ? findListMatching(node, matching) : void 0;\n}\nfunction spanToPlainText(span) {\n let text = \"\";\n return span.children.forEach(current => {\n isPortableTextToolkitTextNode(current) ? text += current.text : isPortableTextToolkitSpan(current) && (text += spanToPlainText(current));\n }), text;\n}\nconst leadingSpace = /^\\s/,\n trailingSpace = /\\s$/;\nfunction toPlainText(block) {\n const blocks = Array.isArray(block) ? block : [block];\n let text = \"\";\n return blocks.forEach((current, index) => {\n if (!isPortableTextBlock(current)) return;\n let pad = !1;\n current.children.forEach(span => {\n isPortableTextSpan(span) ? (text += pad && text && !trailingSpace.test(text) && !leadingSpace.test(span.text) ? \" \" : \"\", text += span.text, pad = !1) : pad = !0;\n }), index !== blocks.length - 1 && (text += `\n\n`);\n }), text;\n}\nconst LIST_NEST_MODE_HTML = \"html\",\n LIST_NEST_MODE_DIRECT = \"direct\";\nexport { LIST_NEST_MODE_DIRECT, LIST_NEST_MODE_HTML, buildMarksTree, isPortableTextBlock, isPortableTextListItemBlock, isPortableTextSpan, isPortableTextToolkitList, isPortableTextToolkitSpan, isPortableTextToolkitTextNode, nestLists, sortMarksByOccurences, spanToPlainText, toPlainText };\n//# sourceMappingURL=index.js.map\n","import type {PortableTextSpan} from '@sanity/types'\nimport {Node, Path} from 'slate'\nimport type {PortableTextSlateEditor} from '../types/editor'\n\nexport function getPreviousSpan({\n editor,\n blockPath,\n spanPath,\n}: {\n editor: PortableTextSlateEditor\n blockPath: Path\n spanPath: Path\n}): PortableTextSpan | undefined {\n let previousSpan: PortableTextSpan | undefined\n\n for (const [child, childPath] of Node.children(editor, blockPath, {\n reverse: true,\n })) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (Path.isBefore(childPath, spanPath)) {\n previousSpan = child\n break\n }\n }\n\n return previousSpan\n}\n\nexport function getNextSpan({\n editor,\n blockPath,\n spanPath,\n}: {\n editor: PortableTextSlateEditor\n blockPath: Path\n spanPath: Path\n}): PortableTextSpan | undefined {\n let nextSpan: PortableTextSpan | undefined\n\n for (const [child, childPath] of Node.children(editor, blockPath)) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (Path.isAfter(childPath, spanPath)) {\n nextSpan = child\n break\n }\n }\n\n return nextSpan\n}\n","/**\n *\n * This plugin will change Slate's default marks model (every prop is a mark) with the Portable Text model (marks is an array of strings on prop .marks).\n *\n */\n\nimport {isPortableTextBlock, isPortableTextSpan} from '@portabletext/toolkit'\nimport type {PortableTextObject, PortableTextSpan} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {Editor, Element, Node, Path, Range, Text, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {getNextSpan, getPreviousSpan} from '../../utils/sibling-utils'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {BehaviourActionImplementation} from '../behavior/behavior.actions'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextMarkModel')\n\nexport function createWithPortableTextMarkModel(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n return function withPortableTextMarkModel(editor: PortableTextSlateEditor) {\n const {apply, normalizeNode} = editor\n const decorators = types.decorators.map((t) => t.value)\n\n // Extend Slate's default normalization. Merge spans with same set of .marks when doing merge_node operations, and clean up markDefs / marks\n editor.normalizeNode = (nodeEntry) => {\n const [node, path] = nodeEntry\n\n if (editor.isTextBlock(node)) {\n const children = Node.children(editor, path)\n\n for (const [child, childPath] of children) {\n const nextNode = node.children[childPath[1] + 1]\n\n if (\n editor.isTextSpan(child) &&\n editor.isTextSpan(nextNode) &&\n child.marks?.every((mark) => nextNode.marks?.includes(mark)) &&\n nextNode.marks?.every((mark) => child.marks?.includes(mark))\n ) {\n debug(\n 'Merging spans',\n JSON.stringify(child, null, 2),\n JSON.stringify(nextNode, null, 2),\n )\n editorActor.send({type: 'normalizing'})\n Transforms.mergeNodes(editor, {\n at: [childPath[0], childPath[1] + 1],\n voids: true,\n })\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n /**\n * Add missing .markDefs to block nodes\n */\n if (editor.isTextBlock(node) && !Array.isArray(node.markDefs)) {\n debug('Adding .markDefs to block node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {markDefs: []}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n /**\n * Add missing .marks to span nodes\n */\n if (editor.isTextSpan(node) && !Array.isArray(node.marks)) {\n debug('Adding .marks to span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {marks: []}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n /**\n * Remove annotations from empty spans\n */\n if (editor.isTextSpan(node)) {\n const blockPath = Path.parent(path)\n const [block] = Editor.node(editor, blockPath)\n const decorators = types.decorators.map((decorator) => decorator.value)\n const annotations = node.marks?.filter(\n (mark) => !decorators.includes(mark),\n )\n\n if (editor.isTextBlock(block)) {\n if (node.text === '' && annotations && annotations.length > 0) {\n debug('Removing annotations from empty span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {marks: node.marks?.filter((mark) => decorators.includes(mark))},\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n /**\n * Remove orphaned annotations from child spans of block nodes\n */\n if (editor.isTextBlock(node)) {\n const decorators = types.decorators.map((decorator) => decorator.value)\n\n for (const [child, childPath] of Node.children(editor, path)) {\n if (editor.isTextSpan(child)) {\n const marks = child.marks ?? []\n const orphanedAnnotations = marks.filter((mark) => {\n return (\n !decorators.includes(mark) &&\n !node.markDefs?.find((def) => def._key === mark)\n )\n })\n\n if (orphanedAnnotations.length > 0) {\n debug('Removing orphaned annotations from span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {\n marks: marks.filter(\n (mark) => !orphanedAnnotations.includes(mark),\n ),\n },\n {at: childPath},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n }\n\n /**\n * Remove orphaned annotations from span nodes\n */\n if (editor.isTextSpan(node)) {\n const blockPath = Path.parent(path)\n const [block] = Editor.node(editor, blockPath)\n\n if (editor.isTextBlock(block)) {\n const decorators = types.decorators.map(\n (decorator) => decorator.value,\n )\n const marks = node.marks ?? []\n const orphanedAnnotations = marks.filter((mark) => {\n return (\n !decorators.includes(mark) &&\n !block.markDefs?.find((def) => def._key === mark)\n )\n })\n\n if (orphanedAnnotations.length > 0) {\n debug('Removing orphaned annotations from span node')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {\n marks: marks.filter(\n (mark) => !orphanedAnnotations.includes(mark),\n ),\n },\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n }\n\n // Remove duplicate markDefs\n if (editor.isTextBlock(node)) {\n const markDefs = node.markDefs ?? []\n const markDefKeys = new Set<string>()\n const newMarkDefs: Array<PortableTextObject> = []\n\n for (const markDef of markDefs) {\n if (!markDefKeys.has(markDef._key)) {\n markDefKeys.add(markDef._key)\n newMarkDefs.push(markDef)\n }\n }\n\n if (markDefs.length !== newMarkDefs.length) {\n debug('Removing duplicate markDefs')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {markDefs: newMarkDefs}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n\n // Check consistency of markDefs (unless we are merging two nodes)\n if (\n editor.isTextBlock(node) &&\n !editor.operations.some(\n (op) =>\n op.type === 'merge_node' &&\n 'markDefs' in op.properties &&\n op.path.length === 1,\n )\n ) {\n const newMarkDefs = (node.markDefs || []).filter((def) => {\n return node.children.find((child) => {\n return (\n Text.isText(child) &&\n Array.isArray(child.marks) &&\n child.marks.includes(def._key)\n )\n })\n })\n if (node.markDefs && !isEqual(newMarkDefs, node.markDefs)) {\n debug('Removing markDef not in use')\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {\n markDefs: newMarkDefs,\n },\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n }\n\n normalizeNode(nodeEntry)\n }\n\n editor.apply = (op) => {\n /**\n * We don't want to run any side effects when the editor is processing\n * remote changes.\n */\n if (isChangingRemotely(editor)) {\n apply(op)\n return\n }\n\n /**\n * We don't want to run any side effects when the editor is undoing or\n * redoing operations.\n */\n if (isUndoing(editor) || isRedoing(editor)) {\n apply(op)\n return\n }\n\n if (op.type === 'set_selection') {\n const marks = Editor.marks(editor)\n\n if (\n marks &&\n op.properties &&\n op.newProperties &&\n op.properties.anchor &&\n op.properties.focus &&\n op.newProperties.anchor &&\n op.newProperties.focus\n ) {\n const previousSelectionIsCollapsed = Range.isCollapsed({\n anchor: op.properties.anchor,\n focus: op.properties.focus,\n })\n const newSelectionIsCollapsed = Range.isCollapsed({\n anchor: op.newProperties.anchor,\n focus: op.newProperties.focus,\n })\n\n if (previousSelectionIsCollapsed && newSelectionIsCollapsed) {\n const focusSpan: PortableTextSpan | undefined = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: op.properties.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0]?.[0]\n const newFocusSpan: PortableTextSpan | undefined = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: op.newProperties.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0]?.[0]\n const movedToNextSpan =\n focusSpan &&\n newFocusSpan &&\n op.newProperties.focus.path[0] === op.properties.focus.path[0] &&\n op.newProperties.focus.path[1] ===\n op.properties.focus.path[1] + 1 &&\n focusSpan.text.length === op.properties.focus.offset &&\n op.newProperties.focus.offset === 0\n const movedToPreviousSpan =\n focusSpan &&\n newFocusSpan &&\n op.newProperties.focus.path[0] === op.properties.focus.path[0] &&\n op.newProperties.focus.path[1] ===\n op.properties.focus.path[1] - 1 &&\n op.properties.focus.offset === 0 &&\n newFocusSpan.text.length === op.newProperties.focus.offset\n\n // If the editor has marks and we are not visually moving the\n // selection then we just abort. Otherwise the marks would be\n // cleared and we can't use them for the possible subsequent insert\n // operation.\n if (movedToNextSpan || movedToPreviousSpan) {\n return\n }\n }\n }\n }\n\n if (op.type === 'insert_node') {\n const {selection} = editor\n\n if (selection) {\n const [_block, blockPath] = Editor.node(editor, selection, {depth: 1})\n const previousSpan = getPreviousSpan({\n editor,\n blockPath,\n spanPath: op.path,\n })\n const previousSpanAnnotations = previousSpan\n ? previousSpan.marks?.filter((mark) => !decorators.includes(mark))\n : []\n\n const nextSpan = getNextSpan({\n editor,\n blockPath,\n spanPath: [op.path[0], op.path[1] - 1],\n })\n const nextSpanAnnotations = nextSpan\n ? nextSpan.marks?.filter((mark) => !decorators.includes(mark))\n : []\n\n const annotationsEnding =\n previousSpanAnnotations?.filter(\n (annotation) => !nextSpanAnnotations?.includes(annotation),\n ) ?? []\n const atTheEndOfAnnotation = annotationsEnding.length > 0\n\n if (\n atTheEndOfAnnotation &&\n isPortableTextSpan(op.node) &&\n op.node.marks?.some((mark) => annotationsEnding.includes(mark))\n ) {\n Transforms.insertNodes(editor, {\n ...op.node,\n marks:\n op.node.marks?.filter(\n (mark) => !annotationsEnding.includes(mark),\n ) ?? [],\n })\n return\n }\n\n const annotationsStarting =\n nextSpanAnnotations?.filter(\n (annotation) => !previousSpanAnnotations?.includes(annotation),\n ) ?? []\n const atTheStartOfAnnotation = annotationsStarting.length > 0\n\n if (\n atTheStartOfAnnotation &&\n isPortableTextSpan(op.node) &&\n op.node.marks?.some((mark) => annotationsStarting.includes(mark))\n ) {\n Transforms.insertNodes(editor, {\n ...op.node,\n marks:\n op.node.marks?.filter(\n (mark) => !annotationsStarting.includes(mark),\n ) ?? [],\n })\n return\n }\n\n const nextSpanDecorators =\n nextSpan?.marks?.filter((mark) => decorators.includes(mark)) ?? []\n const decoratorStarting = nextSpanDecorators.length > 0\n\n if (\n decoratorStarting &&\n atTheEndOfAnnotation &&\n !atTheStartOfAnnotation &&\n isPortableTextSpan(op.node) &&\n op.node.marks?.length === 0\n ) {\n Transforms.insertNodes(editor, {\n ...op.node,\n marks: nextSpanDecorators,\n })\n return\n }\n }\n }\n\n if (op.type === 'insert_text') {\n const {selection} = editor\n const collapsedSelection = selection\n ? Range.isCollapsed(selection)\n : false\n\n if (selection && collapsedSelection) {\n const [_block, blockPath] = Editor.node(editor, selection, {\n depth: 1,\n })\n\n const [span, spanPath] =\n Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: selection.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0] ?? ([undefined, undefined] as const)\n\n const marks = span.marks ?? []\n const marksWithoutAnnotations = marks.filter((mark) =>\n decorators.includes(mark),\n )\n const spanHasAnnotations =\n marks.length > marksWithoutAnnotations.length\n\n const spanIsEmpty = span.text.length === 0\n\n const atTheBeginningOfSpan = selection.anchor.offset === 0\n const atTheEndOfSpan = selection.anchor.offset === span.text.length\n\n const previousSpan = getPreviousSpan({editor, blockPath, spanPath})\n const nextSpan = getNextSpan({editor, blockPath, spanPath})\n const nextSpanAnnotations =\n nextSpan?.marks?.filter((mark) => !decorators.includes(mark)) ?? []\n const spanAnnotations = marks.filter(\n (mark) => !decorators.includes(mark),\n )\n\n const previousSpanHasAnnotations = previousSpan\n ? previousSpan.marks?.some((mark) => !decorators.includes(mark))\n : false\n const previousSpanHasSameAnnotations = previousSpan\n ? previousSpan.marks\n ?.filter((mark) => !decorators.includes(mark))\n .every((mark) => marks.includes(mark))\n : false\n const previousSpanHasSameAnnotation = previousSpan\n ? previousSpan.marks?.some(\n (mark) => !decorators.includes(mark) && marks.includes(mark),\n )\n : false\n\n const previousSpanHasSameMarks = previousSpan\n ? previousSpan.marks?.every((mark) => marks.includes(mark))\n : false\n const nextSpanSharesSomeAnnotations = spanAnnotations.some((mark) =>\n nextSpanAnnotations?.includes(mark),\n )\n\n if (spanHasAnnotations && !spanIsEmpty) {\n if (atTheBeginningOfSpan) {\n if (previousSpanHasSameMarks) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: previousSpan?.marks ?? [],\n })\n return\n } else if (previousSpanHasSameAnnotations) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: previousSpan?.marks ?? [],\n })\n return\n } else if (previousSpanHasSameAnnotation) {\n apply(op)\n return\n } else if (!previousSpan) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: [],\n })\n return\n }\n }\n\n if (atTheEndOfSpan) {\n if (\n (nextSpan &&\n nextSpanSharesSomeAnnotations &&\n nextSpanAnnotations.length < spanAnnotations.length) ||\n !nextSpanSharesSomeAnnotations\n ) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: nextSpan?.marks ?? [],\n })\n return\n }\n\n if (!nextSpan) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: [],\n })\n return\n }\n }\n }\n\n if (atTheBeginningOfSpan && !spanIsEmpty && !!previousSpan) {\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: op.text,\n marks: previousSpanHasAnnotations\n ? []\n : (previousSpan.marks ?? []).filter((mark) =>\n decorators.includes(mark),\n ),\n })\n return\n }\n }\n }\n\n if (op.type === 'remove_text') {\n const {selection} = editor\n\n if (selection && Range.isExpanded(selection)) {\n const [block, blockPath] = Editor.node(editor, selection, {\n depth: 1,\n })\n const [span, spanPath] =\n Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: {path: op.path, offset: op.offset},\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0] ?? ([undefined, undefined] as const)\n\n if (span && block && isPortableTextBlock(block)) {\n const markDefs = block.markDefs ?? []\n const marks = span.marks ?? []\n const spanHasAnnotations = marks.some((mark) =>\n markDefs.find((markDef) => markDef._key === mark),\n )\n const deletingFromTheEnd =\n op.offset + op.text.length === span.text.length\n const deletingAllText = op.offset === 0 && deletingFromTheEnd\n\n const previousSpan = getPreviousSpan({editor, blockPath, spanPath})\n const nextSpan = getNextSpan({editor, blockPath, spanPath})\n\n const previousSpanHasSameAnnotation = previousSpan\n ? previousSpan.marks?.some(\n (mark) => !decorators.includes(mark) && marks.includes(mark),\n )\n : false\n const nextSpanHasSameAnnotation = nextSpan\n ? nextSpan.marks?.some(\n (mark) => !decorators.includes(mark) && marks.includes(mark),\n )\n : false\n\n if (\n spanHasAnnotations &&\n deletingAllText &&\n !previousSpanHasSameAnnotation &&\n !nextSpanHasSameAnnotation\n ) {\n const marksWithoutAnnotationMarks: string[] = (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).filter((mark) => decorators.includes(mark))\n\n Editor.withoutNormalizing(editor, () => {\n apply(op)\n Transforms.setNodes(\n editor,\n {marks: marksWithoutAnnotationMarks},\n {at: op.path},\n )\n })\n\n editor.onChange()\n return\n }\n }\n }\n }\n\n /**\n * Copy over markDefs when merging blocks\n */\n if (\n op.type === 'merge_node' &&\n op.path.length === 1 &&\n 'markDefs' in op.properties &&\n op.properties._type === types.block.name &&\n Array.isArray(op.properties.markDefs) &&\n op.properties.markDefs.length > 0 &&\n op.path[0] - 1 >= 0\n ) {\n const [targetBlock, targetPath] = Editor.node(editor, [op.path[0] - 1])\n\n if (editor.isTextBlock(targetBlock)) {\n const oldDefs =\n (Array.isArray(targetBlock.markDefs) && targetBlock.markDefs) || []\n const newMarkDefs = uniq([...oldDefs, ...op.properties.markDefs])\n\n debug(`Copying markDefs over to merged block`, op)\n Transforms.setNodes(\n editor,\n {markDefs: newMarkDefs},\n {at: targetPath, voids: false},\n )\n apply(op)\n return\n }\n }\n\n apply(op)\n }\n\n return editor\n }\n}\n\nexport const addDecoratorActionImplementation: BehaviourActionImplementation<\n 'decorator.add'\n> = ({action}) => {\n const editor = action.editor\n const mark = action.decorator\n\n if (editor.selection) {\n if (Range.isExpanded(editor.selection)) {\n // Split if needed\n Transforms.setNodes(\n editor,\n {},\n {match: Text.isText, split: true, hanging: true},\n )\n // Use new selection\n const splitTextNodes = Range.isRange(editor.selection)\n ? [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: Text.isText,\n }),\n ]\n : []\n const shouldRemoveMark =\n splitTextNodes.length > 1 &&\n splitTextNodes.every((node) => node[0].marks?.includes(mark))\n\n if (shouldRemoveMark) {\n editor.removeMark(mark)\n } else {\n splitTextNodes.forEach(([node, path]) => {\n const marks = [\n ...(Array.isArray(node.marks) ? node.marks : []).filter(\n (eMark: string) => eMark !== mark,\n ),\n mark,\n ]\n Transforms.setNodes(\n editor,\n {marks},\n {at: path, match: Text.isText, split: true, hanging: true},\n )\n })\n }\n } else {\n const [block, blockPath] = Editor.node(editor, editor.selection, {\n depth: 1,\n })\n const lonelyEmptySpan =\n editor.isTextBlock(block) &&\n block.children.length === 1 &&\n editor.isTextSpan(block.children[0]) &&\n block.children[0].text === ''\n ? block.children[0]\n : undefined\n\n if (lonelyEmptySpan) {\n const existingMarks = lonelyEmptySpan.marks ?? []\n const existingMarksWithoutDecorator = existingMarks.filter(\n (existingMark) => existingMark !== mark,\n )\n\n Transforms.setNodes(\n editor,\n {\n marks:\n existingMarks.length === existingMarksWithoutDecorator.length\n ? [...existingMarks, mark]\n : existingMarksWithoutDecorator,\n },\n {\n at: blockPath,\n match: (node) => editor.isTextSpan(node),\n },\n )\n } else {\n const existingMarks: string[] =\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n const marks = {\n ...(Editor.marks(editor) || {}),\n marks: [...existingMarks, mark],\n }\n editor.marks = marks as Text\n }\n }\n editor.onChange()\n }\n}\n\nexport const removeDecoratorActionImplementation: BehaviourActionImplementation<\n 'decorator.remove'\n> = ({action}) => {\n const editor = action.editor\n const mark = action.decorator\n const {selection} = editor\n\n if (selection) {\n if (Range.isExpanded(selection)) {\n // Split if needed\n Transforms.setNodes(\n editor,\n {},\n {match: Text.isText, split: true, hanging: true},\n )\n if (editor.selection) {\n const splitTextNodes = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: Text.isText,\n }),\n ]\n splitTextNodes.forEach(([node, path]) => {\n const block = editor.children[path[0]]\n if (Element.isElement(block) && block.children.includes(node)) {\n Transforms.setNodes(\n editor,\n {\n marks: (Array.isArray(node.marks) ? node.marks : []).filter(\n (eMark: string) => eMark !== mark,\n ),\n _type: 'span',\n },\n {at: path},\n )\n }\n })\n }\n } else {\n const [block, blockPath] = Editor.node(editor, selection, {\n depth: 1,\n })\n const lonelyEmptySpan =\n editor.isTextBlock(block) &&\n block.children.length === 1 &&\n editor.isTextSpan(block.children[0]) &&\n block.children[0].text === ''\n ? block.children[0]\n : undefined\n\n if (lonelyEmptySpan) {\n const existingMarks = lonelyEmptySpan.marks ?? []\n const existingMarksWithoutDecorator = existingMarks.filter(\n (existingMark) => existingMark !== mark,\n )\n\n Transforms.setNodes(\n editor,\n {\n marks: existingMarksWithoutDecorator,\n },\n {\n at: blockPath,\n match: (node) => editor.isTextSpan(node),\n },\n )\n } else {\n const existingMarks: string[] =\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n const marks = {\n ...(Editor.marks(editor) || {}),\n marks: existingMarks.filter((eMark) => eMark !== mark),\n } as Text\n editor.marks = {marks: marks.marks, _type: 'span'} as Text\n }\n }\n }\n}\n\nexport function isDecoratorActive({\n editor,\n decorator,\n}: {\n editor: PortableTextSlateEditor\n decorator: string\n}) {\n if (!editor.selection) {\n return false\n }\n\n const selectedNodes = Array.from(\n Editor.nodes(editor, {match: Text.isText, at: editor.selection}),\n )\n\n if (Range.isExpanded(editor.selection)) {\n return selectedNodes.every((n) => {\n const [node] = n\n\n return node.marks?.includes(decorator)\n })\n }\n\n return (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).includes(decorator)\n}\n\nexport const toggleDecoratorActionImplementation: BehaviourActionImplementation<\n 'decorator.toggle'\n> = ({context, action}) => {\n const isActive = isDecoratorActive({\n editor: action.editor,\n decorator: action.decorator,\n })\n\n if (isActive) {\n removeDecoratorActionImplementation({\n context,\n action: {\n type: 'decorator.remove',\n editor: action.editor,\n decorator: action.decorator,\n },\n })\n } else {\n addDecoratorActionImplementation({\n context,\n action: {\n type: 'decorator.add',\n editor: action.editor,\n decorator: action.decorator,\n },\n })\n }\n}\n","import type {BaseRange} from 'slate'\nimport type {\n EditorSelection,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {\n toPortableTextRange,\n type ObjectWithKeyAndType,\n} from '../../utils/ranges'\nimport {SLATE_TO_PORTABLE_TEXT_RANGE} from '../../utils/weakMaps'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextSelections')\nconst debugVerbose = debug.enabled && false\n\n// This plugin will make sure that we emit a PT selection whenever the editor has changed.\nexport function createWithPortableTextSelections(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n let prevSelection: BaseRange | null = null\n return function withPortableTextSelections(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const emitPortableTextSelection = () => {\n if (prevSelection !== editor.selection) {\n let ptRange: EditorSelection = null\n if (editor.selection) {\n const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection)\n if (existing) {\n ptRange = existing\n } else {\n const value = editor.children satisfies ObjectWithKeyAndType[]\n ptRange = toPortableTextRange(value, editor.selection, types)\n SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange)\n }\n }\n if (debugVerbose) {\n debug(\n `Emitting selection ${JSON.stringify(ptRange || null)} (${JSON.stringify(\n editor.selection,\n )})`,\n )\n }\n if (ptRange) {\n editorActor.send({type: 'selection', selection: ptRange})\n } else {\n editorActor.send({type: 'selection', selection: null})\n }\n }\n prevSelection = editor.selection\n }\n\n const {onChange} = editor\n editor.onChange = () => {\n const hasChanges = editor.operations.length > 0\n onChange()\n if (hasChanges) {\n emitPortableTextSelection()\n }\n }\n return editor\n }\n}\n","import {\n isPortableTextListBlock,\n isPortableTextSpan,\n isPortableTextTextBlock,\n type PortableTextListBlock,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport {Transforms, type Element} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withSchemaTypes')\n/**\n * This plugin makes sure that schema types are recognized properly by Slate as blocks, voids, inlines\n *\n */\nexport function createWithSchemaTypes({\n editorActor,\n schemaTypes,\n}: {\n editorActor: EditorActor\n schemaTypes: PortableTextMemberSchemaTypes\n}) {\n return function withSchemaTypes(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n editor.isTextBlock = (value: unknown): value is PortableTextTextBlock => {\n return (\n isPortableTextTextBlock(value) && value._type === schemaTypes.block.name\n )\n }\n editor.isTextSpan = (value: unknown): value is PortableTextSpan => {\n return isPortableTextSpan(value) && value._type === schemaTypes.span.name\n }\n editor.isListBlock = (value: unknown): value is PortableTextListBlock => {\n return (\n isPortableTextListBlock(value) && value._type === schemaTypes.block.name\n )\n }\n editor.isVoid = (element: Element): boolean => {\n return (\n schemaTypes.block.name !== element._type &&\n (schemaTypes.blockObjects\n .map((obj) => obj.name)\n .includes(element._type) ||\n schemaTypes.inlineObjects\n .map((obj) => obj.name)\n .includes(element._type))\n )\n }\n editor.isInline = (element: Element): boolean => {\n const inlineSchemaTypes = schemaTypes.inlineObjects.map((obj) => obj.name)\n return (\n inlineSchemaTypes.includes(element._type) &&\n '__inline' in element &&\n element.__inline === true\n )\n }\n\n // Extend Slate's default normalization\n const {normalizeNode} = editor\n editor.normalizeNode = (entry) => {\n const [node, path] = entry\n\n // If text block children node is missing _type, set it to the span type\n if (node._type === undefined && path.length === 2) {\n debug('Setting span type on text node without a type')\n const span = node as PortableTextSpan\n const key =\n span._key || editorActor.getSnapshot().context.keyGenerator()\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(\n editor,\n {...span, _type: schemaTypes.span.name, _key: key},\n {at: path},\n )\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n // catches cases when the children are missing keys but excludes it when the normalize is running the node as the editor object\n if (node._key === undefined && (path.length === 1 || path.length === 2)) {\n debug('Setting missing key on child node without a key')\n const key = editorActor.getSnapshot().context.keyGenerator()\n editorActor.send({type: 'normalizing'})\n Transforms.setNodes(editor, {_key: key}, {at: path})\n editorActor.send({type: 'done normalizing'})\n return\n }\n\n normalizeNode(entry)\n }\n return editor\n }\n}\n","import {Editor, Range, Text, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toSlateValue} from '../../utils/values'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withUtils')\n\ninterface Options {\n editorActor: EditorActor\n schemaTypes: PortableTextMemberSchemaTypes\n}\n/**\n * This plugin makes various util commands available in the editor\n *\n */\nexport function createWithUtils({editorActor, schemaTypes}: Options) {\n return function withUtils(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n // Expands the the selection to wrap around the word the focus is at\n editor.pteExpandToWord = () => {\n const {selection} = editor\n if (selection && !Range.isExpanded(selection)) {\n const [textNode] = Editor.node(editor, selection.focus, {depth: 2})\n if (!textNode || !Text.isText(textNode) || textNode.text.length === 0) {\n debug(`pteExpandToWord: Can't expand to word here`)\n return\n }\n const {focus} = selection\n const focusOffset = focus.offset\n const charsBefore = textNode.text.slice(0, focusOffset)\n const charsAfter = textNode.text.slice(focusOffset, -1)\n const isEmpty = (str: string) => str.match(/\\s/g)\n const whiteSpaceBeforeIndex = charsBefore\n .split('')\n .reverse()\n .findIndex((str) => isEmpty(str))\n const newStartOffset =\n whiteSpaceBeforeIndex > -1\n ? charsBefore.length - whiteSpaceBeforeIndex\n : 0\n const whiteSpaceAfterIndex = charsAfter\n .split('')\n .findIndex((obj) => isEmpty(obj))\n const newEndOffset =\n charsBefore.length +\n (whiteSpaceAfterIndex > -1\n ? whiteSpaceAfterIndex\n : charsAfter.length + 1)\n if (\n !(\n newStartOffset === newEndOffset ||\n Number.isNaN(newStartOffset) ||\n Number.isNaN(newEndOffset)\n )\n ) {\n debug('pteExpandToWord: Expanding to focused word')\n Transforms.setSelection(editor, {\n anchor: {...selection.anchor, offset: newStartOffset},\n focus: {...selection.focus, offset: newEndOffset},\n })\n return\n }\n debug(`pteExpandToWord: Can't expand to word here`)\n }\n }\n\n editor.pteCreateTextBlock = (options: {\n decorators: Array<string>\n listItem?: string\n level?: number\n }) => {\n const block = toSlateValue(\n [\n {\n _type: schemaTypes.block.name,\n _key: editorActor.getSnapshot().context.keyGenerator(),\n style: schemaTypes.styles[0].value || 'normal',\n ...(options.listItem ? {listItem: options.listItem} : {}),\n ...(options.level ? {level: options.level} : {}),\n markDefs: [],\n children: [\n {\n _type: 'span',\n _key: editorActor.getSnapshot().context.keyGenerator(),\n text: '',\n marks: options.decorators.filter((decorator) =>\n schemaTypes.decorators.find(({value}) => value === decorator),\n ),\n },\n ],\n },\n ],\n {schemaTypes},\n )[0]\n return block\n }\n return editor\n }\n}\n","import type {BaseOperation, Editor, Node, NodeEntry} from 'slate'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport type {createEditorOptions} from '../../types/options'\nimport {createOperationToPatches} from '../../utils/operationToPatches'\nimport {createWithEventListeners} from './create-with-event-listeners'\nimport {createWithMaxBlocks} from './createWithMaxBlocks'\nimport {createWithObjectKeys} from './createWithObjectKeys'\nimport {createWithPatches} from './createWithPatches'\nimport {createWithPlaceholderBlock} from './createWithPlaceholderBlock'\nimport {createWithPortableTextBlockStyle} from './createWithPortableTextBlockStyle'\nimport {createWithPortableTextLists} from './createWithPortableTextLists'\nimport {createWithPortableTextMarkModel} from './createWithPortableTextMarkModel'\nimport {createWithPortableTextSelections} from './createWithPortableTextSelections'\nimport {createWithSchemaTypes} from './createWithSchemaTypes'\nimport {createWithUndoRedo} from './createWithUndoRedo'\nimport {createWithUtils} from './createWithUtils'\n\nexport interface OriginalEditorFunctions {\n apply: (operation: BaseOperation) => void\n onChange: () => void\n normalizeNode: (entry: NodeEntry<Node>) => void\n}\n\nconst originalFnMap = new WeakMap<\n PortableTextSlateEditor,\n OriginalEditorFunctions\n>()\n\nexport const withPlugins = <T extends Editor>(\n editor: T,\n options: createEditorOptions,\n): PortableTextSlateEditor => {\n const e = editor as T & PortableTextSlateEditor\n const {editorActor} = options\n const schemaTypes = editorActor.getSnapshot().context.schema\n if (e.destroy) {\n e.destroy()\n } else {\n // Save a copy of the original editor functions here before they were changed by plugins.\n // We will put them back when .destroy is called (see below).\n originalFnMap.set(e, {\n apply: e.apply,\n onChange: e.onChange,\n normalizeNode: e.normalizeNode,\n })\n }\n const operationToPatches = createOperationToPatches(schemaTypes)\n const withObjectKeys = createWithObjectKeys(editorActor, schemaTypes)\n const withSchemaTypes = createWithSchemaTypes({\n editorActor,\n schemaTypes,\n })\n const withPatches = createWithPatches({\n editorActor,\n patchFunctions: operationToPatches,\n schemaTypes,\n subscriptions: options.subscriptions,\n })\n const withMaxBlocks = createWithMaxBlocks(editorActor)\n const withPortableTextLists = createWithPortableTextLists(schemaTypes)\n const withUndoRedo = createWithUndoRedo({\n editorActor,\n blockSchemaType: schemaTypes.block,\n subscriptions: options.subscriptions,\n })\n const withPortableTextMarkModel = createWithPortableTextMarkModel(\n editorActor,\n schemaTypes,\n )\n const withPortableTextBlockStyle = createWithPortableTextBlockStyle(\n editorActor,\n schemaTypes,\n )\n\n const withPlaceholderBlock = createWithPlaceholderBlock(editorActor)\n\n const withUtils = createWithUtils({\n editorActor,\n schemaTypes,\n })\n const withPortableTextSelections = createWithPortableTextSelections(\n editorActor,\n schemaTypes,\n )\n const withEventListeners = createWithEventListeners(\n editorActor,\n options.subscriptions,\n )\n\n e.destroy = () => {\n const originalFunctions = originalFnMap.get(e)\n if (!originalFunctions) {\n throw new Error('Could not find pristine versions of editor functions')\n }\n e.apply = originalFunctions.apply\n e.history = {undos: [], redos: []}\n e.normalizeNode = originalFunctions.normalizeNode\n e.onChange = originalFunctions.onChange\n }\n\n // Ordering is important here, selection dealing last, data manipulation in the middle and core model stuff first.\n return withEventListeners(\n withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withPortableTextLists(\n withPlaceholderBlock(\n withUtils(\n withMaxBlocks(\n withUndoRedo(withPatches(withPortableTextSelections(e))),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n}\n","import {createEditor, type Descendant} from 'slate'\nimport {withReact} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../types/editor'\nimport {debugWithName} from '../utils/debug'\nimport {KEY_TO_SLATE_ELEMENT, KEY_TO_VALUE_ELEMENT} from '../utils/weakMaps'\nimport type {EditorActor} from './editor-machine'\nimport {withPlugins} from './plugins/with-plugins'\n\nconst debug = debugWithName('component:PortableTextEditor:SlateContainer')\n\ntype SlateEditorConfig = {\n editorActor: EditorActor\n}\n\nexport type SlateEditor = {\n instance: PortableTextSlateEditor\n initialValue: Array<Descendant>\n destroy: () => void\n}\n\nconst slateEditors = new WeakMap<EditorActor, SlateEditor>()\n\nexport function createSlateEditor(config: SlateEditorConfig): SlateEditor {\n const existingSlateEditor = slateEditors.get(config.editorActor)\n\n if (existingSlateEditor) {\n debug('Reusing existing Slate editor instance', config.editorActor.id)\n return existingSlateEditor\n }\n\n debug('Creating new Slate editor instance', config.editorActor.id)\n\n let unsubscriptions: Array<() => void> = []\n let subscriptions: Array<() => () => void> = []\n\n const instance = withPlugins(withReact(createEditor()), {\n editorActor: config.editorActor,\n subscriptions,\n })\n\n KEY_TO_VALUE_ELEMENT.set(instance, {})\n KEY_TO_SLATE_ELEMENT.set(instance, {})\n\n for (const subscription of subscriptions) {\n unsubscriptions.push(subscription())\n }\n\n const initialValue = [instance.pteCreateTextBlock({decorators: []})]\n\n const slateEditor: SlateEditor = {\n instance,\n initialValue,\n destroy: () => {\n debug('Destroying Slate editor')\n instance.destroy()\n for (const unsubscribe of unsubscriptions) {\n unsubscribe()\n }\n subscriptions = []\n unsubscriptions = []\n },\n }\n\n slateEditors.set(config.editorActor, slateEditor)\n\n return slateEditor\n}\n","import {createContext} from 'react'\nimport type {EditorActor} from './editor-machine'\n\nexport const EditorActorContext = createContext<EditorActor>({} as EditorActor)\n","import {\n isPortableTextSpan,\n type Path,\n type PortableTextBlock,\n type PortableTextChild,\n type PortableTextObject,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} from '@sanity/types'\nimport {\n Editor,\n Node,\n Range,\n Element as SlateElement,\n Path as SlatePath,\n Text,\n Transforms,\n} from 'slate'\nimport type {DOMNode} from 'slate-dom'\nimport {ReactEditor} from 'slate-react'\nimport type {\n EditableAPI,\n EditableAPIDeleteOptions,\n EditorSelection,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toPortableTextRange, toSlateRange} from '../../utils/ranges'\nimport {\n fromSlateValue,\n isEqualToEmptyEditor,\n toSlateValue,\n} from '../../utils/values'\nimport {\n KEY_TO_VALUE_ELEMENT,\n SLATE_TO_PORTABLE_TEXT_RANGE,\n} from '../../utils/weakMaps'\nimport type {BehaviourActionImplementation} from '../behavior/behavior.actions'\nimport type {EditorActor} from '../editor-machine'\nimport {isDecoratorActive} from './createWithPortableTextMarkModel'\n\nconst debug = debugWithName('API:editable')\n\nexport function createEditableAPI(\n editor: PortableTextSlateEditor,\n editorActor: EditorActor,\n) {\n const types = editorActor.getSnapshot().context.schema\n\n const editableApi: EditableAPI = {\n focus: (): void => {\n ReactEditor.focus(editor)\n },\n blur: (): void => {\n ReactEditor.blur(editor)\n },\n toggleMark: (mark: string): void => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.toggle',\n decorator: mark,\n },\n editor,\n })\n },\n toggleList: (listStyle: string): void => {\n editor.pteToggleListItem(listStyle)\n },\n toggleBlockStyle: (blockStyle: string): void => {\n editor.pteToggleBlockStyle(blockStyle)\n },\n isMarkActive: (mark: string): boolean => {\n // Try/catch this, as Slate may error because the selection is currently wrong\n // TODO: catch only relevant error from Slate\n try {\n return isDecoratorActive({editor, decorator: mark})\n } catch (err) {\n console.warn(err)\n return false\n }\n },\n marks: (): string[] => {\n return (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n )\n },\n undo: (): void => editor.undo(),\n redo: (): void => editor.redo(),\n select: (selection: EditorSelection): void => {\n const slateSelection = toSlateRange(selection, editor)\n if (slateSelection) {\n Transforms.select(editor, slateSelection)\n } else {\n Transforms.deselect(editor)\n }\n editor.onChange()\n },\n focusBlock: (): PortableTextBlock | undefined => {\n if (editor.selection) {\n const block = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n )\n if (block) {\n return fromSlateValue(\n [block],\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0]\n }\n }\n return undefined\n },\n focusChild: (): PortableTextChild | undefined => {\n if (editor.selection) {\n const block = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n )\n if (block && editor.isTextBlock(block)) {\n const ptBlock = fromSlateValue(\n [block],\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0] as PortableTextTextBlock\n return ptBlock.children[editor.selection.focus.path[1]]\n }\n }\n return undefined\n },\n insertChild: <TSchemaType extends {name: string}>(\n type: TSchemaType,\n value?: {[prop: string]: any},\n ): Path => {\n if (!editor.selection) {\n throw new Error('The editor has no selection')\n }\n const [focusBlock] = Array.from(\n Editor.nodes(editor, {\n at: editor.selection.focus.path.slice(0, 1),\n match: (n) => n._type === types.block.name,\n }),\n )[0] || [undefined]\n if (!focusBlock) {\n throw new Error('No focused text block')\n }\n if (\n type.name !== types.span.name &&\n !types.inlineObjects.some((t) => t.name === type.name)\n ) {\n throw new Error(\n 'This type cannot be inserted as a child to a text block',\n )\n }\n const block = toSlateValue(\n [\n {\n _key: editorActor.getSnapshot().context.keyGenerator(),\n _type: types.block.name,\n children: [\n {\n _key: editorActor.getSnapshot().context.keyGenerator(),\n _type: type.name,\n ...(value ? value : {}),\n },\n ],\n },\n ],\n {schemaTypes: editorActor.getSnapshot().context.schema},\n )[0] as unknown as SlateElement\n const child = block.children[0]\n const focusChildPath = editor.selection.focus.path.slice(0, 2)\n const isSpanNode = child._type === types.span.name\n const focusNode = Node.get(editor, focusChildPath)\n\n // If we are inserting a span, and currently have focus on an inline object,\n // move the selection to the next span (guaranteed by normalizing rules) before inserting it.\n if (isSpanNode && focusNode._type !== types.span.name) {\n debug(\n 'Inserting span child next to inline object child, moving selection + 1',\n )\n editor.move({distance: 1, unit: 'character'})\n }\n\n Transforms.insertNodes(editor, child, {\n select: true,\n at: editor.selection,\n })\n editor.onChange()\n return (\n toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )?.focus.path || []\n )\n },\n insertBlock: <TSchemaType extends {name: string}>(\n type: TSchemaType,\n value?: {[prop: string]: any},\n ): Path => {\n const block = toSlateValue(\n [\n {\n _key: editorActor.getSnapshot().context.keyGenerator(),\n _type: type.name,\n ...(value ? value : {}),\n },\n ],\n {schemaTypes: editorActor.getSnapshot().context.schema},\n )[0] as unknown as Node\n\n if (!editor.selection) {\n const lastBlock = Array.from(\n Editor.nodes(editor, {\n match: (n) => !Editor.isEditor(n),\n at: [],\n reverse: true,\n }),\n )[0]\n\n // If there is no selection, let's just insert the new block at the\n // end of the document\n Editor.insertNode(editor, block)\n\n if (lastBlock && isEqualToEmptyEditor([lastBlock[0]], types)) {\n // And if the last block was an empty text block, let's remove\n // that too\n Transforms.removeNodes(editor, {at: lastBlock[1]})\n }\n\n editor.onChange()\n\n return (\n toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )?.focus.path ?? []\n )\n }\n\n const focusBlock = Array.from(\n Editor.nodes(editor, {\n at: editor.selection.focus.path.slice(0, 1),\n match: (n) => n._type === types.block.name,\n }),\n )[0]\n\n Editor.insertNode(editor, block)\n\n if (focusBlock && isEqualToEmptyEditor([focusBlock[0]], types)) {\n Transforms.removeNodes(editor, {at: focusBlock[1]})\n }\n\n editor.onChange()\n\n return (\n toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )?.focus.path || []\n )\n },\n hasBlockStyle: (style: string): boolean => {\n try {\n return editor.pteHasBlockStyle(style)\n } catch {\n // This is fine.\n return false\n }\n },\n hasListStyle: (listStyle: string): boolean => {\n try {\n return editor.pteHasListStyle(listStyle)\n } catch {\n // This is fine.\n return false\n }\n },\n isVoid: (element: PortableTextBlock | PortableTextChild) => {\n return ![types.block.name, types.span.name].includes(element._type)\n },\n findByPath: (\n path: Path,\n ): [\n PortableTextBlock | PortableTextChild | undefined,\n Path | undefined,\n ] => {\n const slatePath = toSlateRange(\n {focus: {path, offset: 0}, anchor: {path, offset: 0}},\n editor,\n )\n if (slatePath) {\n const [block, blockPath] = Editor.node(\n editor,\n slatePath.focus.path.slice(0, 1),\n )\n if (block && blockPath && typeof block._key === 'string') {\n if (path.length === 1 && slatePath.focus.path.length === 1) {\n return [\n fromSlateValue([block], types.block.name)[0],\n [{_key: block._key}],\n ]\n }\n const ptBlock = fromSlateValue(\n [block],\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )[0]\n if (editor.isTextBlock(ptBlock)) {\n const ptChild = ptBlock.children[slatePath.focus.path[1]]\n if (ptChild) {\n return [\n ptChild,\n [{_key: block._key}, 'children', {_key: ptChild._key}],\n ]\n }\n }\n }\n }\n return [undefined, undefined]\n },\n findDOMNode: (\n element: PortableTextBlock | PortableTextChild,\n ): DOMNode | undefined => {\n let node: DOMNode | undefined\n try {\n const [item] = Array.from(\n Editor.nodes(editor, {\n at: [],\n match: (n) => n._key === element._key,\n }) || [],\n )[0] || [undefined]\n node = ReactEditor.toDOMNode(editor, item)\n } catch {\n // Nothing\n }\n return node\n },\n activeAnnotations: (): PortableTextObject[] => {\n if (!editor.selection || editor.selection.focus.path.length < 2) {\n return []\n }\n try {\n const activeAnnotations: PortableTextObject[] = []\n const spans = Editor.nodes(editor, {\n at: editor.selection,\n match: (node) =>\n Text.isText(node) &&\n node.marks !== undefined &&\n Array.isArray(node.marks) &&\n node.marks.length > 0,\n })\n for (const [span, path] of spans) {\n const [block] = Editor.node(editor, path, {depth: 1})\n if (editor.isTextBlock(block)) {\n block.markDefs?.forEach((def) => {\n if (\n Text.isText(span) &&\n span.marks &&\n Array.isArray(span.marks) &&\n span.marks.includes(def._key)\n ) {\n activeAnnotations.push(def)\n }\n })\n }\n }\n return activeAnnotations\n } catch {\n return []\n }\n },\n isAnnotationActive: (\n annotationType: PortableTextObject['_type'],\n ): boolean => {\n return isAnnotationActive({editor, annotation: {name: annotationType}})\n },\n addAnnotation: (type, value) => {\n let paths: ReturnType<EditableAPI['addAnnotation']> = undefined\n\n Editor.withoutNormalizing(editor, () => {\n paths = addAnnotationActionImplementation({\n context: {\n keyGenerator: editorActor.getSnapshot().context.keyGenerator,\n schema: types,\n },\n action: {\n type: 'annotation.add',\n annotation: {name: type.name, value: value ?? {}},\n editor,\n },\n })\n })\n editor.onChange()\n\n return paths\n },\n delete: (\n selection: EditorSelection,\n options?: EditableAPIDeleteOptions,\n ): void => {\n if (selection) {\n const range = toSlateRange(selection, editor)\n const hasRange =\n range && range.anchor.path.length > 0 && range.focus.path.length > 0\n if (!hasRange) {\n throw new Error('Invalid range')\n }\n if (range) {\n if (!options?.mode || options?.mode === 'selected') {\n debug(`Deleting content in selection`)\n Transforms.delete(editor, {\n at: range,\n hanging: true,\n voids: true,\n })\n editor.onChange()\n return\n }\n if (options?.mode === 'blocks') {\n debug(`Deleting blocks touched by selection`)\n Transforms.removeNodes(editor, {\n at: range,\n voids: true,\n match: (node) => {\n return (\n editor.isTextBlock(node) ||\n (!editor.isTextBlock(node) && SlateElement.isElement(node))\n )\n },\n })\n }\n if (options?.mode === 'children') {\n debug(`Deleting children touched by selection`)\n Transforms.removeNodes(editor, {\n at: range,\n voids: true,\n match: (node) => {\n return (\n node._type === types.span.name || // Text children\n (!editor.isTextBlock(node) && SlateElement.isElement(node)) // inline blocks\n )\n },\n })\n }\n // If the editor was emptied, insert a placeholder block\n // directly into the editor's children. We don't want to do this\n // through a Transform (because that would trigger a change event\n // that would insert the placeholder into the actual value\n // which should remain empty)\n if (editor.children.length === 0) {\n editor.children = [editor.pteCreateTextBlock({decorators: []})]\n }\n editor.onChange()\n }\n }\n },\n removeAnnotation: <TSchemaType extends {name: string}>(\n type: TSchemaType,\n ): void => {\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'annotation.remove',\n annotation: {name: type.name},\n },\n editor,\n })\n },\n getSelection: (): EditorSelection | null => {\n let ptRange: EditorSelection = null\n if (editor.selection) {\n const existing = SLATE_TO_PORTABLE_TEXT_RANGE.get(editor.selection)\n if (existing) {\n return existing\n }\n ptRange = toPortableTextRange(\n fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n ),\n editor.selection,\n types,\n )\n SLATE_TO_PORTABLE_TEXT_RANGE.set(editor.selection, ptRange)\n }\n return ptRange\n },\n getValue: () => {\n return fromSlateValue(\n editor.children,\n types.block.name,\n KEY_TO_VALUE_ELEMENT.get(editor),\n )\n },\n isCollapsedSelection: () => {\n return !!editor.selection && Range.isCollapsed(editor.selection)\n },\n isExpandedSelection: () => {\n return !!editor.selection && Range.isExpanded(editor.selection)\n },\n insertBreak: () => {\n editor.insertBreak()\n editor.onChange()\n },\n getFragment: () => {\n return fromSlateValue(editor.getFragment(), types.block.name)\n },\n isSelectionsOverlapping: (\n selectionA: EditorSelection,\n selectionB: EditorSelection,\n ) => {\n // Convert the selections to Slate ranges\n const rangeA = toSlateRange(selectionA, editor)\n const rangeB = toSlateRange(selectionB, editor)\n\n // Make sure the ranges are valid\n const isValidRanges = Range.isRange(rangeA) && Range.isRange(rangeB)\n\n // Check if the ranges are overlapping\n const isOverlapping = isValidRanges && Range.includes(rangeA, rangeB)\n\n return isOverlapping\n },\n }\n\n return editableApi\n}\n\nfunction isAnnotationActive({\n editor,\n annotation,\n}: {\n editor: PortableTextSlateEditor\n annotation: {\n name: string\n }\n}) {\n if (!editor.selection || editor.selection.focus.path.length < 2) {\n return false\n }\n\n try {\n const spans = [\n ...Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => Text.isText(node),\n }),\n ]\n\n if (spans.length === 0) {\n return false\n }\n\n if (\n spans.some(\n ([span]) =>\n !isPortableTextSpan(span) || !span.marks || span.marks?.length === 0,\n )\n )\n return false\n\n const selectionMarkDefs = spans.reduce((accMarkDefs, [, path]) => {\n const [block] = Editor.node(editor, path, {depth: 1})\n if (editor.isTextBlock(block) && block.markDefs) {\n return [...accMarkDefs, ...block.markDefs]\n }\n return accMarkDefs\n }, [] as PortableTextObject[])\n\n return spans.every(([span]) => {\n if (!isPortableTextSpan(span)) return false\n\n const spanMarkDefs = span.marks?.map(\n (markKey) =>\n selectionMarkDefs.find((def) => def?._key === markKey)?._type,\n )\n\n return spanMarkDefs?.includes(annotation.name)\n })\n } catch {\n return false\n }\n}\n\n/**\n * @public\n */\nexport type AddedAnnotationPaths = {\n /**\n * @deprecated An annotation may be applied to multiple blocks, resulting\n * in multiple `markDef`'s being created. Use `markDefPaths` instead.\n */\n markDefPath: Path\n markDefPaths: Array<Path>\n /**\n * @deprecated Does not return anything meaningful since an annotation\n * can span multiple blocks and spans. If references the span closest\n * to the focus point of the selection.\n */\n spanPath: Path\n}\n\nexport const addAnnotationActionImplementation: BehaviourActionImplementation<\n 'annotation.add',\n AddedAnnotationPaths | undefined\n> = ({context, action}) => {\n const editor = action.editor\n const {selection: originalSelection} = editor\n let paths: AddedAnnotationPaths | undefined = undefined\n\n if (originalSelection) {\n if (Range.isCollapsed(originalSelection)) {\n editor.pteExpandToWord()\n editor.onChange()\n }\n\n // If we still have a selection, add the annotation to the selected text\n if (editor.selection) {\n let spanPath: Path | undefined\n let markDefPath: Path | undefined\n const markDefPaths: Path[] = []\n\n if (!editor.selection) {\n return\n }\n\n const selectedBlocks = Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n reverse: Range.isBackward(editor.selection),\n })\n\n for (const [block, blockPath] of selectedBlocks) {\n if (block.children.length === 0) {\n continue\n }\n\n if (block.children.length === 1 && block.children[0].text === '') {\n continue\n }\n\n const annotationKey = context.keyGenerator()\n const markDefs = block.markDefs ?? []\n const existingMarkDef = markDefs.find(\n (markDef) =>\n markDef._type === action.annotation.name &&\n markDef._key === annotationKey,\n )\n\n if (existingMarkDef === undefined) {\n Transforms.setNodes(\n editor,\n {\n markDefs: [\n ...markDefs,\n {\n _type: action.annotation.name,\n _key: annotationKey,\n ...action.annotation.value,\n },\n ],\n },\n {at: blockPath},\n )\n\n markDefPath = [{_key: block._key}, 'markDefs', {_key: annotationKey}]\n if (Range.isBackward(editor.selection)) {\n markDefPaths.unshift(markDefPath)\n } else {\n markDefPaths.push(markDefPath)\n }\n }\n\n Transforms.setNodes(editor, {}, {match: Text.isText, split: true})\n\n const children = Node.children(editor, blockPath)\n\n for (const [span, path] of children) {\n if (!editor.isTextSpan(span)) {\n continue\n }\n\n if (!Range.includes(editor.selection, path)) {\n continue\n }\n\n const marks = span.marks ?? []\n const existingSameTypeAnnotations = marks.filter((mark) =>\n markDefs.some(\n (markDef) =>\n markDef._key === mark &&\n markDef._type === action.annotation.name,\n ),\n )\n\n Transforms.setNodes(\n editor,\n {\n marks: [\n ...marks.filter(\n (mark) => !existingSameTypeAnnotations.includes(mark),\n ),\n annotationKey,\n ],\n },\n {at: path},\n )\n spanPath = [{_key: block._key}, 'children', {_key: span._key}]\n }\n }\n\n if (markDefPath && spanPath) {\n paths = {\n markDefPath,\n markDefPaths,\n spanPath,\n }\n }\n }\n }\n return paths\n}\n\nexport const removeAnnotationActionImplementation: BehaviourActionImplementation<\n 'annotation.remove'\n> = ({action}) => {\n const editor = action.editor\n\n debug('Removing annotation', action.annotation.name)\n\n if (!editor.selection) {\n return\n }\n\n if (Range.isCollapsed(editor.selection)) {\n const [block, blockPath] = Editor.node(editor, editor.selection, {\n depth: 1,\n })\n\n if (!editor.isTextBlock(block)) {\n return\n }\n\n const markDefs = block.markDefs ?? []\n const potentialAnnotations = markDefs.filter(\n (markDef) => markDef._type === action.annotation.name,\n )\n\n const [selectedChild, selectedChildPath] = Editor.node(\n editor,\n editor.selection,\n {\n depth: 2,\n },\n )\n\n if (!editor.isTextSpan(selectedChild)) {\n return\n }\n\n const annotationToRemove = selectedChild.marks?.find((mark) =>\n potentialAnnotations.some((markDef) => markDef._key === mark),\n )\n\n if (!annotationToRemove) {\n return\n }\n\n const previousSpansWithSameAnnotation: Array<\n [span: PortableTextSpan, path: SlatePath]\n > = []\n\n for (const [child, childPath] of Node.children(editor, blockPath, {\n reverse: true,\n })) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (!SlatePath.isBefore(childPath, selectedChildPath)) {\n continue\n }\n\n if (child.marks?.includes(annotationToRemove)) {\n previousSpansWithSameAnnotation.push([child, childPath])\n } else {\n break\n }\n }\n\n const nextSpansWithSameAnnotation: Array<\n [span: PortableTextSpan, path: SlatePath]\n > = []\n\n for (const [child, childPath] of Node.children(editor, blockPath)) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (!SlatePath.isAfter(childPath, selectedChildPath)) {\n continue\n }\n\n if (child.marks?.includes(annotationToRemove)) {\n nextSpansWithSameAnnotation.push([child, childPath])\n } else {\n break\n }\n }\n\n for (const [child, childPath] of [\n ...previousSpansWithSameAnnotation,\n [selectedChild, selectedChildPath] as const,\n ...nextSpansWithSameAnnotation,\n ]) {\n Transforms.setNodes(\n editor,\n {\n marks: child.marks?.filter((mark) => mark !== annotationToRemove),\n },\n {at: childPath},\n )\n }\n } else {\n Transforms.setNodes(\n editor,\n {},\n {\n match: (node) => editor.isTextSpan(node),\n split: true,\n hanging: true,\n },\n )\n\n const blocks = Editor.nodes(editor, {\n at: editor.selection,\n match: (node) => editor.isTextBlock(node),\n })\n\n for (const [block, blockPath] of blocks) {\n const children = Node.children(editor, blockPath)\n\n for (const [child, childPath] of children) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n if (!Range.includes(editor.selection, childPath)) {\n continue\n }\n\n const markDefs = block.markDefs ?? []\n const marks = child.marks ?? []\n const marksWithoutAnnotation = marks.filter((mark) => {\n const markDef = markDefs.find((markDef) => markDef._key === mark)\n return markDef?._type !== action.annotation.name\n })\n\n if (marksWithoutAnnotation.length !== marks.length) {\n Transforms.setNodes(\n editor,\n {\n marks: marksWithoutAnnotation,\n },\n {at: childPath},\n )\n }\n }\n }\n }\n}\n\nexport const toggleAnnotationActionImplementation: BehaviourActionImplementation<\n 'annotation.toggle',\n AddedAnnotationPaths | undefined\n> = ({context, action}) => {\n const isActive = isAnnotationActive({\n editor: action.editor,\n annotation: {name: action.annotation.name},\n })\n\n if (isActive) {\n removeAnnotationActionImplementation({\n context,\n action: {\n type: 'annotation.remove',\n annotation: action.annotation,\n editor: action.editor,\n },\n })\n } else {\n return addAnnotationActionImplementation({\n context,\n action: {\n type: 'annotation.add',\n annotation: action.annotation,\n editor: action.editor,\n },\n })\n }\n}\n","import {isEqual} from 'lodash'\nimport {Editor, Node, Path, Range, Transforms} from 'slate'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport type {BehaviourActionImplementation} from './behavior.actions'\n\nexport const insertBreakActionImplementation: BehaviourActionImplementation<\n 'insert break'\n> = ({context, action}) => {\n const keyGenerator = context.keyGenerator\n const schema = context.schema\n const editor = action.editor\n\n if (!editor.selection) {\n return\n }\n\n const [focusSpan] = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: editor.selection.focus,\n match: (n) => editor.isTextSpan(n),\n voids: false,\n }),\n )[0] ?? [undefined]\n const focusDecorators =\n focusSpan.marks?.filter((mark) =>\n schema.decorators.some((decorator) => decorator.value === mark),\n ) ?? []\n const focusAnnotations =\n focusSpan.marks?.filter(\n (mark) =>\n !schema.decorators.some((decorator) => decorator.value === mark),\n ) ?? []\n\n const focusBlockPath = editor.selection.focus.path.slice(0, 1)\n const focusBlock = Node.descendant(editor, focusBlockPath) as\n | SlateTextBlock\n | VoidElement\n\n if (editor.isTextBlock(focusBlock)) {\n const [start, end] = Range.edges(editor.selection)\n const atTheStartOfBlock = isEqual(end, {\n path: [...focusBlockPath, 0],\n offset: 0,\n })\n\n if (atTheStartOfBlock && Range.isCollapsed(editor.selection)) {\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({\n decorators: focusAnnotations.length === 0 ? focusDecorators : [],\n listItem: focusBlock.listItem,\n level: focusBlock.level,\n }),\n )\n\n const [nextBlockPath] = Path.next(focusBlockPath)\n\n Transforms.select(editor, {\n anchor: {path: [nextBlockPath, 0], offset: 0},\n focus: {path: [nextBlockPath, 0], offset: 0},\n })\n\n return\n }\n\n const lastFocusBlockChild =\n focusBlock.children[focusBlock.children.length - 1]\n const atTheEndOfBlock = isEqual(start, {\n path: [...focusBlockPath, focusBlock.children.length - 1],\n offset: editor.isTextSpan(lastFocusBlockChild)\n ? lastFocusBlockChild.text.length\n : 0,\n })\n\n if (atTheEndOfBlock && Range.isCollapsed(editor.selection)) {\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({\n decorators: [],\n listItem: focusBlock.listItem,\n level: focusBlock.level,\n }),\n )\n\n const [nextBlockPath] = Path.next(focusBlockPath)\n\n Transforms.setSelection(editor, {\n anchor: {path: [nextBlockPath, 0], offset: 0},\n focus: {path: [nextBlockPath, 0], offset: 0},\n })\n\n return\n }\n\n const isInTheMiddleOfNode = !atTheStartOfBlock && !atTheEndOfBlock\n\n if (isInTheMiddleOfNode) {\n Editor.withoutNormalizing(editor, () => {\n if (!editor.selection) {\n return\n }\n\n Transforms.splitNodes(editor, {\n at: editor.selection,\n })\n\n const [nextNode, nextNodePath] = Editor.node(\n editor,\n Path.next(focusBlockPath),\n {depth: 1},\n )\n\n Transforms.setSelection(editor, {\n anchor: {path: [...nextNodePath, 0], offset: 0},\n focus: {path: [...nextNodePath, 0], offset: 0},\n })\n\n /**\n * Assign new keys to markDefs that are now split across two blocks\n */\n if (\n editor.isTextBlock(nextNode) &&\n nextNode.markDefs &&\n nextNode.markDefs.length > 0\n ) {\n const newMarkDefKeys = new Map<string, string>()\n\n const prevNodeSpans = Array.from(\n Node.children(editor, focusBlockPath),\n )\n .map((entry) => entry[0])\n .filter((node) => editor.isTextSpan(node))\n const children = Node.children(editor, nextNodePath)\n\n for (const [child, childPath] of children) {\n if (!editor.isTextSpan(child)) {\n continue\n }\n\n const marks = child.marks ?? []\n\n // Go through the marks of the span and figure out if any of\n // them refer to annotations that are also present in the\n // previous block\n for (const mark of marks) {\n if (\n schema.decorators.some((decorator) => decorator.value === mark)\n ) {\n continue\n }\n\n if (\n prevNodeSpans.some((prevNodeSpan) =>\n prevNodeSpan.marks?.includes(mark),\n ) &&\n !newMarkDefKeys.has(mark)\n ) {\n // This annotation is both present in the previous block\n // and this block, so let's assign a new key to it\n newMarkDefKeys.set(mark, keyGenerator())\n }\n }\n\n const newMarks = marks.map(\n (mark) => newMarkDefKeys.get(mark) ?? mark,\n )\n\n // No need to update the marks if they are the same\n if (!isEqual(marks, newMarks)) {\n Transforms.setNodes(\n editor,\n {marks: newMarks},\n {\n at: childPath,\n },\n )\n }\n }\n\n // Time to update all the markDefs that need a new key because\n // they've been split across blocks\n const newMarkDefs = nextNode.markDefs.map((markDef) => ({\n ...markDef,\n _key: newMarkDefKeys.get(markDef._key) ?? markDef._key,\n }))\n\n // No need to update the markDefs if they are the same\n if (!isEqual(nextNode.markDefs, newMarkDefs)) {\n Transforms.setNodes(\n editor,\n {markDefs: newMarkDefs},\n {\n at: nextNodePath,\n match: (node) => editor.isTextBlock(node),\n },\n )\n }\n }\n })\n editor.onChange()\n return\n }\n }\n}\n\nexport const insertSoftBreakActionImplementation: BehaviourActionImplementation<\n 'insert soft break'\n> = ({context, action}) => {\n // This mimics Slate's internal which also just does a regular insert break\n // when soft-breaking\n insertBreakActionImplementation({\n context,\n action: {...action, type: 'insert break'},\n })\n}\n","import {\n deleteBackward,\n deleteForward,\n Editor,\n insertText,\n Transforms,\n} from 'slate'\nimport {ReactEditor} from 'slate-react'\nimport type {PortableTextMemberSchemaTypes} from '../../types/editor'\nimport {toSlateRange} from '../../utils/ranges'\nimport {\n addAnnotationActionImplementation,\n removeAnnotationActionImplementation,\n toggleAnnotationActionImplementation,\n} from '../plugins/createWithEditableAPI'\nimport {\n addDecoratorActionImplementation,\n removeDecoratorActionImplementation,\n toggleDecoratorActionImplementation,\n} from '../plugins/createWithPortableTextMarkModel'\nimport {\n insertBreakActionImplementation,\n insertSoftBreakActionImplementation,\n} from './behavior.action.insert-break'\nimport type {\n BehaviorAction,\n BehaviorEvent,\n PickFromUnion,\n} from './behavior.types'\n\nexport type BehaviorActionContext = {\n keyGenerator: () => string\n schema: PortableTextMemberSchemaTypes\n}\n\nexport type BehaviourActionImplementation<\n TBehaviorActionType extends BehaviorAction['type'],\n TReturnType = void,\n> = ({\n context,\n action,\n}: {\n context: BehaviorActionContext\n action: PickFromUnion<BehaviorAction, 'type', TBehaviorActionType>\n}) => TReturnType\n\ntype BehaviourActionImplementations = {\n [TBehaviorActionType in BehaviorAction['type']]: BehaviourActionImplementation<TBehaviorActionType>\n}\n\nconst behaviorActionImplementations: BehaviourActionImplementations = {\n 'annotation.add': addAnnotationActionImplementation,\n 'annotation.remove': removeAnnotationActionImplementation,\n 'annotation.toggle': toggleAnnotationActionImplementation,\n 'decorator.add': addDecoratorActionImplementation,\n 'decorator.remove': removeDecoratorActionImplementation,\n 'decorator.toggle': toggleDecoratorActionImplementation,\n 'focus': ({action}) => {\n ReactEditor.focus(action.editor)\n },\n 'set block': ({action}) => {\n for (const path of action.paths) {\n const at = toSlateRange(\n {anchor: {path, offset: 0}, focus: {path, offset: 0}},\n action.editor,\n )!\n\n Transforms.setNodes(\n action.editor,\n {\n ...(action.style ? {style: action.style} : {}),\n ...(action.listItem ? {listItem: action.listItem} : {}),\n ...(action.level ? {level: action.level} : {}),\n },\n {at},\n )\n }\n },\n 'unset block': ({action}) => {\n for (const path of action.paths) {\n const at = toSlateRange(\n {anchor: {path, offset: 0}, focus: {path, offset: 0}},\n action.editor,\n )!\n\n Transforms.unsetNodes(action.editor, action.props, {at})\n }\n },\n 'delete backward': ({action}) => {\n deleteBackward(action.editor, action.unit)\n },\n 'delete forward': ({action}) => {\n deleteForward(action.editor, action.unit)\n },\n 'delete': ({action}) => {\n const location = toSlateRange(action.selection, action.editor)\n\n if (!location) {\n console.error(\n `Could not find Slate location from selection ${action.selection}`,\n )\n return\n }\n\n if (location.anchor.path.length === 1 && location.focus.path.length === 1) {\n Transforms.removeNodes(action.editor, {\n at: location,\n })\n } else {\n Transforms.delete(action.editor, {\n at: location,\n })\n }\n },\n 'insert break': insertBreakActionImplementation,\n 'insert soft break': insertSoftBreakActionImplementation,\n 'insert text': ({action}) => {\n insertText(action.editor, action.text)\n },\n 'insert text block': ({context, action}) => {\n Editor.insertNode(action.editor, {\n _key: context.keyGenerator(),\n _type: context.schema.block.name,\n style: context.schema.styles[0].value ?? 'normal',\n markDefs: [],\n children: [\n {\n _key: context.keyGenerator(),\n _type: 'span',\n text: '',\n },\n ],\n })\n },\n 'effect': ({action}) => {\n action.effect()\n },\n 'select': ({action}) => {\n const newSelection = toSlateRange(action.selection, action.editor)\n\n if (newSelection) {\n Transforms.select(action.editor, newSelection)\n } else {\n Transforms.deselect(action.editor)\n }\n },\n 'reselect': ({action}) => {\n const selection = action.editor.selection\n\n if (selection) {\n Transforms.select(action.editor, {...selection})\n action.editor.selection = {...selection}\n }\n },\n}\n\nexport function performAction({\n context,\n action,\n}: {\n context: BehaviorActionContext\n action: BehaviorAction\n}) {\n switch (action.type) {\n case 'delete': {\n behaviorActionImplementations.delete({\n context,\n action,\n })\n break\n }\n case 'insert text block': {\n behaviorActionImplementations['insert text block']({\n context,\n action,\n })\n break\n }\n case 'set block': {\n behaviorActionImplementations['set block']({\n context,\n action,\n })\n break\n }\n case 'unset block': {\n behaviorActionImplementations['unset block']({\n context,\n action,\n })\n break\n }\n case 'effect': {\n behaviorActionImplementations.effect({\n context,\n action,\n })\n break\n }\n case 'select': {\n behaviorActionImplementations.select({\n context,\n action,\n })\n break\n }\n case 'reselect': {\n behaviorActionImplementations.reselect({\n context,\n action,\n })\n break\n }\n default: {\n performDefaultAction({context, action})\n }\n }\n}\n\nfunction performDefaultAction({\n context,\n action,\n}: {\n context: BehaviorActionContext\n action: PickFromUnion<BehaviorAction, 'type', BehaviorEvent['type']>\n}) {\n switch (action.type) {\n case 'annotation.add': {\n behaviorActionImplementations['annotation.add']({\n context,\n action,\n })\n break\n }\n case 'annotation.remove': {\n behaviorActionImplementations['annotation.remove']({\n context,\n action,\n })\n break\n }\n case 'annotation.toggle': {\n behaviorActionImplementations['annotation.toggle']({\n context,\n action,\n })\n break\n }\n case 'decorator.add': {\n behaviorActionImplementations['decorator.add']({\n context,\n action,\n })\n break\n }\n case 'decorator.remove': {\n behaviorActionImplementations['decorator.remove']({\n context,\n action,\n })\n break\n }\n case 'decorator.toggle': {\n behaviorActionImplementations['decorator.toggle']({\n context,\n action,\n })\n break\n }\n case 'delete backward': {\n behaviorActionImplementations['delete backward']({\n context,\n action,\n })\n break\n }\n case 'delete forward': {\n behaviorActionImplementations['delete forward']({\n context,\n action,\n })\n break\n }\n case 'focus': {\n behaviorActionImplementations.focus({\n context,\n action,\n })\n break\n }\n case 'insert break': {\n behaviorActionImplementations['insert break']({\n context,\n action,\n })\n break\n }\n case 'insert soft break': {\n behaviorActionImplementations['insert soft break']({\n context,\n action,\n })\n break\n }\n default: {\n behaviorActionImplementations['insert text']({\n context,\n action,\n })\n }\n }\n}\n","import type {Patch} from '@portabletext/patches'\nimport type {PortableTextBlock} from '@sanity/types'\nimport type {FocusEvent} from 'react'\nimport {Editor} from 'slate'\nimport {\n assertEvent,\n assign,\n emit,\n enqueueActions,\n fromCallback,\n setup,\n type ActorRefFrom,\n} from 'xstate'\nimport type {\n EditorSelection,\n InvalidValueResolution,\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../types/editor'\nimport {toPortableTextRange} from '../utils/ranges'\nimport {fromSlateValue} from '../utils/values'\nimport {KEY_TO_VALUE_ELEMENT} from '../utils/weakMaps'\nimport {performAction} from './behavior/behavior.actions'\nimport {coreBehaviors} from './behavior/behavior.core'\nimport type {\n Behavior,\n BehaviorAction,\n BehaviorActionIntend,\n BehaviorContext,\n BehaviorEvent,\n PickFromUnion,\n} from './behavior/behavior.types'\n\nexport * from 'xstate/guards'\n\n/**\n * @internal\n */\nexport type EditorActor = ActorRefFrom<typeof editorMachine>\n\nconst networkLogic = fromCallback(({sendBack}) => {\n const onlineHandler = () => {\n sendBack({type: 'online'})\n }\n const offlineHandler = () => {\n sendBack({type: 'offline'})\n }\n\n window.addEventListener('online', onlineHandler)\n window.addEventListener('offline', offlineHandler)\n\n return () => {\n window.removeEventListener('online', onlineHandler)\n window.removeEventListener('offline', offlineHandler)\n }\n})\n\n/**\n * @internal\n */\nexport type PatchEvent = {type: 'patch'; patch: Patch}\n\n/**\n * @internal\n */\nexport type PatchesEvent = {\n type: 'patches'\n patches: Array<Patch>\n snapshot: Array<PortableTextBlock> | undefined\n}\n\n/**\n * @internal\n */\nexport type MutationEvent = {\n type: 'mutation'\n patches: Array<Patch>\n snapshot: Array<PortableTextBlock> | undefined\n}\n\n/**\n * @internal\n */\nexport type InternalEditorEvent =\n | {type: 'normalizing'}\n | {type: 'done normalizing'}\n | {\n type: 'behavior event'\n behaviorEvent: BehaviorEvent\n editor: PortableTextSlateEditor\n }\n | {\n type: 'behavior action intends'\n editor: PortableTextSlateEditor\n actionIntends: Array<BehaviorActionIntend>\n }\n | {\n type: 'update schema'\n schema: PortableTextMemberSchemaTypes\n }\n | {\n type: 'update behaviors'\n behaviors: Array<Behavior>\n }\n | {\n type: 'toggle readOnly'\n }\n | {\n type: 'update maxBlocks'\n maxBlocks: number | undefined\n }\n | InternalEditorEmittedEvent\n\n/**\n * @internal\n */\nexport type InternalEditorEmittedEvent =\n | {type: 'ready'}\n | PatchEvent\n | PatchesEvent\n | MutationEvent\n | {\n type: 'unset'\n previousValue: Array<PortableTextBlock>\n }\n | {\n type: 'value changed'\n value: Array<PortableTextBlock> | undefined\n }\n | {\n type: 'invalid value'\n resolution: InvalidValueResolution | null\n value: Array<PortableTextBlock> | undefined\n }\n | {\n type: 'error'\n name: string\n description: string\n data: unknown\n }\n | {type: 'selection'; selection: EditorSelection}\n | {type: 'blur'; event: FocusEvent<HTMLDivElement, Element>}\n | {type: 'focused'; event: FocusEvent<HTMLDivElement, Element>}\n | {type: 'online'}\n | {type: 'offline'}\n | {type: 'loading'}\n | {type: 'done loading'}\n | PickFromUnion<\n BehaviorEvent,\n 'type',\n 'annotation.add' | 'annotation.remove' | 'annotation.toggle' | 'focus'\n >\n\n/**\n * @internal\n */\nexport const editorMachine = setup({\n types: {\n context: {} as {\n behaviors: Array<Behavior>\n keyGenerator: () => string\n pendingEvents: Array<PatchEvent | MutationEvent>\n schema: PortableTextMemberSchemaTypes\n readOnly: boolean\n maxBlocks: number | undefined\n },\n events: {} as InternalEditorEvent,\n emitted: {} as InternalEditorEmittedEvent,\n input: {} as {\n behaviors?: Array<Behavior>\n keyGenerator: () => string\n schema: PortableTextMemberSchemaTypes\n },\n },\n actions: {\n 'assign behaviors': assign({\n behaviors: ({event}) => {\n assertEvent(event, 'update behaviors')\n return event.behaviors\n },\n }),\n 'assign schema': assign({\n schema: ({event}) => {\n assertEvent(event, 'update schema')\n return event.schema\n },\n }),\n 'emit patch event': emit(({event}) => {\n assertEvent(event, 'patch')\n return event\n }),\n 'emit mutation event': emit(({event}) => {\n assertEvent(event, 'mutation')\n return event\n }),\n 'defer event': assign({\n pendingEvents: ({context, event}) => {\n assertEvent(event, ['patch', 'mutation'])\n return [...context.pendingEvents, event]\n },\n }),\n 'emit pending events': enqueueActions(({context, enqueue}) => {\n for (const event of context.pendingEvents) {\n enqueue(emit(event))\n }\n }),\n 'clear pending events': assign({\n pendingEvents: [],\n }),\n 'handle behavior event': enqueueActions(({context, event, enqueue}) => {\n assertEvent(event, ['behavior event'])\n\n const defaultAction = {\n ...event.behaviorEvent,\n editor: event.editor,\n } satisfies BehaviorAction\n\n const eventBehaviors = context.behaviors.filter(\n (behavior) => behavior.on === event.behaviorEvent.type,\n )\n\n if (eventBehaviors.length === 0) {\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends: [defaultAction],\n })\n return\n }\n\n const value = fromSlateValue(\n event.editor.children,\n context.schema.block.name,\n KEY_TO_VALUE_ELEMENT.get(event.editor),\n )\n const selection = toPortableTextRange(\n value,\n event.editor.selection,\n context.schema,\n )\n\n if (!selection) {\n console.warn(\n `Unable to handle event ${event.type} due to missing selection`,\n )\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends: [defaultAction],\n })\n return\n }\n\n const behaviorContext = {\n schema: context.schema,\n value,\n selection,\n } satisfies BehaviorContext\n\n let behaviorOverwritten = false\n\n for (const eventBehavior of eventBehaviors) {\n const shouldRun =\n eventBehavior.guard?.({\n context: behaviorContext,\n event: event.behaviorEvent,\n }) ?? true\n\n if (!shouldRun) {\n continue\n }\n\n const actionIntendSets = eventBehavior.actions.map((actionSet) =>\n actionSet(\n {context: behaviorContext, event: event.behaviorEvent},\n shouldRun,\n ),\n )\n\n for (const actionIntends of actionIntendSets) {\n behaviorOverwritten =\n actionIntends.length > 0 &&\n actionIntends.some((actionIntend) => actionIntend.type !== 'effect')\n\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends,\n })\n }\n\n if (behaviorOverwritten) {\n break\n }\n }\n\n if (!behaviorOverwritten) {\n enqueue.raise({\n type: 'behavior action intends',\n editor: event.editor,\n actionIntends: [defaultAction],\n })\n }\n }),\n },\n actors: {\n networkLogic,\n },\n}).createMachine({\n id: 'editor',\n context: ({input}) => ({\n behaviors: input.behaviors ?? coreBehaviors,\n keyGenerator: input.keyGenerator,\n pendingEvents: [],\n schema: input.schema,\n readOnly: false,\n maxBlocks: undefined,\n }),\n invoke: {\n id: 'networkLogic',\n src: 'networkLogic',\n },\n on: {\n 'annotation.add': {\n actions: emit(({event}) => event),\n guard: ({context}) => !context.readOnly,\n },\n 'annotation.remove': {\n actions: emit(({event}) => event),\n guard: ({context}) => !context.readOnly,\n },\n 'annotation.toggle': {\n actions: emit(({event}) => event),\n guard: ({context}) => !context.readOnly,\n },\n 'focus': {\n actions: emit(({event}) => event),\n guard: ({context}) => !context.readOnly,\n },\n 'ready': {actions: emit(({event}) => event)},\n 'unset': {actions: emit(({event}) => event)},\n 'value changed': {actions: emit(({event}) => event)},\n 'invalid value': {actions: emit(({event}) => event)},\n 'error': {actions: emit(({event}) => event)},\n 'selection': {actions: emit(({event}) => event)},\n 'blur': {actions: emit(({event}) => event)},\n 'focused': {actions: emit(({event}) => event)},\n 'online': {actions: emit({type: 'online'})},\n 'offline': {actions: emit({type: 'offline'})},\n 'loading': {actions: emit({type: 'loading'})},\n 'patches': {actions: emit(({event}) => event)},\n 'done loading': {actions: emit({type: 'done loading'})},\n 'update behaviors': {actions: 'assign behaviors'},\n 'update schema': {actions: 'assign schema'},\n 'toggle readOnly': {\n actions: assign({readOnly: ({context}) => !context.readOnly}),\n },\n 'update maxBlocks': {\n actions: assign({maxBlocks: ({event}) => event.maxBlocks}),\n },\n 'behavior event': {\n actions: 'handle behavior event',\n guard: ({context}) => !context.readOnly,\n },\n 'behavior action intends': {\n actions: [\n ({context, event}) => {\n Editor.withoutNormalizing(event.editor, () => {\n for (const actionIntend of event.actionIntends) {\n const action = {\n ...actionIntend,\n editor: event.editor,\n }\n\n performAction({context, action})\n }\n })\n event.editor.onChange()\n },\n enqueueActions(({context, event, enqueue}) => {\n if (\n event.actionIntends.some(\n (actionIntend) => actionIntend.type === 'reselect',\n )\n ) {\n enqueue.raise({\n type: 'selection',\n selection: toPortableTextRange(\n event.editor.children,\n event.editor.selection,\n context.schema,\n ),\n })\n }\n }),\n ],\n },\n },\n initial: 'pristine',\n states: {\n pristine: {\n initial: 'idle',\n states: {\n idle: {\n on: {\n normalizing: {\n target: 'normalizing',\n },\n patch: {\n actions: 'defer event',\n target: '#editor.dirty',\n },\n mutation: {\n actions: 'defer event',\n target: '#editor.dirty',\n },\n },\n },\n normalizing: {\n on: {\n 'done normalizing': {\n target: 'idle',\n },\n 'patch': {\n actions: 'defer event',\n },\n 'mutation': {\n actions: 'defer event',\n },\n },\n },\n },\n },\n dirty: {\n entry: ['emit pending events', 'clear pending events'],\n on: {\n patch: {\n actions: 'emit patch event',\n },\n mutation: {\n actions: 'emit mutation event',\n },\n },\n },\n },\n})\n","import {\n createContext,\n startTransition,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport type {EditorSelection} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\n\n/**\n * A React context for sharing the editor selection.\n */\nconst PortableTextEditorSelectionContext =\n createContext<EditorSelection | null>(null)\n\n/**\n * @public\n * Get the current editor selection from the React context.\n */\nexport const usePortableTextEditorSelection = (): EditorSelection => {\n const selection = useContext(PortableTextEditorSelectionContext)\n\n if (selection === undefined) {\n throw new Error(\n `The \\`usePortableTextEditorSelection\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n return selection\n}\nconst debug = debugWithName('component:PortableTextEditor:SelectionProvider')\nconst debugVerbose = debug.enabled && false\n\n/**\n * @internal\n */\nexport function PortableTextEditorSelectionProvider(\n props: React.PropsWithChildren<{\n editorActor: EditorActor\n }>,\n) {\n const [selection, setSelection] = useState<EditorSelection>(null)\n\n // Subscribe to, and handle changes from the editor\n useEffect(() => {\n debug('Subscribing to selection changes')\n const subscription = props.editorActor.on('selection', (event) => {\n // Set the selection state in a transition, we don't need the state immediately.\n startTransition(() => {\n if (debugVerbose) debug('Setting selection')\n setSelection(event.selection)\n })\n })\n\n return () => {\n debug('Unsubscribing to selection changes')\n subscription.unsubscribe()\n }\n }, [props.editorActor])\n\n return (\n <PortableTextEditorSelectionContext.Provider value={selection}>\n {props.children}\n </PortableTextEditorSelectionContext.Provider>\n )\n}\n","import getRandomValues from 'get-random-values-esm'\n\n/**\n * @public\n */\nexport const defaultKeyGenerator = (): string => randomKey(12)\n\nconst getByteHexTable = (() => {\n let table: any[]\n return () => {\n if (table) {\n return table\n }\n\n table = []\n for (let i = 0; i < 256; ++i) {\n table[i] = (i + 0x100).toString(16).slice(1)\n }\n return table\n }\n})()\n\n// WHATWG crypto RNG - https://w3c.github.io/webcrypto/Overview.html\nfunction whatwgRNG(length = 16) {\n const rnds8 = new Uint8Array(length)\n getRandomValues(rnds8)\n return rnds8\n}\n\nfunction randomKey(length?: number): string {\n const table = getByteHexTable()\n return whatwgRNG(length)\n .reduce((str, n) => str + table[n], '')\n .slice(0, length)\n}\n","import type {\n ArrayDefinition,\n ArraySchemaType,\n Path,\n PortableTextBlock,\n PortableTextChild,\n PortableTextObject,\n} from '@sanity/types'\nimport {\n Component,\n useEffect,\n type MutableRefObject,\n type PropsWithChildren,\n} from 'react'\nimport {Subject} from 'rxjs'\nimport {Slate} from 'slate-react'\nimport {createActor} from 'xstate'\nimport type {\n EditableAPI,\n EditableAPIDeleteOptions,\n EditorChange,\n EditorChanges,\n EditorSelection,\n PatchObservable,\n PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport {debugWithName} from '../utils/debug'\nimport {getPortableTextMemberSchemaTypes} from '../utils/getPortableTextMemberSchemaTypes'\nimport {compileType} from '../utils/schema'\nimport {Synchronizer} from './components/Synchronizer'\nimport {createSlateEditor, type SlateEditor} from './create-slate-editor'\nimport {EditorActorContext} from './editor-actor-context'\nimport {editorMachine, type EditorActor} from './editor-machine'\nimport {PortableTextEditorContext} from './hooks/usePortableTextEditor'\nimport {PortableTextEditorSelectionProvider} from './hooks/usePortableTextEditorSelection'\nimport {defaultKeyGenerator} from './key-generator'\nimport {\n createEditableAPI,\n type AddedAnnotationPaths,\n} from './plugins/createWithEditableAPI'\nimport type {Editor} from './use-editor'\n\nconst debug = debugWithName('component:PortableTextEditor')\n\n/**\n * Props for the PortableTextEditor component\n *\n * @public\n */\nexport type PortableTextEditorProps<\n TEditor extends Editor | undefined = undefined,\n> = PropsWithChildren<\n (TEditor extends Editor\n ? {\n /**\n * @alpha\n */\n editor: TEditor\n }\n : {\n editor?: undefined\n\n /**\n * Function that gets called when the editor changes the value\n */\n onChange: (change: EditorChange) => void\n\n /**\n * Schema type for the portable text field\n */\n schemaType: ArraySchemaType<PortableTextBlock> | ArrayDefinition\n\n /**\n * Maximum number of blocks to allow within the editor\n */\n maxBlocks?: number | string\n\n /**\n * Function used to generate keys for array items (`_key`)\n */\n keyGenerator?: () => string\n\n /**\n * Observable of local and remote patches for the edited value.\n */\n patches$?: PatchObservable\n\n /**\n * Backward compatibility (renamed to patches$).\n */\n incomingPatches$?: PatchObservable\n\n /**\n * Whether or not the editor should be in read-only mode\n */\n readOnly?: boolean\n }) & {\n /**\n * The current value of the portable text field\n */\n value?: PortableTextBlock[]\n\n /**\n * A ref to the editor instance\n */\n editorRef?: MutableRefObject<PortableTextEditor | null>\n }\n>\n\n/**\n * The main Portable Text Editor component.\n * @public\n */\nexport class PortableTextEditor extends Component<\n PortableTextEditorProps<Editor | undefined>\n> {\n public static displayName = 'PortableTextEditor'\n /**\n * An observable of all the editor changes.\n */\n public change$: EditorChanges = new Subject()\n /**\n * A lookup table for all the relevant schema types for this portable text type.\n */\n public schemaTypes: PortableTextMemberSchemaTypes\n /**\n * The editor API (currently implemented with Slate).\n */\n private editable?: EditableAPI\n private editorActor: EditorActor\n private slateEditor: SlateEditor\n\n constructor(props: PortableTextEditorProps) {\n super(props)\n\n if (props.editor) {\n const editor = props.editor as Editor\n this.editorActor = editor._internal.editorActor\n this.editorActor.start()\n this.schemaTypes = this.editorActor.getSnapshot().context.schema\n } else {\n if (!props.schemaType) {\n throw new Error('PortableTextEditor: missing \"schemaType\" property')\n }\n\n if (props.incomingPatches$) {\n console.warn(\n `The prop 'incomingPatches$' is deprecated and renamed to 'patches$'`,\n )\n }\n\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n props.schemaType.hasOwnProperty('jsonType')\n ? props.schemaType\n : compileType(props.schemaType),\n )\n\n this.editorActor = createActor(editorMachine, {\n input: {\n keyGenerator: props.keyGenerator || defaultKeyGenerator,\n schema: this.schemaTypes,\n },\n })\n this.editorActor.start()\n\n if (props.readOnly) {\n this.editorActor.send({\n type: 'toggle readOnly',\n })\n }\n\n if (props.maxBlocks) {\n this.editorActor.send({\n type: 'update maxBlocks',\n maxBlocks:\n props.maxBlocks === undefined\n ? undefined\n : Number.parseInt(props.maxBlocks.toString(), 10),\n })\n }\n }\n this.slateEditor = createSlateEditor({\n editorActor: this.editorActor,\n })\n this.editable = createEditableAPI(\n this.slateEditor.instance,\n this.editorActor,\n )\n }\n\n componentDidUpdate(prevProps: PortableTextEditorProps) {\n // Set up the schema type lookup table again if the source schema type changes\n if (\n !this.props.editor &&\n !prevProps.editor &&\n this.props.schemaType !== prevProps.schemaType\n ) {\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n this.props.schemaType.hasOwnProperty('jsonType')\n ? this.props.schemaType\n : compileType(this.props.schemaType),\n )\n\n this.editorActor.send({\n type: 'update schema',\n schema: this.schemaTypes,\n })\n }\n\n if (!this.props.editor && !prevProps.editor) {\n if (this.props.readOnly !== prevProps.readOnly) {\n this.editorActor.send({\n type: 'toggle readOnly',\n })\n }\n\n if (this.props.maxBlocks !== prevProps.maxBlocks) {\n this.editorActor.send({\n type: 'update maxBlocks',\n maxBlocks:\n this.props.maxBlocks === undefined\n ? undefined\n : Number.parseInt(this.props.maxBlocks.toString(), 10),\n })\n }\n }\n\n if (this.props.editorRef !== prevProps.editorRef && this.props.editorRef) {\n this.props.editorRef.current = this\n }\n }\n\n componentWillUnmount(): void {\n this.slateEditor.destroy()\n }\n\n public setEditable = (editable: EditableAPI) => {\n this.editable = {...this.editable, ...editable}\n }\n\n private getValue = () => {\n if (this.editable) {\n return this.editable.getValue()\n }\n\n return undefined\n }\n\n render() {\n const legacyPatches = !this.props.editor\n ? (this.props.incomingPatches$ ?? this.props.patches$)\n : undefined\n\n return (\n <>\n {legacyPatches ? (\n <RoutePatchesObservableToEditorActor\n editorActor={this.editorActor}\n patches$={legacyPatches}\n />\n ) : null}\n <EditorActorContext.Provider value={this.editorActor}>\n <Slate\n editor={this.slateEditor.instance}\n initialValue={this.slateEditor.initialValue}\n >\n <PortableTextEditorContext.Provider value={this}>\n <PortableTextEditorSelectionProvider\n editorActor={this.editorActor}\n >\n <Synchronizer\n editorActor={this.editorActor}\n getValue={this.getValue}\n onChange={(change) => {\n if (!this.props.editor) {\n this.props.onChange(change)\n }\n /**\n * For backwards compatibility, we relay all changes to the\n * `change$` Subject as well.\n */\n this.change$.next(change)\n }}\n value={this.props.value}\n />\n {this.props.children}\n </PortableTextEditorSelectionProvider>\n </PortableTextEditorContext.Provider>\n </Slate>\n </EditorActorContext.Provider>\n </>\n )\n }\n\n // Static API methods\n static activeAnnotations = (\n editor: PortableTextEditor,\n ): PortableTextObject[] => {\n return editor && editor.editable ? editor.editable.activeAnnotations() : []\n }\n static isAnnotationActive = (\n editor: PortableTextEditor,\n annotationType: PortableTextObject['_type'],\n ): boolean => {\n return editor && editor.editable\n ? editor.editable.isAnnotationActive(annotationType)\n : false\n }\n static addAnnotation = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n value?: {[prop: string]: unknown},\n ): AddedAnnotationPaths | undefined =>\n editor.editable?.addAnnotation(type, value)\n static blur = (editor: PortableTextEditor): void => {\n debug('Host blurred')\n editor.editable?.blur()\n }\n static delete = (\n editor: PortableTextEditor,\n selection: EditorSelection,\n options?: EditableAPIDeleteOptions,\n ) => editor.editable?.delete(selection, options)\n static findDOMNode = (\n editor: PortableTextEditor,\n element: PortableTextBlock | PortableTextChild,\n ) => {\n return editor.editable?.findDOMNode(element)\n }\n static findByPath = (editor: PortableTextEditor, path: Path) => {\n return editor.editable?.findByPath(path) || []\n }\n static focus = (editor: PortableTextEditor): void => {\n debug('Host requesting focus')\n editor.editable?.focus()\n }\n static focusBlock = (editor: PortableTextEditor) => {\n return editor.editable?.focusBlock()\n }\n static focusChild = (\n editor: PortableTextEditor,\n ): PortableTextChild | undefined => {\n return editor.editable?.focusChild()\n }\n static getSelection = (editor: PortableTextEditor) => {\n return editor.editable ? editor.editable.getSelection() : null\n }\n static getValue = (editor: PortableTextEditor) => {\n return editor.editable?.getValue()\n }\n static hasBlockStyle = (editor: PortableTextEditor, blockStyle: string) => {\n return editor.editable?.hasBlockStyle(blockStyle)\n }\n static hasListStyle = (editor: PortableTextEditor, listStyle: string) => {\n return editor.editable?.hasListStyle(listStyle)\n }\n static isCollapsedSelection = (editor: PortableTextEditor) =>\n editor.editable?.isCollapsedSelection()\n static isExpandedSelection = (editor: PortableTextEditor) =>\n editor.editable?.isExpandedSelection()\n static isMarkActive = (editor: PortableTextEditor, mark: string) =>\n editor.editable?.isMarkActive(mark)\n static insertChild = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n value?: {[prop: string]: unknown},\n ): Path | undefined => {\n debug(`Host inserting child`)\n return editor.editable?.insertChild(type, value)\n }\n static insertBlock = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n value?: {[prop: string]: unknown},\n ): Path | undefined => {\n return editor.editable?.insertBlock(type, value)\n }\n static insertBreak = (editor: PortableTextEditor): void => {\n return editor.editable?.insertBreak()\n }\n static isVoid = (\n editor: PortableTextEditor,\n element: PortableTextBlock | PortableTextChild,\n ) => {\n return editor.editable?.isVoid(element)\n }\n static isObjectPath = (_editor: PortableTextEditor, path: Path): boolean => {\n if (!path || !Array.isArray(path)) return false\n const isChildObjectEditPath = path.length > 3 && path[1] === 'children'\n const isBlockObjectEditPath = path.length > 1 && path[1] !== 'children'\n return isBlockObjectEditPath || isChildObjectEditPath\n }\n static marks = (editor: PortableTextEditor) => {\n return editor.editable?.marks()\n }\n static select = (\n editor: PortableTextEditor,\n selection: EditorSelection | null,\n ) => {\n debug(`Host setting selection`, selection)\n editor.editable?.select(selection)\n }\n static removeAnnotation = <TSchemaType extends {name: string}>(\n editor: PortableTextEditor,\n type: TSchemaType,\n ) => editor.editable?.removeAnnotation(type)\n static toggleBlockStyle = (\n editor: PortableTextEditor,\n blockStyle: string,\n ) => {\n debug(`Host is toggling block style`)\n return editor.editable?.toggleBlockStyle(blockStyle)\n }\n static toggleList = (editor: PortableTextEditor, listStyle: string): void => {\n return editor.editable?.toggleList(listStyle)\n }\n static toggleMark = (editor: PortableTextEditor, mark: string): void => {\n debug(`Host toggling mark`, mark)\n editor.editable?.toggleMark(mark)\n }\n static getFragment = (\n editor: PortableTextEditor,\n ): PortableTextBlock[] | undefined => {\n debug(`Host getting fragment`)\n return editor.editable?.getFragment()\n }\n static undo = (editor: PortableTextEditor): void => {\n debug('Host undoing')\n editor.editable?.undo()\n }\n static redo = (editor: PortableTextEditor): void => {\n debug('Host redoing')\n editor.editable?.redo()\n }\n static isSelectionsOverlapping = (\n editor: PortableTextEditor,\n selectionA: EditorSelection,\n selectionB: EditorSelection,\n ) => {\n return editor.editable?.isSelectionsOverlapping(selectionA, selectionB)\n }\n}\n\nfunction RoutePatchesObservableToEditorActor(props: {\n editorActor: EditorActor\n patches$: PatchObservable\n}) {\n useEffect(() => {\n const subscription = props.patches$.subscribe((payload) => {\n props.editorActor.send({\n type: 'patches',\n ...payload,\n })\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [props.editorActor, props.patches$])\n\n return null\n}\n","import type {\n Path,\n PortableTextObject,\n PortableTextTextBlock,\n} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {\n startTransition,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactElement,\n} from 'react'\nimport {Text} from 'slate'\nimport {useSelected, type RenderLeafProps} from 'slate-react'\nimport type {\n BlockAnnotationRenderProps,\n BlockChildRenderProps,\n BlockDecoratorRenderProps,\n PortableTextMemberSchemaTypes,\n RenderAnnotationFunction,\n RenderChildFunction,\n RenderDecoratorFunction,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\nimport {usePortableTextEditor} from '../hooks/usePortableTextEditor'\nimport {DefaultAnnotation} from '../nodes/DefaultAnnotation'\nimport {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('components:Leaf')\n\nconst EMPTY_MARKS: string[] = []\n\n/**\n * @internal\n */\nexport interface LeafProps extends RenderLeafProps {\n editorActor: EditorActor\n children: ReactElement\n schemaTypes: PortableTextMemberSchemaTypes\n renderAnnotation?: RenderAnnotationFunction\n renderChild?: RenderChildFunction\n renderDecorator?: RenderDecoratorFunction\n readOnly: boolean\n}\n\n/**\n * Renders Portable Text span nodes in Slate\n * @internal\n */\nexport const Leaf = (props: LeafProps) => {\n const {\n editorActor,\n attributes,\n children,\n leaf,\n schemaTypes,\n renderChild,\n renderDecorator,\n renderAnnotation,\n } = props\n const spanRef = useRef<HTMLElement>(null)\n const portableTextEditor = usePortableTextEditor()\n const blockSelected = useSelected()\n const [focused, setFocused] = useState(false)\n const [selected, setSelected] = useState(false)\n const block = children.props.parent as PortableTextTextBlock | undefined\n const path: Path = useMemo(\n () => (block ? [{_key: block?._key}, 'children', {_key: leaf._key}] : []),\n [block, leaf._key],\n )\n const decoratorValues = useMemo(\n () => schemaTypes.decorators.map((dec) => dec.value),\n [schemaTypes.decorators],\n )\n const marks: string[] = useMemo(\n () =>\n uniq(\n (leaf.marks || EMPTY_MARKS).filter((mark) =>\n decoratorValues.includes(mark),\n ),\n ),\n [decoratorValues, leaf.marks],\n )\n const annotationMarks = Array.isArray(leaf.marks) ? leaf.marks : EMPTY_MARKS\n const annotations = useMemo(\n () =>\n annotationMarks\n .map(\n (mark) =>\n !decoratorValues.includes(mark) &&\n block?.markDefs?.find((def) => def._key === mark),\n )\n .filter(Boolean) as PortableTextObject[],\n [annotationMarks, block, decoratorValues],\n )\n\n const shouldTrackSelectionAndFocus = annotations.length > 0 && blockSelected\n\n useEffect(() => {\n if (!shouldTrackSelectionAndFocus) {\n setFocused(false)\n return\n }\n const sel = PortableTextEditor.getSelection(portableTextEditor)\n if (\n sel &&\n isEqual(sel.focus.path, path) &&\n PortableTextEditor.isCollapsedSelection(portableTextEditor)\n ) {\n startTransition(() => {\n setFocused(true)\n })\n }\n }, [shouldTrackSelectionAndFocus, path, portableTextEditor])\n\n // Function to check if this leaf is currently inside the user's text selection\n const setSelectedFromRange = useCallback(() => {\n if (!shouldTrackSelectionAndFocus) {\n return\n }\n debug('Setting selection and focus from range')\n const winSelection = window.getSelection()\n if (!winSelection) {\n setSelected(false)\n return\n }\n if (winSelection && winSelection.rangeCount > 0) {\n const range = winSelection.getRangeAt(0)\n if (spanRef.current && range.intersectsNode(spanRef.current)) {\n setSelected(true)\n } else {\n setSelected(false)\n }\n } else {\n setSelected(false)\n }\n }, [shouldTrackSelectionAndFocus])\n\n useEffect(() => {\n if (!shouldTrackSelectionAndFocus) {\n return undefined\n }\n\n const onBlur = editorActor.on('blur', () => {\n setFocused(false)\n setSelected(false)\n })\n\n const onFocus = editorActor.on('focus', () => {\n const sel = PortableTextEditor.getSelection(portableTextEditor)\n if (\n sel &&\n isEqual(sel.focus.path, path) &&\n PortableTextEditor.isCollapsedSelection(portableTextEditor)\n ) {\n setFocused(true)\n }\n setSelectedFromRange()\n })\n\n const onSelection = editorActor.on('selection', (event) => {\n if (\n event.selection &&\n isEqual(event.selection.focus.path, path) &&\n PortableTextEditor.isCollapsedSelection(portableTextEditor)\n ) {\n setFocused(true)\n } else {\n setFocused(false)\n }\n setSelectedFromRange()\n })\n\n return () => {\n onBlur.unsubscribe()\n onFocus.unsubscribe()\n onSelection.unsubscribe()\n }\n }, [\n editorActor,\n path,\n portableTextEditor,\n setSelectedFromRange,\n shouldTrackSelectionAndFocus,\n ])\n\n useEffect(() => setSelectedFromRange(), [setSelectedFromRange])\n\n const content = useMemo(() => {\n let returnedChildren = children\n // Render text nodes\n if (Text.isText(leaf) && leaf._type === schemaTypes.span.name) {\n marks.forEach((mark) => {\n const schemaType = schemaTypes.decorators.find(\n (dec) => dec.value === mark,\n )\n if (schemaType && renderDecorator) {\n const _props: Omit<BlockDecoratorRenderProps, 'type'> =\n Object.defineProperty(\n {\n children: returnedChildren,\n editorElementRef: spanRef,\n focused,\n path,\n selected,\n schemaType,\n value: mark,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaType\n },\n },\n )\n returnedChildren = renderDecorator(\n _props as BlockDecoratorRenderProps,\n )\n }\n })\n\n if (block && annotations.length > 0) {\n annotations.forEach((annotation) => {\n const schemaType = schemaTypes.annotations.find(\n (t) => t.name === annotation._type,\n )\n if (schemaType) {\n if (renderAnnotation) {\n const _props: Omit<BlockAnnotationRenderProps, 'type'> =\n Object.defineProperty(\n {\n block,\n children: returnedChildren,\n editorElementRef: spanRef,\n focused,\n path,\n selected,\n schemaType,\n value: annotation,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaType\n },\n },\n )\n\n returnedChildren = (\n <span ref={spanRef}>\n {renderAnnotation(_props as BlockAnnotationRenderProps)}\n </span>\n )\n } else {\n returnedChildren = (\n <DefaultAnnotation annotation={annotation}>\n <span ref={spanRef}>{returnedChildren}</span>\n </DefaultAnnotation>\n )\n }\n }\n })\n }\n if (block && renderChild) {\n const child = block.children.find((_child) => _child._key === leaf._key) // Ensure object equality\n if (child) {\n const defaultRendered = <>{returnedChildren}</>\n const _props: Omit<BlockChildRenderProps, 'type'> =\n Object.defineProperty(\n {\n annotations,\n children: defaultRendered,\n editorElementRef: spanRef,\n focused,\n path,\n schemaType: schemaTypes.span,\n selected,\n value: child,\n },\n 'type',\n {\n enumerable: false,\n get() {\n console.warn(\n \"Property 'type' is deprecated, use 'schemaType' instead.\",\n )\n return schemaTypes.span\n },\n },\n )\n returnedChildren = renderChild(_props as BlockChildRenderProps)\n }\n }\n }\n return returnedChildren\n }, [\n annotations,\n block,\n children,\n focused,\n leaf,\n marks,\n path,\n renderAnnotation,\n renderChild,\n renderDecorator,\n schemaTypes.annotations,\n schemaTypes.decorators,\n schemaTypes.span,\n selected,\n ])\n return useMemo(\n () => (\n <span key={leaf._key} {...attributes} ref={spanRef}>\n {content}\n </span>\n ),\n [leaf, attributes, content],\n )\n}\n\nLeaf.displayName = 'Leaf'\n","import {isPortableTextSpan, isPortableTextTextBlock} from '@sanity/types'\nimport {isHotkey} from 'is-hotkey-esm'\nimport type {KeyboardEvent} from 'react'\nimport {Editor, Node, Path, Range, Transforms} from 'slate'\nimport type {ReactEditor} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../../types/editor'\nimport type {HotkeyOptions} from '../../types/options'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport {debugWithName} from '../../utils/debug'\nimport type {EditorActor} from '../editor-machine'\nimport type {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('plugin:withHotKeys')\n\nconst DEFAULT_HOTKEYS: HotkeyOptions = {\n marks: {\n 'mod+b': 'strong',\n 'mod+i': 'em',\n 'mod+u': 'underline',\n \"mod+'\": 'code',\n },\n custom: {},\n}\n\n/**\n * This plugin takes care of all hotkeys in the editor\n *\n */\nexport function createWithHotkeys(\n editorActor: EditorActor,\n portableTextEditor: PortableTextEditor,\n hotkeysFromOptions?: HotkeyOptions,\n): (editor: PortableTextSlateEditor & ReactEditor) => any {\n const reservedHotkeys = ['enter', 'tab', 'shift', 'delete', 'end']\n const activeHotkeys = hotkeysFromOptions || DEFAULT_HOTKEYS // TODO: Merge where possible? A union?\n return function withHotKeys(editor: PortableTextSlateEditor & ReactEditor) {\n editor.pteWithHotKeys = (event: KeyboardEvent<HTMLDivElement>): void => {\n // Wire up custom marks hotkeys\n Object.keys(activeHotkeys).forEach((cat) => {\n if (cat === 'marks') {\n for (const hotkey in activeHotkeys[cat]) {\n if (reservedHotkeys.includes(hotkey)) {\n throw new Error(`The hotkey ${hotkey} is reserved!`)\n }\n if (isHotkey(hotkey, event.nativeEvent)) {\n event.preventDefault()\n const possibleMark = activeHotkeys[cat]\n if (possibleMark) {\n const mark = possibleMark[hotkey]\n debug(`HotKey ${hotkey} to toggle ${mark}`)\n editorActor.send({\n type: 'behavior event',\n behaviorEvent: {\n type: 'decorator.toggle',\n decorator: mark,\n },\n editor,\n })\n }\n }\n }\n }\n if (cat === 'custom') {\n for (const hotkey in activeHotkeys[cat]) {\n if (reservedHotkeys.includes(hotkey)) {\n throw new Error(`The hotkey ${hotkey} is reserved!`)\n }\n if (isHotkey(hotkey, event.nativeEvent)) {\n const possibleCommand = activeHotkeys[cat]\n if (possibleCommand) {\n const command = possibleCommand[hotkey]\n command(event, portableTextEditor)\n }\n }\n }\n }\n })\n\n const isEnter = isHotkey('enter', event.nativeEvent)\n const isTab = isHotkey('tab', event.nativeEvent)\n const isShiftEnter = isHotkey('shift+enter', event.nativeEvent)\n const isShiftTab = isHotkey('shift+tab', event.nativeEvent)\n const isArrowDown = isHotkey('down', event.nativeEvent)\n const isArrowUp = isHotkey('up', event.nativeEvent)\n\n // Check if the user is in a void block, in that case, add an empty text block below if there is no next block\n if (isArrowDown && editor.selection) {\n const focusBlock = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n ) as SlateTextBlock | VoidElement\n\n if (focusBlock && Editor.isVoid(editor, focusBlock)) {\n const nextPath = Path.next(editor.selection.focus.path.slice(0, 1))\n const nextBlock = Node.has(editor, nextPath)\n if (!nextBlock) {\n Transforms.insertNodes(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n {\n at: nextPath,\n },\n )\n Transforms.select(editor, {path: [...nextPath, 0], offset: 0})\n editor.onChange()\n return\n }\n }\n }\n if (isArrowUp && editor.selection) {\n const isFirstBlock = editor.selection.focus.path[0] === 0\n const focusBlock = Node.descendant(\n editor,\n editor.selection.focus.path.slice(0, 1),\n ) as SlateTextBlock | VoidElement\n\n if (isFirstBlock && focusBlock && Editor.isVoid(editor, focusBlock)) {\n Transforms.insertNodes(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n {\n at: [0],\n },\n )\n Transforms.select(editor, {path: [0, 0], offset: 0})\n editor.onChange()\n return\n }\n }\n\n // Tab for lists\n // Only steal tab when we are on a plain text span or we are at the start of the line (fallback if the whole block is annotated or contains a single inline object)\n // Otherwise tab is reserved for accessability for buttons etc.\n if ((isTab || isShiftTab) && editor.selection) {\n const [focusChild] = Editor.node(editor, editor.selection.focus, {\n depth: 2,\n })\n const [focusBlock] = isPortableTextSpan(focusChild)\n ? Editor.node(editor, editor.selection.focus, {depth: 1})\n : []\n const hasAnnotationFocus =\n focusChild &&\n isPortableTextTextBlock(focusBlock) &&\n isPortableTextSpan(focusChild) &&\n (focusChild.marks || ([] as string[])).filter((m) =>\n (focusBlock.markDefs || []).map((def) => def._key).includes(m),\n ).length > 0\n const [start] = Range.edges(editor.selection)\n const atStartOfNode = Editor.isStart(editor, start, start.path)\n\n if (\n focusChild &&\n isPortableTextSpan(focusChild) &&\n (!hasAnnotationFocus || atStartOfNode) &&\n editor.pteIncrementBlockLevels(isShiftTab)\n ) {\n event.preventDefault()\n }\n }\n\n // Deal with enter key combos\n if (isEnter && !isShiftEnter && editor.selection) {\n const focusBlockPath = editor.selection.focus.path.slice(0, 1)\n const focusBlock = Node.descendant(editor, focusBlockPath) as\n | SlateTextBlock\n | VoidElement\n\n // List item enter key\n if (editor.isListBlock(focusBlock)) {\n if (editor.pteEndList()) {\n event.preventDefault()\n }\n return\n }\n }\n }\n return editor\n }\n}\n","import {htmlToBlocks, normalizeBlock} from '@sanity/block-tools'\nimport type {PortableTextBlock, PortableTextChild} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {Editor, Range, Transforms, type Descendant, type Node} from 'slate'\nimport {ReactEditor} from 'slate-react'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {validateValue} from '../../utils/validateValue'\nimport {\n fromSlateValue,\n isEqualToEmptyEditor,\n toSlateValue,\n} from '../../utils/values'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withInsertData')\n\n/**\n * This plugin handles copy/paste in the editor\n *\n */\nexport function createWithInsertData(\n editorActor: EditorActor,\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n return function withInsertData(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const blockTypeName = schemaTypes.block.name\n const spanTypeName = schemaTypes.span.name\n const whitespaceOnPasteMode =\n schemaTypes.block.options.unstable_whitespaceOnPasteMode\n\n const toPlainText = (blocks: PortableTextBlock[]) => {\n return blocks\n .map((block) => {\n if (editor.isTextBlock(block)) {\n return block.children\n .map((child: PortableTextChild) => {\n if (child._type === spanTypeName) {\n return child.text\n }\n return `[${\n schemaTypes.inlineObjects.find((t) => t.name === child._type)\n ?.title || 'Object'\n }]`\n })\n .join('')\n }\n return `[${\n schemaTypes.blockObjects.find((t) => t.name === block._type)\n ?.title || 'Object'\n }]`\n })\n .join('\\n\\n')\n }\n\n editor.setFragmentData = (data: DataTransfer, originEvent) => {\n const {selection} = editor\n\n if (!selection) {\n return\n }\n\n const [start, end] = Range.edges(selection)\n const startVoid = Editor.void(editor, {at: start.path})\n const endVoid = Editor.void(editor, {at: end.path})\n\n if (Range.isCollapsed(selection) && !startVoid) {\n return\n }\n\n // Create a fake selection so that we can add a Base64-encoded copy of the\n // fragment to the HTML, to decode on future pastes.\n const domRange = ReactEditor.toDOMRange(editor, selection)\n let contents = domRange.cloneContents()\n // COMPAT: If the end node is a void node, we need to move the end of the\n // range from the void node's spacer span, to the end of the void node's\n // content, since the spacer is before void's content in the DOM.\n if (endVoid) {\n const [voidNode] = endVoid\n const r = domRange.cloneRange()\n const domNode = ReactEditor.toDOMNode(editor, voidNode)\n r.setEndAfter(domNode)\n contents = r.cloneContents()\n }\n // Remove any zero-width space spans from the cloned DOM so that they don't\n // show up elsewhere when pasted.\n Array.from(contents.querySelectorAll('[data-slate-zero-width]')).forEach(\n (zw) => {\n const isNewline = zw.getAttribute('data-slate-zero-width') === 'n'\n zw.textContent = isNewline ? '\\n' : ''\n },\n )\n // Clean up the clipboard HTML for editor spesific attributes\n Array.from(contents.querySelectorAll('*')).forEach((elm) => {\n elm.removeAttribute('contentEditable')\n elm.removeAttribute('data-slate-inline')\n elm.removeAttribute('data-slate-leaf')\n elm.removeAttribute('data-slate-node')\n elm.removeAttribute('data-slate-spacer')\n elm.removeAttribute('data-slate-string')\n elm.removeAttribute('data-slate-zero-width')\n elm.removeAttribute('draggable')\n for (const key in elm.attributes) {\n if (elm.hasAttribute(key)) {\n elm.removeAttribute(key)\n }\n }\n })\n const div = contents.ownerDocument.createElement('div')\n div.appendChild(contents)\n div.setAttribute('hidden', 'true')\n contents.ownerDocument.body.appendChild(div)\n const asHTML = div.innerHTML\n contents.ownerDocument.body.removeChild(div)\n const fragment = editor.getFragment()\n const portableText = fromSlateValue(fragment, blockTypeName)\n\n const asJSON = JSON.stringify(portableText)\n const asPlainText = toPlainText(portableText)\n data.clearData()\n data.setData('text/plain', asPlainText)\n data.setData('text/html', asHTML)\n data.setData('application/json', asJSON)\n data.setData('application/x-portable-text', asJSON)\n debug('text', asPlainText)\n data.setData(\n 'application/x-portable-text-event-origin',\n originEvent || 'external',\n )\n debug('Set fragment data', asJSON, asHTML)\n }\n\n editor.insertPortableTextData = (data: DataTransfer): boolean => {\n if (!editor.selection) {\n return false\n }\n const pText = data.getData('application/x-portable-text')\n const origin = data.getData('application/x-portable-text-event-origin')\n debug(`Inserting portable text from ${origin} event`, pText)\n if (pText) {\n const parsed = JSON.parse(pText) as PortableTextBlock[]\n if (Array.isArray(parsed) && parsed.length > 0) {\n const slateValue = _regenerateKeys(\n editor,\n toSlateValue(parsed, {schemaTypes}),\n editorActor.getSnapshot().context.keyGenerator,\n spanTypeName,\n schemaTypes,\n )\n // Validate the result\n const validation = validateValue(\n parsed,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n // Bail out if it's not valid\n if (!validation.valid && !validation.resolution?.autoResolve) {\n const errorDescription = `${validation.resolution?.description}`\n editorActor.send({\n type: 'error',\n name: 'pasteError',\n description: errorDescription,\n data: validation,\n })\n debug('Invalid insert result', validation)\n return false\n }\n _insertFragment(editor, slateValue, schemaTypes)\n return true\n }\n }\n return false\n }\n\n editor.insertTextOrHTMLData = (data: DataTransfer): boolean => {\n if (!editor.selection) {\n debug('No selection, not inserting')\n return false\n }\n const html = data.getData('text/html')\n const text = data.getData('text/plain')\n\n if (html || text) {\n debug('Inserting data', data)\n let portableText: PortableTextBlock[]\n let fragment: Node[]\n let insertedType: string | undefined\n\n if (html) {\n portableText = htmlToBlocks(html, schemaTypes.portableText, {\n unstable_whitespaceOnPasteMode: whitespaceOnPasteMode,\n }).map((block) =>\n normalizeBlock(block, {blockTypeName}),\n ) as PortableTextBlock[]\n fragment = toSlateValue(portableText, {schemaTypes})\n insertedType = 'HTML'\n\n if (portableText.length === 0) {\n return false\n }\n } else {\n // plain text\n const blocks = escapeHtml(text)\n .split(/\\n{2,}/)\n .map((line) =>\n line\n ? `<p>${line.replace(/(?:\\r\\n|\\r|\\n)/g, '<br/>')}</p>`\n : '<p></p>',\n )\n .join('')\n const textToHtml = `<html><body>${blocks}</body></html>`\n portableText = htmlToBlocks(textToHtml, schemaTypes.portableText).map(\n (block) => normalizeBlock(block, {blockTypeName}),\n ) as PortableTextBlock[]\n fragment = toSlateValue(portableText, {\n schemaTypes,\n })\n insertedType = 'text'\n }\n\n // Validate the result\n const validation = validateValue(\n portableText,\n schemaTypes,\n editorActor.getSnapshot().context.keyGenerator,\n )\n\n // Bail out if it's not valid\n if (!validation.valid) {\n const errorDescription = `Could not validate the resulting portable text to insert.\\n${validation.resolution?.description}\\nTry to insert as plain text (shift-paste) instead.`\n editorActor.send({\n type: 'error',\n name: 'pasteError',\n description: errorDescription,\n data: validation,\n })\n debug('Invalid insert result', validation)\n return false\n }\n debug(\n `Inserting ${insertedType} fragment at ${JSON.stringify(editor.selection)}`,\n )\n _insertFragment(editor, fragment, schemaTypes)\n return true\n }\n return false\n }\n\n editor.insertData = (data: DataTransfer) => {\n if (!editor.insertPortableTextData(data)) {\n editor.insertTextOrHTMLData(data)\n }\n }\n\n editor.insertFragmentData = (data: DataTransfer): boolean => {\n const fragment = data.getData('application/x-portable-text')\n if (fragment) {\n const parsed = JSON.parse(fragment)\n editor.insertFragment(parsed)\n return true\n }\n return false\n }\n\n return editor\n }\n}\n\nconst entityMap: Record<string, string> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;',\n}\nfunction escapeHtml(str: string) {\n return String(str).replace(/[&<>\"'`=/]/g, (s: string) => entityMap[s])\n}\n\n/**\n * Shared helper function to regenerate the keys on a fragment.\n *\n * @internal\n */\nfunction _regenerateKeys(\n editor: Pick<PortableTextSlateEditor, 'isTextBlock' | 'isTextSpan'>,\n fragment: Descendant[],\n keyGenerator: () => string,\n spanTypeName: string,\n editorTypes: Pick<PortableTextMemberSchemaTypes, 'annotations'>,\n): Descendant[] {\n return fragment.map((node) => {\n const newNode: Descendant = {...node}\n // Ensure the copy has new keys\n if (editor.isTextBlock(newNode)) {\n const annotations = editorTypes.annotations.map((t) => t.name)\n\n // Ensure that if there are no annotations, we remove the markDefs\n if (annotations.length === 0) {\n const {markDefs, ...NewNodeNoDefs} = newNode\n\n return {...NewNodeNoDefs, _key: keyGenerator()}\n }\n\n // Ensure that all annotations are allowed\n const hasForbiddenAnnotations = (newNode.markDefs || []).some((def) => {\n return !annotations.includes(def._type)\n })\n\n // if they have forbidden annotations, we remove them and keep the rest\n if (hasForbiddenAnnotations) {\n const allowedAnnotations = (newNode.markDefs || []).filter((def) => {\n return annotations.includes(def._type)\n })\n\n return {...newNode, markDefs: allowedAnnotations, _key: keyGenerator()}\n }\n\n newNode.markDefs = (newNode.markDefs || []).map((def) => {\n const oldKey = def._key\n const newKey = keyGenerator()\n newNode.children = newNode.children.map((child) =>\n child._type === spanTypeName && editor.isTextSpan(child)\n ? {\n ...child,\n marks:\n child.marks && child.marks.includes(oldKey)\n ? [...child.marks]\n .filter((mark) => mark !== oldKey)\n .concat(newKey)\n : child.marks,\n }\n : child,\n )\n return {...def, _key: newKey}\n })\n }\n const nodeWithNewKeys = {...newNode, _key: keyGenerator()}\n if (editor.isTextBlock(nodeWithNewKeys)) {\n nodeWithNewKeys.children = nodeWithNewKeys.children.map((child) => ({\n ...child,\n _key: keyGenerator(),\n }))\n }\n return nodeWithNewKeys as Descendant\n })\n}\n\n/**\n * Shared helper function to insert the final fragment into the editor\n *\n * @internal\n */\nfunction _insertFragment(\n editor: PortableTextSlateEditor,\n fragment: Descendant[],\n schemaTypes: PortableTextMemberSchemaTypes,\n) {\n editor.withoutNormalizing(() => {\n if (!editor.selection) {\n return\n }\n // Ensure that markDefs for any annotations inside this fragment are copied over to the focused text block.\n const [focusBlock, focusPath] = Editor.node(editor, editor.selection, {\n depth: 1,\n })\n if (editor.isTextBlock(focusBlock) && editor.isTextBlock(fragment[0])) {\n const {markDefs} = focusBlock\n debug(\n 'Mixing markDefs of focusBlock and fragments[0] block',\n markDefs,\n fragment[0].markDefs,\n )\n if (!isEqual(markDefs, fragment[0].markDefs)) {\n Transforms.setNodes(\n editor,\n {\n markDefs: uniq([\n ...(fragment[0].markDefs || []),\n ...(markDefs || []),\n ]),\n },\n {at: focusPath, mode: 'lowest', voids: false},\n )\n }\n }\n\n const isPasteToEmptyEditor = isEqualToEmptyEditor(\n editor.children,\n schemaTypes,\n )\n\n if (isPasteToEmptyEditor) {\n // Special case for pasting directly into an empty editor (a placeholder block).\n // When pasting content starting with multiple empty blocks,\n // `editor.insertFragment` can potentially duplicate the keys of\n // the placeholder block because of operations that happen\n // inside `editor.insertFragment` (involves an `insert_node` operation).\n // However by splitting the placeholder block first in this situation we are good.\n Transforms.splitNodes(editor, {at: [0, 0]})\n editor.insertFragment(fragment)\n Transforms.removeNodes(editor, {at: [0]})\n } else {\n // All other inserts\n editor.insertFragment(fragment)\n }\n })\n\n editor.onChange()\n}\n\n/**\n * functions we don't want to export but want to test\n * @internal\n */\nexport const exportedForTesting = {\n _regenerateKeys,\n}\n","import type {BaseEditor, Operation} from 'slate'\nimport type {ReactEditor} from 'slate-react'\nimport type {PortableTextSlateEditor} from '../types/editor'\n\n// React Compiler considers `slateEditor` as immutable, and opts-out if we do this inline in a useEffect, doing it in a function moves it out of the scope, and opts-in again for the rest of the component.\nexport function withSyncRangeDecorations(\n slateEditor: BaseEditor & ReactEditor & PortableTextSlateEditor,\n syncRangeDecorations: (operation?: Operation) => void,\n) {\n const originalApply = slateEditor.apply\n slateEditor.apply = (op: Operation) => {\n originalApply(op)\n if (op.type !== 'set_selection') {\n syncRangeDecorations(op)\n }\n }\n return () => {\n slateEditor.apply = originalApply\n }\n}\n","import type {PortableTextBlock} from '@sanity/types'\nimport {useSelector} from '@xstate/react'\nimport {isEqual, noop} from 'lodash'\nimport {\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type CSSProperties,\n type FocusEventHandler,\n type KeyboardEvent,\n type MutableRefObject,\n type TextareaHTMLAttributes,\n} from 'react'\nimport {\n Editor,\n Node,\n Path,\n Range as SlateRange,\n Transforms,\n type BaseRange,\n type NodeEntry,\n type Operation,\n type Text,\n} from 'slate'\nimport {\n ReactEditor,\n Editable as SlateEditable,\n useSlate,\n type RenderElementProps,\n type RenderLeafProps,\n} from 'slate-react'\nimport type {\n EditorSelection,\n OnCopyFn,\n OnPasteFn,\n RangeDecoration,\n RenderAnnotationFunction,\n RenderBlockFunction,\n RenderChildFunction,\n RenderDecoratorFunction,\n RenderListItemFunction,\n RenderPlaceholderFunction,\n RenderStyleFunction,\n ScrollSelectionIntoViewFunction,\n} from '../types/editor'\nimport type {HotkeyOptions} from '../types/options'\nimport type {SlateTextBlock, VoidElement} from '../types/slate'\nimport {debugWithName} from '../utils/debug'\nimport {\n moveRangeByOperation,\n toPortableTextRange,\n toSlateRange,\n} from '../utils/ranges'\nimport {normalizeSelection} from '../utils/selection'\nimport {\n fromSlateValue,\n isEqualToEmptyEditor,\n toSlateValue,\n} from '../utils/values'\nimport {Element} from './components/Element'\nimport {Leaf} from './components/Leaf'\nimport {EditorActorContext} from './editor-actor-context'\nimport {usePortableTextEditor} from './hooks/usePortableTextEditor'\nimport {createWithHotkeys} from './plugins/createWithHotKeys'\nimport {createWithInsertData} from './plugins/createWithInsertData'\nimport {PortableTextEditor} from './PortableTextEditor'\nimport {withSyncRangeDecorations} from './withSyncRangeDecorations'\n\nconst debug = debugWithName('component:Editable')\n\nconst PLACEHOLDER_STYLE: CSSProperties = {\n position: 'absolute',\n userSelect: 'none',\n pointerEvents: 'none',\n left: 0,\n right: 0,\n}\n\ninterface BaseRangeWithDecoration extends BaseRange {\n rangeDecoration: RangeDecoration\n}\n\n/**\n * @public\n */\nexport type PortableTextEditableProps = Omit<\n TextareaHTMLAttributes<HTMLDivElement>,\n 'onPaste' | 'onCopy' | 'onBeforeInput'\n> & {\n hotkeys?: HotkeyOptions\n onBeforeInput?: (event: InputEvent) => void\n onPaste?: OnPasteFn\n onCopy?: OnCopyFn\n ref: MutableRefObject<HTMLDivElement | null>\n rangeDecorations?: RangeDecoration[]\n renderAnnotation?: RenderAnnotationFunction\n renderBlock?: RenderBlockFunction\n renderChild?: RenderChildFunction\n renderDecorator?: RenderDecoratorFunction\n renderListItem?: RenderListItemFunction\n renderPlaceholder?: RenderPlaceholderFunction\n renderStyle?: RenderStyleFunction\n scrollSelectionIntoView?: ScrollSelectionIntoViewFunction\n selection?: EditorSelection\n spellCheck?: boolean\n}\n\n/**\n * @public\n */\nexport const PortableTextEditable = forwardRef<\n Omit<HTMLDivElement, 'as' | 'onPaste' | 'onBeforeInput'>,\n PortableTextEditableProps\n>(function PortableTextEditable(props, forwardedRef) {\n const {\n hotkeys,\n onBlur,\n onFocus,\n onBeforeInput,\n onPaste,\n onCopy,\n onClick,\n rangeDecorations,\n renderAnnotation,\n renderBlock,\n renderChild,\n renderDecorator,\n renderListItem,\n renderPlaceholder,\n renderStyle,\n selection: propsSelection,\n scrollSelectionIntoView,\n spellCheck,\n ...restProps\n } = props\n\n const portableTextEditor = usePortableTextEditor()\n const ref = useRef<HTMLDivElement | null>(null)\n const [editableElement, setEditableElement] = useState<HTMLDivElement | null>(\n null,\n )\n const [hasInvalidValue, setHasInvalidValue] = useState(false)\n const [rangeDecorationState, setRangeDecorationsState] = useState<\n BaseRangeWithDecoration[]\n >([])\n\n // Forward ref to parent component\n useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(\n forwardedRef,\n () => ref.current,\n )\n\n const rangeDecorationsRef = useRef(rangeDecorations)\n\n const editorActor = useContext(EditorActorContext)\n const readOnly = useSelector(editorActor, (s) => s.context.readOnly)\n const {schemaTypes} = portableTextEditor\n const slateEditor = useSlate()\n\n const blockTypeName = schemaTypes.block.name\n\n // Output a minimal React editor inside Editable when in readOnly mode.\n // NOTE: make sure all the plugins used here can be safely run over again at any point.\n // There will be a problem if they redefine editor methods and then calling the original method within themselves.\n useMemo(() => {\n // React/UI-specific plugins\n const withInsertData = createWithInsertData(editorActor, schemaTypes)\n\n if (readOnly) {\n debug('Editable is in read only mode')\n return withInsertData(slateEditor)\n }\n const withHotKeys = createWithHotkeys(\n editorActor,\n portableTextEditor,\n hotkeys,\n )\n\n debug('Editable is in edit mode')\n return withInsertData(withHotKeys(slateEditor))\n }, [\n editorActor,\n hotkeys,\n portableTextEditor,\n readOnly,\n schemaTypes,\n slateEditor,\n ])\n\n const renderElement = useCallback(\n (eProps: RenderElementProps) => (\n <Element\n {...eProps}\n readOnly={readOnly}\n renderBlock={renderBlock}\n renderChild={renderChild}\n renderListItem={renderListItem}\n renderStyle={renderStyle}\n schemaTypes={schemaTypes}\n spellCheck={spellCheck}\n />\n ),\n [\n schemaTypes,\n spellCheck,\n readOnly,\n renderBlock,\n renderChild,\n renderListItem,\n renderStyle,\n ],\n )\n\n const renderLeaf = useCallback(\n (\n lProps: RenderLeafProps & {\n leaf: Text & {placeholder?: boolean; rangeDecoration?: RangeDecoration}\n },\n ) => {\n if (lProps.leaf._type === 'span') {\n let rendered = (\n <Leaf\n {...lProps}\n editorActor={editorActor}\n schemaTypes={schemaTypes}\n renderAnnotation={renderAnnotation}\n renderChild={renderChild}\n renderDecorator={renderDecorator}\n readOnly={readOnly}\n />\n )\n if (\n renderPlaceholder &&\n lProps.leaf.placeholder &&\n lProps.text.text === ''\n ) {\n return (\n <>\n <span style={PLACEHOLDER_STYLE} contentEditable={false}>\n {renderPlaceholder()}\n </span>\n {rendered}\n </>\n )\n }\n const decoration = lProps.leaf.rangeDecoration\n if (decoration) {\n rendered = decoration.component({children: rendered})\n }\n return rendered\n }\n return lProps.children\n },\n [\n editorActor,\n readOnly,\n renderAnnotation,\n renderChild,\n renderDecorator,\n renderPlaceholder,\n schemaTypes,\n ],\n )\n\n const restoreSelectionFromProps = useCallback(() => {\n if (propsSelection) {\n debug(`Selection from props ${JSON.stringify(propsSelection)}`)\n const normalizedSelection = normalizeSelection(\n propsSelection,\n fromSlateValue(slateEditor.children, blockTypeName),\n )\n if (normalizedSelection !== null) {\n debug(\n `Normalized selection from props ${JSON.stringify(normalizedSelection)}`,\n )\n const slateRange = toSlateRange(normalizedSelection, slateEditor)\n if (slateRange) {\n Transforms.select(slateEditor, slateRange)\n // Output selection here in those cases where the editor selection was the same, and there are no set_selection operations made.\n // The selection is usually automatically emitted to change$ by the withPortableTextSelections plugin whenever there is a set_selection operation applied.\n if (!slateEditor.operations.some((o) => o.type === 'set_selection')) {\n editorActor.send({\n type: 'selection',\n selection: normalizedSelection,\n })\n }\n slateEditor.onChange()\n }\n }\n }\n }, [blockTypeName, editorActor, propsSelection, slateEditor])\n\n const syncRangeDecorations = useCallback(\n (operation?: Operation) => {\n if (rangeDecorations && rangeDecorations.length > 0) {\n const newSlateRanges: BaseRangeWithDecoration[] = []\n rangeDecorations.forEach((rangeDecorationItem) => {\n const slateRange = toSlateRange(\n rangeDecorationItem.selection,\n slateEditor,\n )\n if (!SlateRange.isRange(slateRange)) {\n if (rangeDecorationItem.onMoved) {\n rangeDecorationItem.onMoved({\n newSelection: null,\n rangeDecoration: rangeDecorationItem,\n origin: 'local',\n })\n }\n return\n }\n let newRange: BaseRange | null | undefined\n if (operation) {\n newRange = moveRangeByOperation(slateRange, operation)\n if (\n (newRange && newRange !== slateRange) ||\n (newRange === null && slateRange)\n ) {\n const value = PortableTextEditor.getValue(portableTextEditor)\n const newRangeSelection = toPortableTextRange(\n value,\n newRange,\n schemaTypes,\n )\n if (rangeDecorationItem.onMoved) {\n rangeDecorationItem.onMoved({\n newSelection: newRangeSelection,\n rangeDecoration: rangeDecorationItem,\n origin: 'local',\n })\n }\n }\n }\n // If the newRange is null, it means that the range is not valid anymore and should be removed\n // If it's undefined, it means that the slateRange is still valid and should be kept\n if (newRange !== null) {\n newSlateRanges.push({\n ...(newRange || slateRange),\n rangeDecoration: rangeDecorationItem,\n })\n }\n })\n if (newSlateRanges.length > 0) {\n setRangeDecorationsState(newSlateRanges)\n return\n }\n }\n setRangeDecorationsState((rangeDecorationState) => {\n // If there's state then we want to reset\n if (rangeDecorationState.length > 0) {\n return []\n }\n // Otherwise we no-op, React will skip a state update if what we return has reference equality to the previous state\n return rangeDecorationState\n })\n },\n [portableTextEditor, rangeDecorations, schemaTypes, slateEditor],\n )\n\n // Restore selection from props when the editor has been initialized properly with it's value\n useEffect(() => {\n const onReady = editorActor.on('ready', () => {\n restoreSelectionFromProps()\n })\n const onInvalidValue = editorActor.on('invalid value', () => {\n setHasInvalidValue(true)\n })\n const onValueChanged = editorActor.on('value changed', () => {\n setHasInvalidValue(false)\n })\n\n return () => {\n onReady.unsubscribe()\n onInvalidValue.unsubscribe()\n onValueChanged.unsubscribe()\n }\n }, [editorActor, restoreSelectionFromProps])\n\n // Restore selection from props when it changes\n useEffect(() => {\n if (propsSelection && !hasInvalidValue) {\n restoreSelectionFromProps()\n }\n }, [hasInvalidValue, propsSelection, restoreSelectionFromProps])\n\n const [syncedRangeDecorations, setSyncedRangeDecorations] = useState(false)\n useEffect(() => {\n if (!syncedRangeDecorations) {\n // We only want this to run once, on mount\n setSyncedRangeDecorations(true)\n syncRangeDecorations()\n }\n }, [syncRangeDecorations, syncedRangeDecorations])\n\n useEffect(() => {\n if (!isEqual(rangeDecorations, rangeDecorationsRef.current)) {\n syncRangeDecorations()\n }\n rangeDecorationsRef.current = rangeDecorations\n }, [rangeDecorations, syncRangeDecorations])\n\n // Sync range decorations after an operation is applied\n useEffect(() => {\n const teardown = withSyncRangeDecorations(slateEditor, syncRangeDecorations)\n return () => teardown()\n }, [slateEditor, syncRangeDecorations])\n\n // Handle from props onCopy function\n const handleCopy = useCallback(\n (event: ClipboardEvent<HTMLDivElement>): void | ReactEditor => {\n if (onCopy) {\n const result = onCopy(event)\n // CopyFn may return something to avoid doing default stuff\n if (result !== undefined) {\n event.preventDefault()\n }\n }\n },\n [onCopy],\n )\n\n // Handle incoming pasting events in the editor\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLDivElement>): Promise<void> | void => {\n event.preventDefault()\n if (!slateEditor.selection) {\n return\n }\n if (!onPaste) {\n debug('Pasting normally')\n slateEditor.insertData(event.clipboardData)\n return\n }\n\n const value = PortableTextEditor.getValue(portableTextEditor)\n const ptRange = toPortableTextRange(\n value,\n slateEditor.selection,\n schemaTypes,\n )\n const path = ptRange?.focus.path || []\n const onPasteResult = onPaste({event, value, path, schemaTypes})\n\n if (onPasteResult === undefined) {\n debug('No result from custom paste handler, pasting normally')\n slateEditor.insertData(event.clipboardData)\n } else {\n // Resolve it as promise (can be either async promise or sync return value)\n editorActor.send({type: 'loading'})\n Promise.resolve(onPasteResult)\n .then((result) => {\n debug('Custom paste function from client resolved', result)\n if (!result || !result.insert) {\n debug('No result from custom paste handler, pasting normally')\n slateEditor.insertData(event.clipboardData)\n } else if (result.insert) {\n slateEditor.insertFragment(\n toSlateValue(result.insert as PortableTextBlock[], {\n schemaTypes,\n }),\n )\n } else {\n console.warn(\n 'Your onPaste function returned something unexpected:',\n result,\n )\n }\n })\n .catch((error) => {\n console.error(error)\n return error\n })\n .finally(() => {\n editorActor.send({type: 'done loading'})\n })\n }\n },\n [editorActor, onPaste, portableTextEditor, schemaTypes, slateEditor],\n )\n\n const handleOnFocus: FocusEventHandler<HTMLDivElement> = useCallback(\n (event) => {\n if (onFocus) {\n onFocus(event)\n }\n if (!event.isDefaultPrevented()) {\n const selection = PortableTextEditor.getSelection(portableTextEditor)\n // Create an editor selection if it does'nt exist\n if (selection === null) {\n Transforms.select(slateEditor, Editor.start(slateEditor, []))\n slateEditor.onChange()\n }\n editorActor.send({type: 'focused', event})\n const newSelection = PortableTextEditor.getSelection(portableTextEditor)\n // If the selection is the same, emit it explicitly here as there is no actual onChange event triggered.\n if (selection === newSelection) {\n editorActor.send({\n type: 'selection',\n selection,\n })\n }\n }\n },\n [editorActor, onFocus, portableTextEditor, slateEditor],\n )\n\n const handleClick = useCallback(\n (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {\n if (onClick) {\n onClick(event)\n }\n // Inserts a new block if it's clicking on the editor, focused on the last block and it's a void element\n if (slateEditor.selection && event.target === event.currentTarget) {\n const [lastBlock, path] = Node.last(slateEditor, [])\n const focusPath = slateEditor.selection.focus.path.slice(0, 1)\n const lastPath = path.slice(0, 1)\n if (Path.equals(focusPath, lastPath)) {\n const node = Node.descendant(slateEditor, path.slice(0, 1)) as\n | SlateTextBlock\n | VoidElement\n if (lastBlock && Editor.isVoid(slateEditor, node)) {\n Transforms.insertNodes(\n slateEditor,\n slateEditor.pteCreateTextBlock({decorators: []}),\n )\n slateEditor.onChange()\n }\n }\n }\n },\n [onClick, slateEditor],\n )\n\n const handleOnBlur: FocusEventHandler<HTMLDivElement> = useCallback(\n (event) => {\n if (onBlur) {\n onBlur(event)\n }\n if (!event.isPropagationStopped()) {\n editorActor.send({type: 'blur', event})\n }\n },\n [editorActor, onBlur],\n )\n\n const handleOnBeforeInput = useCallback(\n (event: InputEvent) => {\n if (onBeforeInput) {\n onBeforeInput(event)\n }\n },\n [onBeforeInput],\n )\n\n // This function will handle unexpected DOM changes inside the Editable rendering,\n // and make sure that we can maintain a stable slateEditor.selection when that happens.\n //\n // For example, if this Editable is rendered inside something that might re-render\n // this component (hidden contexts) while the user is still actively changing the\n // contentEditable, this could interfere with the intermediate DOM selection,\n // which again could be picked up by ReactEditor's event listeners.\n // If that range is invalid at that point, the slate.editorSelection could be\n // set either wrong, or invalid, to which slateEditor will throw exceptions\n // that are impossible to recover properly from or result in a wrong selection.\n //\n // Also the other way around, when the ReactEditor will try to create a DOM Range\n // from the current slateEditor.selection, it may throw unrecoverable errors\n // if the current editor.selection is invalid according to the DOM.\n // If this is the case, default to selecting the top of the document, if the\n // user already had a selection.\n const validateSelection = useCallback(() => {\n if (!slateEditor.selection) {\n return\n }\n const root = ReactEditor.findDocumentOrShadowRoot(slateEditor)\n const {activeElement} = root\n // Return if the editor isn't the active element\n if (ref.current !== activeElement) {\n return\n }\n const window = ReactEditor.getWindow(slateEditor)\n const domSelection = window.getSelection()\n if (!domSelection || domSelection.rangeCount === 0) {\n return\n }\n const existingDOMRange = domSelection.getRangeAt(0)\n try {\n const newDOMRange = ReactEditor.toDOMRange(\n slateEditor,\n slateEditor.selection,\n )\n if (\n newDOMRange.startOffset !== existingDOMRange.startOffset ||\n newDOMRange.endOffset !== existingDOMRange.endOffset\n ) {\n debug('DOM range out of sync, validating selection')\n // Remove all ranges temporary\n domSelection?.removeAllRanges()\n // Set the correct range\n domSelection.addRange(newDOMRange)\n }\n } catch {\n debug(`Could not resolve selection, selecting top document`)\n // Deselect the editor\n Transforms.deselect(slateEditor)\n // Select top document if there is a top block to select\n if (slateEditor.children.length > 0) {\n Transforms.select(slateEditor, [0, 0])\n }\n slateEditor.onChange()\n }\n }, [ref, slateEditor])\n\n // Observe mutations (child list and subtree) to this component's DOM,\n // and make sure the editor selection is valid when that happens.\n useEffect(() => {\n if (editableElement) {\n const mutationObserver = new MutationObserver(validateSelection)\n mutationObserver.observe(editableElement, {\n attributeOldValue: false,\n attributes: false,\n characterData: false,\n childList: true,\n subtree: true,\n })\n return () => {\n mutationObserver.disconnect()\n }\n }\n return undefined\n }, [validateSelection, editableElement])\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (props.onKeyDown) {\n props.onKeyDown(event)\n }\n if (!event.isDefaultPrevented()) {\n slateEditor.pteWithHotKeys(event)\n }\n },\n [props, slateEditor],\n )\n\n const scrollSelectionIntoViewToSlate = useMemo(() => {\n // Use slate-react default scroll into view\n if (scrollSelectionIntoView === undefined) {\n return undefined\n }\n // Disable scroll into view totally\n if (scrollSelectionIntoView === null) {\n return noop\n }\n // Translate PortableTextEditor prop fn to Slate plugin fn\n return (_editor: ReactEditor, domRange: Range) => {\n scrollSelectionIntoView(portableTextEditor, domRange)\n }\n }, [portableTextEditor, scrollSelectionIntoView])\n\n const decorate: (entry: NodeEntry) => BaseRange[] = useCallback(\n ([, path]) => {\n if (isEqualToEmptyEditor(slateEditor.children, schemaTypes)) {\n return [\n {\n anchor: {\n path: [0, 0],\n offset: 0,\n },\n focus: {\n path: [0, 0],\n offset: 0,\n },\n placeholder: true,\n },\n ]\n }\n // Editor node has a path length of 0 (should never be decorated)\n if (path.length === 0) {\n return []\n }\n const result = rangeDecorationState.filter((item) => {\n // Special case in order to only return one decoration for collapsed ranges\n if (SlateRange.isCollapsed(item)) {\n // Collapsed ranges should only be decorated if they are on a block child level (length 2)\n if (path.length !== 2) {\n return false\n }\n return (\n Path.equals(item.focus.path, path) &&\n Path.equals(item.anchor.path, path)\n )\n }\n // Include decorations that either include or intersects with this path\n return (\n SlateRange.intersection(item, {\n anchor: {path, offset: 0},\n focus: {path, offset: 0},\n }) || SlateRange.includes(item, path)\n )\n })\n if (result.length > 0) {\n return result\n }\n return []\n },\n [slateEditor, schemaTypes, rangeDecorationState],\n )\n\n // Set the forwarded ref to be the Slate editable DOM element\n // Also set the editable element in a state so that the MutationObserver\n // is setup when this element is ready.\n useEffect(() => {\n ref.current = ReactEditor.toDOMNode(\n slateEditor,\n slateEditor,\n ) as HTMLDivElement | null\n setEditableElement(ref.current)\n }, [slateEditor, ref])\n\n if (!portableTextEditor) {\n return null\n }\n return hasInvalidValue ? null : (\n <SlateEditable\n {...restProps}\n autoFocus={false}\n className={restProps.className || 'pt-editable'}\n decorate={decorate}\n onBlur={handleOnBlur}\n onCopy={handleCopy}\n onClick={handleClick}\n onDOMBeforeInput={handleOnBeforeInput}\n onFocus={handleOnFocus}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n readOnly={readOnly}\n // We have implemented our own placeholder logic with decorations.\n // This 'renderPlaceholder' should not be used.\n renderPlaceholder={undefined}\n renderElement={renderElement}\n renderLeaf={renderLeaf}\n scrollSelectionIntoView={scrollSelectionIntoViewToSlate}\n />\n )\n})\n\nPortableTextEditable.displayName = 'ForwardRef(PortableTextEditable)'\n","import type {\n ArrayDefinition,\n ArraySchemaType,\n PortableTextBlock,\n} from '@sanity/types'\nimport {useActorRef, useSelector} from '@xstate/react'\nimport {getPortableTextMemberSchemaTypes} from '../utils/getPortableTextMemberSchemaTypes'\nimport {compileType} from '../utils/schema'\nimport type {Behavior, PickFromUnion} from './behavior/behavior.types'\nimport {compileSchemaDefinition, type SchemaDefinition} from './define-schema'\nimport {\n editorMachine,\n type EditorActor,\n type InternalEditorEvent,\n} from './editor-machine'\nimport {defaultKeyGenerator} from './key-generator'\n\n/**\n * @alpha\n */\nexport type EditorConfig = {\n behaviors?: Array<Behavior>\n keyGenerator?: () => string\n} & (\n | {\n schemaDefinition: SchemaDefinition\n schema?: undefined\n }\n | {\n schemaDefinition?: undefined\n schema: ArraySchemaType<PortableTextBlock> | ArrayDefinition\n }\n)\n\n/**\n * @alpha\n */\nexport type EditorEvent = PickFromUnion<\n InternalEditorEvent,\n 'type',\n | 'annotation.toggle'\n | 'focus'\n | 'patches'\n | 'toggle readOnly'\n | 'update behaviors'\n>\n\n/**\n * @alpha\n */\nexport type Editor = {\n send: (event: EditorEvent) => void\n on: EditorActor['on']\n readOnly: boolean\n _internal: {\n editorActor: EditorActor\n }\n}\n\n/**\n * @alpha\n */\nexport function useEditor(config: EditorConfig): Editor {\n const editorActor = useActorRef(editorMachine, {\n input: {\n behaviors: config.behaviors,\n keyGenerator: config.keyGenerator ?? defaultKeyGenerator,\n schema: config.schemaDefinition\n ? compileSchemaDefinition(config.schemaDefinition)\n : getPortableTextMemberSchemaTypes(\n config.schema.hasOwnProperty('jsonType')\n ? config.schema\n : compileType(config.schema),\n ),\n },\n })\n const readOnly = useSelector(editorActor, (s) => s.context.readOnly)\n\n return {\n send: (event) => {\n editorActor.send(event)\n },\n on: (event, listener) => editorActor.on(event, listener),\n readOnly,\n _internal: {\n editorActor,\n },\n }\n}\n"],"names":["defineBehavior","behavior","selectionIsCollapsed","context","selection","anchor","path","join","focus","offset","getFocusBlock","key","isKeySegment","_key","undefined","node","value","find","block","getFocusTextBlock","focusBlock","isPortableTextTextBlock","getFocusBlockObject","getFocusChild","children","span","getFocusSpan","focusChild","isPortableTextSpan","getSelectionStartBlock","backward","getSelectionEndBlock","getPreviousBlock","previousBlock","selectionStartBlock","foundSelectionStartBlock","getNextBlock","nextBlock","selectionEndBlock","foundSelectionEndBlock","isEmptyTextBlock","length","text","breakingBlockObject","on","guard","actions","type","decorators","deletingEmptyTextBlockAfterBlockObject","focusTextBlock","selectionCollapsed","_","deletingEmptyTextBlockBeforeBlockObject","coreBlockObjectBehaviors","decoratorAdd","event","decorator","decoratorRemove","decoratorToggle","coreDecoratorBehaviors","clearListOnBackspace","focusSpan","level","props","paths","unindentListOnBackspace","coreListBehaviors","softReturn","coreBehaviors","coreBehavior","blockObjects","lists","createMarkdownBehaviors","config","automaticBlockquoteOnSpace","caretAtTheEndOfQuote","looksLikeMarkdownQuote","test","blockquoteStyle","mapBlockquoteStyle","schema","style","automaticHeadingOnSpace","markdownHeadingSearch","exec","headingLevel","headingStyle","mapHeadingStyle","clearStyleOnBackspace","atTheBeginningOfBLock","defaultStyle","mapDefaultStyle","automaticListOnSpace","looksLikeUnorderedList","unorderedListStyle","mapUnorderedListStyle","caretAtTheEndOfUnorderedList","listItem","listItemLength","looksLikeOrderedList","orderedListStyle","mapOrderedListStyle","caretAtTheEndOfOrderedList","getPortableTextMemberSchemaTypes","portableTextType","Error","blockType","of","findBlockType","childrenField","fields","field","name","ofType","spanType","memberType","inlineObjectTypes","filter","blockObjectTypes","styles","resolveEnabledStyles","resolveEnabledDecorators","resolveEnabledListItems","portableText","inlineObjects","annotations","styleField","btField","textStyles","options","list","listField","listItems","defineSchema","definition","compileSchemaDefinition","map","blockObject","defineType","title","icon","inlineObject","portableTextSchema","defineField","marks","startCase","annotation","SanitySchema","compile","types","get","pteSchema","rootName","debug","debugWithName","namespace","enabled","createKeyedPath","point","blockPath","keyedBlockPath","_type","keyedChildPath","childPath","slice","child","Array","isArray","createArrayedPath","editor","from","Editor","nodes","at","match","n","Element","isElement","isVoid","childIndex","findIndex","isEqual","concat","toPortableTextRange","range","anchorPath","focusPath","Boolean","Range","isRange","isBackward","toSlateRange","moveRangeByOperation","operation","Point","transform","equals","normalizePoint","newPath","newOffset","blockKey","childKey","blk","push","cld","normalizeSelection","newAnchor","newFocus","EMPTY_MARKDEFS","VOID_CHILD_KEY","keepObjectEquality","object","keyMap","toSlateValue","schemaTypes","rest","voidChildren","textBlock","hasInlines","hasMissingStyle","hasMissingMarkDefs","markDefs","hasMissingChildren","cType","cKey","cRest","__inline","fromSlateValue","textBlockType","_cType","v","k","t","_i","_c","blockValue","isEqualToEmptyEditor","Text","isText","IS_PROCESSING_REMOTE_CHANGES","WeakMap","IS_PROCESSING_LOCAL_CHANGES","IS_DRAGGING","IS_DRAGGING_BLOCK_ELEMENT","IS_DRAGGING_ELEMENT_TARGET","IS_DRAGGING_BLOCK_TARGET_POSITION","KEY_TO_SLATE_ELEMENT","KEY_TO_VALUE_ELEMENT","SLATE_TO_PORTABLE_TEXT_RANGE","DefaultObject","$","t0","JSON","stringify","t1","displayName","DefaultBlockObject","styled","div","selected","DefaultListItem","getLeftPositionForListLevel","listLevel","getContentForListLevelAndStyle","listStyle","getCounterIncrementForListLevel","getCounterResetForListLevel","getCounterContentForListLevel","DefaultListItemInner","Number","bullets","normalizedLevel","DraggableBlock","element","readOnly","blockRef","useSlateStatic","dragGhostRef","useRef","isDragOver","setIsDragOver","useState","t2","t3","t4","isInline","blockElement","setBlockElement","t5","t6","current","ReactEditor","toDOMNode","useEffect","t7","isMyDragOver","preventDefault","dataTransfer","dropEffect","set","elementRect","getBoundingClientRect","top","height","Y","pageY","loc","Math","abs","handleDragOver","t8","Symbol","for","handleDragLeave","t9","event_0","targetBlock","stopPropagation","delete","document","body","removeChild","dragPosition","targetPath","findPath","myPath","isBefore","Path","originalPath","originalPath_0","Transforms","moveNodes","to","onChange","handleDragEnd","t10","event_1","handleDrop","t11","event_2","target","HTMLElement","opacity","handleDrag","t12","event_3","setData","effectAllowed","dragGhost","cloneNode","customGhost","querySelector","setAttribute","position","left","boxSizing","appendChild","rect","x","clientX","y","clientY","width","setDragImage","handleDragStart","t13","isDraggingOverFirstBlock","t14","isDraggingOverLastBlock","dragPosition_0","isDraggingOverTop","isDraggingOverBottom","t15","t16","borderBottom","zIndex","dropIndicator","t17","t18","t19","EMPTY_ANNOTATIONS","inlineBlockStyle","display","attributes","renderBlock","renderChild","renderListItem","renderStyle","spellCheck","useSelected","inlineBlockObjectRef","focused","isCollapsed","useMemo","renderedBlock","className","depth","schemaType","SlateElement","elmPath","debugRenders","ObjectNode","editorElementRef","isListItem","blockStyleType","item","isListBlock","listType","renderProps","Object","defineProperty","enumerable","warn","propsOrDefaultRendered","renderedBlockFromProps","_props","PortableTextEditorContext","createContext","usePortableTextEditor","useContext","DefaultAnnotation","alert","handleClick","color","compileType","rawType","Schema","validateValue","keyGenerator","resolution","valid","validChildTypes","validBlockTypes","patches","unset","description","action","i18n","some","index","isPlainObject","String","values","includes","currentBlockTypeName","expectedTypeName","typeName","newSpan","autoResolve","setIfMissing","insert","allUsedMarks","uniq","flatten","unusedMarkDefs","def","markDefKey","m","toString","orphanedMarks","mark","dec","spanChildren","orphaned","cMrk","cIndex","newChild","childType","withRemoteChanges","fn","prev","isChangingRemotely","isChangingLocally","PATCHING","withoutPatching","isPatching","isHighSurrogate","char","charCode","charCodeAt","isLowSurrogate","IS_UDOING","IS_REDOING","withUndoing","isUndoing","setIsUndoing","withRedoing","isRedoing","setIsRedoing","debugVerbose","SAVING","REMOTE_PATCHES","UNDO_STEP_LIMIT","isSaving","state","getRemotePatches","createWithUndoRedo","editorActor","blockSchemaType","previousSnapshot","remotePatches","subscriptions","sub","snapshot","reset","forEach","patch","origin","history","undos","redos","splice","time","Date","unsubscribe","apply","op","getSnapshot","operations","step","lastOp","overwrite","shouldOverwrite","save","merge","shouldMerge","newStep","createSelectOperation","timestamp","shift","shouldClear","undo","otherPatches","transformedOperations","transformOperation","reversedOperations","Operation","inverse","reverse","withoutNormalizing","withoutSaving","normalize","err","deselect","pop","redo","transformedOperation","insertBlockIndex","items","adjustBlockPath","unsetBlockIndex","operationTargetBlock","findOperationTargetBlock","parsePatch","diffPatch","adjustOffsetBy","changedOffset","utf8Start1","diffs","diff","diffType","DIFF_INSERT","DIFF_DELETE","DIFF_EQUAL","every","dType","currentFocus","properties","currentAnchor","newProperties","blockIndex","CURRENT_VALUE","useSyncValue","portableTextEditor","previousValue","slateEditor","useSlate","updateValueFunctionRef","updateFromCurrentValue","useCallback","currentValue","updateValueDebounced","debounce","trailing","leading","updateFunction","isProcessingLocalChanges","isProcessingRemoteChanges","isChanged","isValid","hadSelection","childrenLength","removeNodes","insertNodes","pteCreateTextBlock","select","slateValueFromProps","i","currentBlock","currentBlockIndex","oldBlock","validationValue","validation","console","send","_updateBlock","_replaceBlock","error","currentSelection","selectionFocusOnBlock","setNodes","isTextBlock","oldBlockChildrenLength","currentBlockChild","currentBlockChildIndex","oldBlockChild","isChildChanged","isTextChanged","isSpanNode","insertText","voids","FLUSH_PATCHES_THROTTLED_MS","process","env","NODE_ENV","Synchronizer","useSelector","_temp","getValue","pendingPatches","syncValue","onFlushPendingPatches","change","handleChange","useEffectEvent","onFlushPendingPatchesThrottled","throttle","isNormalizing","bb20","isLoading","handleOnline","subscription","isInitialValueFromProps","s","createOperationToPatches","textBlockName","insertTextPatch","beforeValue","textChild","isTextSpan","prevBlock","prevChild","prevText","diffMatchPatch","removeTextPatch","beforeBlock","prevTextChild","setNodePatch","setNode","omitBy","isUndefined","keys","keyName","val","indexOf","insertNodePatch","targetKey","splitNodePatch","splitBlock","targetValue","splitSpan","targetSpans","removeNodePatch","spanToRemove","mergeNodePatch","updatedBlock","newBlock","updatedSpan","removedSpan","moveNodePatch","targetChild","childToInsert","createWithEventListeners","maxBlocks","behaviorEvent","addMark","removeMark","deleteBackward","unit","deleteForward","insertBreak","insertSoftBreak","createWithMaxBlocks","rows","createWithObjectKeys","normalizeNode","isEditor","entry","Node","createApplyPatch","changed","insertPatch","unsetPatch","setPatch","findBlockAndChildFromPath","newValue","diffMatchPatchApplyPatches","allowExceedingIndices","cleanupEfficiency","makeDiff","debugState","targetBlockPath","targetChildPath","blocksToInsert","targetBlockIndex","normalizedIdx","childrenToInsert","targetChildIndex","childInsertPath","newText","nextRest","prevChildren","prevRest","c","newVal","applyAll","previousSelection","_child","isKeyedSegment","segment","stateName","findBlockFromPath","isMatch","createWithPatches","patchFunctions","previousChildren","applyPatch","bufferedPatches","handleBufferedRemotePatches","handlePatches","p","editorWasEmpty","editorIsEmpty","createWithPlaceholderBlock","nextPath","next","insertNode","createWithPortableTextBlockStyle","nodeEntry","SlateText","pteHasBlockStyle","pteToggleBlockStyle","blockStyle","MAX_LIST_LEVEL","createWithPortableTextLists","pteToggleListItem","listItemStyle","pteHasListStyle","pteUnsetListItem","pteSetListItem","newNode","pteEndList","selectedBlocks","pteIncrementBlockLevels","min","max","isPortableTextBlock","getPreviousSpan","spanPath","previousSpan","getNextSpan","nextSpan","isAfter","createWithPortableTextMarkModel","nextNode","mergeNodes","parent","orphanedAnnotations","markDefKeys","Set","newMarkDefs","markDef","has","add","previousSelectionIsCollapsed","newSelectionIsCollapsed","mode","newFocusSpan","movedToNextSpan","movedToPreviousSpan","_block","previousSpanAnnotations","nextSpanAnnotations","annotationsEnding","atTheEndOfAnnotation","annotationsStarting","atTheStartOfAnnotation","nextSpanDecorators","collapsedSelection","marksWithoutAnnotations","spanHasAnnotations","spanIsEmpty","atTheBeginningOfSpan","atTheEndOfSpan","spanAnnotations","previousSpanHasAnnotations","previousSpanHasSameAnnotations","previousSpanHasSameAnnotation","previousSpanHasSameMarks","nextSpanSharesSomeAnnotations","isExpanded","deletingFromTheEnd","deletingAllText","nextSpanHasSameAnnotation","marksWithoutAnnotationMarks","oldDefs","addDecoratorActionImplementation","split","hanging","splitTextNodes","eMark","lonelyEmptySpan","existingMarks","existingMarksWithoutDecorator","existingMark","removeDecoratorActionImplementation","isDecoratorActive","selectedNodes","toggleDecoratorActionImplementation","createWithPortableTextSelections","prevSelection","emitPortableTextSelection","ptRange","existing","hasChanges","createWithSchemaTypes","isPortableTextListBlock","obj","createWithUtils","pteExpandToWord","textNode","focusOffset","charsBefore","charsAfter","isEmpty","str","whiteSpaceBeforeIndex","newStartOffset","whiteSpaceAfterIndex","newEndOffset","isNaN","setSelection","originalFnMap","withPlugins","e","destroy","operationToPatches","withObjectKeys","withSchemaTypes","withPatches","withMaxBlocks","withPortableTextLists","withUndoRedo","withPortableTextMarkModel","withPortableTextBlockStyle","withPlaceholderBlock","withUtils","withPortableTextSelections","withEventListeners","originalFunctions","slateEditors","createSlateEditor","existingSlateEditor","id","unsubscriptions","instance","withReact","createEditor","initialValue","EditorActorContext","createEditableAPI","blur","toggleMark","toggleList","toggleBlockStyle","isMarkActive","slateSelection","descendant","insertChild","focusChildPath","focusNode","move","distance","insertBlock","lastBlock","hasBlockStyle","hasListStyle","findByPath","slatePath","ptBlock","ptChild","findDOMNode","activeAnnotations","spans","isAnnotationActive","annotationType","addAnnotation","addAnnotationActionImplementation","removeAnnotation","getSelection","isCollapsedSelection","isExpandedSelection","getFragment","isSelectionsOverlapping","selectionA","selectionB","rangeA","rangeB","selectionMarkDefs","reduce","accMarkDefs","markKey","originalSelection","markDefPath","markDefPaths","annotationKey","unshift","existingSameTypeAnnotations","removeAnnotationActionImplementation","potentialAnnotations","selectedChild","selectedChildPath","annotationToRemove","previousSpansWithSameAnnotation","SlatePath","nextSpansWithSameAnnotation","blocks","marksWithoutAnnotation","toggleAnnotationActionImplementation","insertBreakActionImplementation","focusDecorators","focusAnnotations","focusBlockPath","start","end","edges","atTheStartOfBlock","nextBlockPath","lastFocusBlockChild","atTheEndOfBlock","splitNodes","nextNodePath","newMarkDefKeys","Map","prevNodeSpans","prevNodeSpan","newMarks","insertSoftBreakActionImplementation","behaviorActionImplementations","set block","unset block","unsetNodes","delete backward","delete forward","location","insert text","insert text block","effect","newSelection","reselect","performAction","performDefaultAction","networkLogic","fromCallback","sendBack","onlineHandler","offlineHandler","addEventListener","window","removeEventListener","editorMachine","setup","events","emitted","input","assign","behaviors","assertEvent","emit","pendingEvents","enqueueActions","enqueue","defaultAction","eventBehaviors","raise","actionIntends","behaviorContext","behaviorOverwritten","eventBehavior","shouldRun","actionIntendSets","actionSet","actionIntend","actors","createMachine","invoke","src","initial","states","pristine","idle","normalizing","mutation","dirty","PortableTextEditorSelectionContext","usePortableTextEditorSelection","PortableTextEditorSelectionProvider","startTransition","defaultKeyGenerator","randomKey","getByteHexTable","table","whatwgRNG","rnds8","Uint8Array","getRandomValues","PortableTextEditor","Component","change$","Subject","constructor","_internal","incomingPatches$","hasOwnProperty","createActor","parseInt","editable","componentDidUpdate","prevProps","editorRef","componentWillUnmount","setEditable","render","legacyPatches","patches$","isObjectPath","_editor","isChildObjectEditPath","RoutePatchesObservableToEditorActor","subscribe","payload","EMPTY_MARKS","Leaf","leaf","renderDecorator","renderAnnotation","spanRef","blockSelected","setFocused","setSelected","decoratorValues","annotationMarks","shouldTrackSelectionAndFocus","sel","setSelectedFromRange","winSelection","rangeCount","getRangeAt","intersectsNode","onBlur","onFocus","onSelection","content","returnedChildren","DEFAULT_HOTKEYS","custom","createWithHotkeys","hotkeysFromOptions","reservedHotkeys","activeHotkeys","pteWithHotKeys","cat","hotkey","isHotkey","nativeEvent","possibleMark","possibleCommand","command","isEnter","isTab","isShiftEnter","isShiftTab","isArrowDown","isArrowUp","isFirstBlock","hasAnnotationFocus","atStartOfNode","isStart","createWithInsertData","blockTypeName","spanTypeName","whitespaceOnPasteMode","unstable_whitespaceOnPasteMode","toPlainText","setFragmentData","data","originEvent","startVoid","void","endVoid","domRange","toDOMRange","contents","cloneContents","voidNode","r","cloneRange","domNode","setEndAfter","querySelectorAll","zw","isNewline","getAttribute","textContent","elm","removeAttribute","hasAttribute","ownerDocument","createElement","asHTML","innerHTML","fragment","asJSON","asPlainText","clearData","insertPortableTextData","pText","getData","parsed","parse","slateValue","_regenerateKeys","errorDescription","insertTextOrHTMLData","html","insertedType","htmlToBlocks","normalizeBlock","textToHtml","escapeHtml","line","replace","_insertFragment","insertData","insertFragmentData","insertFragment","entityMap","editorTypes","NewNodeNoDefs","allowedAnnotations","oldKey","newKey","nodeWithNewKeys","withSyncRangeDecorations","syncRangeDecorations","originalApply","PLACEHOLDER_STYLE","userSelect","pointerEvents","right","PortableTextEditable","forwardRef","forwardedRef","hotkeys","onBeforeInput","onPaste","onCopy","onClick","rangeDecorations","renderPlaceholder","propsSelection","scrollSelectionIntoView","restProps","ref","editableElement","setEditableElement","hasInvalidValue","setHasInvalidValue","rangeDecorationState","setRangeDecorationsState","rangeDecorationsRef","withInsertData","withHotKeys","renderElement","eProps","renderLeaf","lProps","rendered","placeholder","decoration","rangeDecoration","component","restoreSelectionFromProps","normalizedSelection","slateRange","o","newSlateRanges","rangeDecorationItem","SlateRange","onMoved","newRange","newRangeSelection","onReady","onInvalidValue","onValueChanged","syncedRangeDecorations","setSyncedRangeDecorations","teardown","handleCopy","handlePaste","clipboardData","onPasteResult","Promise","resolve","then","result","catch","finally","handleOnFocus","isDefaultPrevented","currentTarget","last","lastPath","handleOnBlur","isPropagationStopped","handleOnBeforeInput","validateSelection","root","findDocumentOrShadowRoot","activeElement","domSelection","getWindow","existingDOMRange","newDOMRange","startOffset","endOffset","removeAllRanges","addRange","mutationObserver","MutationObserver","observe","attributeOldValue","characterData","childList","subtree","disconnect","handleKeyDown","onKeyDown","scrollSelectionIntoViewToSlate","noop","decorate","intersection","SlateEditable","useEditor","schemaDefinition","useActorRef","listener"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqLO,SAASA,eAGdC,UAAkE;AAC3DA,SAAAA;AACT;AC1KO,SAASC,qBAAqBC,SAA0B;AAC7D,SACEA,QAAQC,WAAWC,OAAOC,KAAKC,WAC7BJ,QAAQC,WAAWI,MAAMF,KAAKC,UAChCJ,QAAQC,WAAWC,OAAOI,WAAWN,QAAQC,WAAWI,MAAMC;AAElE;AAMO,SAASC,cACdP,SAC6D;AAC7D,QAAMQ,MAAMR,QAAQC,aAChBQ,aAAaT,QAAQC,UAAUI,MAAMF,KAAK,CAAC,CAAC,IAC1CH,QAAQC,UAAUI,MAAMF,KAAK,CAAC,EAAEO,OAElCC,QAEEC,OAAOJ,MACTR,QAAQa,MAAMC,KAAMC,CAAUA,UAAAA,MAAML,SAASF,GAAG,IAChDG;AAEJ,SAAOC,QAAQJ,MAAM;AAAA,IAACI;AAAAA,IAAMT,MAAM,CAAC;AAAA,MAACO,MAAMF;AAAAA,IAAI,CAAA;AAAA,EAAKG,IAAAA;AACrD;AAEO,SAASK,kBACdhB,SACiE;AAC3DiB,QAAAA,aAAaV,cAAcP,OAAO;AAExC,SAAOiB,cAAcC,wBAAwBD,WAAWL,IAAI,IACxD;AAAA,IAACA,MAAMK,WAAWL;AAAAA,IAAMT,MAAMc,WAAWd;AAAAA,EACzCQ,IAAAA;AACN;AAEO,SAASQ,oBACdnB,SAC8D;A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