@portabletext/editor 1.1.0 → 1.1.2

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 (79) hide show
  1. package/README.md +3 -0
  2. package/lib/index.d.mts +1680 -12
  3. package/lib/index.d.ts +1680 -12
  4. package/lib/index.esm.js +310 -162
  5. package/lib/index.esm.js.map +1 -1
  6. package/lib/index.js +310 -163
  7. package/lib/index.js.map +1 -1
  8. package/lib/index.mjs +310 -162
  9. package/lib/index.mjs.map +1 -1
  10. package/package.json +25 -38
  11. package/src/editor/Editable.tsx +51 -50
  12. package/src/editor/PortableTextEditor.tsx +42 -26
  13. package/src/editor/__tests__/PortableTextEditor.test.tsx +11 -12
  14. package/src/editor/__tests__/PortableTextEditorTester.tsx +2 -5
  15. package/src/editor/__tests__/RangeDecorations.test.tsx +6 -7
  16. package/src/editor/__tests__/handleClick.test.tsx +27 -7
  17. package/src/editor/__tests__/insert-block.test.tsx +6 -6
  18. package/src/editor/__tests__/pteWarningsSelfSolving.test.tsx +8 -8
  19. package/src/editor/__tests__/self-solving.test.tsx +176 -0
  20. package/src/editor/components/Element.tsx +15 -17
  21. package/src/editor/components/Leaf.tsx +40 -35
  22. package/src/editor/components/SlateContainer.tsx +2 -2
  23. package/src/editor/components/Synchronizer.tsx +62 -34
  24. package/src/editor/editor-machine.ts +195 -0
  25. package/src/editor/hooks/usePortableTextEditor.ts +1 -1
  26. package/src/editor/hooks/usePortableTextEditorSelection.tsx +12 -14
  27. package/src/editor/hooks/useSyncValue.test.tsx +9 -9
  28. package/src/editor/hooks/useSyncValue.ts +16 -19
  29. package/src/editor/nodes/DefaultAnnotation.tsx +1 -2
  30. package/src/editor/nodes/DefaultObject.tsx +1 -1
  31. package/src/editor/plugins/__tests__/createWithInsertData.test.tsx +2 -5
  32. package/src/editor/plugins/__tests__/withEditableAPIDelete.test.tsx +28 -28
  33. package/src/editor/plugins/__tests__/withEditableAPIGetFragment.test.tsx +17 -17
  34. package/src/editor/plugins/__tests__/withEditableAPIInsert.test.tsx +8 -8
  35. package/src/editor/plugins/__tests__/withEditableAPISelectionsOverlapping.test.tsx +6 -6
  36. package/src/editor/plugins/__tests__/withPortableTextLists.test.tsx +2 -2
  37. package/src/editor/plugins/__tests__/withPortableTextMarkModel.test.tsx +47 -49
  38. package/src/editor/plugins/__tests__/withPortableTextSelections.test.tsx +22 -11
  39. package/src/editor/plugins/__tests__/withUndoRedo.test.tsx +9 -9
  40. package/src/editor/plugins/createWithEditableAPI.ts +8 -8
  41. package/src/editor/plugins/createWithHotKeys.ts +8 -12
  42. package/src/editor/plugins/createWithInsertBreak.ts +4 -4
  43. package/src/editor/plugins/createWithInsertData.ts +11 -16
  44. package/src/editor/plugins/createWithMaxBlocks.ts +1 -1
  45. package/src/editor/plugins/createWithObjectKeys.ts +10 -3
  46. package/src/editor/plugins/createWithPatches.ts +9 -12
  47. package/src/editor/plugins/createWithPlaceholderBlock.ts +2 -2
  48. package/src/editor/plugins/createWithPortableTextBlockStyle.ts +13 -5
  49. package/src/editor/plugins/createWithPortableTextLists.ts +3 -4
  50. package/src/editor/plugins/createWithPortableTextMarkModel.ts +24 -10
  51. package/src/editor/plugins/createWithPortableTextSelections.ts +9 -10
  52. package/src/editor/plugins/createWithSchemaTypes.ts +13 -4
  53. package/src/editor/plugins/createWithUndoRedo.ts +3 -7
  54. package/src/editor/plugins/createWithUtils.ts +6 -6
  55. package/src/editor/plugins/index.ts +21 -11
  56. package/src/index.ts +9 -3
  57. package/src/types/editor.ts +33 -33
  58. package/src/types/options.ts +3 -3
  59. package/src/types/slate.ts +4 -4
  60. package/src/utils/__tests__/dmpToOperations.test.ts +4 -4
  61. package/src/utils/__tests__/operationToPatches.test.ts +62 -62
  62. package/src/utils/__tests__/patchToOperations.test.ts +40 -40
  63. package/src/utils/__tests__/ranges.test.ts +2 -2
  64. package/src/utils/__tests__/valueNormalization.test.tsx +14 -2
  65. package/src/utils/__tests__/values.test.ts +17 -17
  66. package/src/utils/applyPatch.ts +10 -12
  67. package/src/utils/getPortableTextMemberSchemaTypes.ts +8 -8
  68. package/src/utils/operationToPatches.ts +5 -9
  69. package/src/utils/paths.ts +5 -5
  70. package/src/utils/ranges.ts +4 -5
  71. package/src/utils/selection.ts +2 -2
  72. package/src/utils/ucs2Indices.ts +2 -2
  73. package/src/utils/validateValue.ts +3 -25
  74. package/src/utils/values.ts +7 -8
  75. package/src/utils/weakMaps.ts +2 -2
  76. package/src/utils/withChanges.ts +1 -1
  77. package/src/utils/withUndoRedo.ts +1 -1
  78. package/src/utils/withoutPatching.ts +1 -1
  79. package/src/editor/__tests__/utils.ts +0 -45
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../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/getPortableTextMemberSchemaTypes.ts","../src/utils/schema.ts","../src/utils/operationToPatches.ts","../src/editor/plugins/createWithEditableAPI.ts","../src/editor/plugins/createWithInsertBreak.ts","../src/utils/withChanges.ts","../src/utils/withUndoRedo.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","../../../node_modules/.pnpm/@portabletext+toolkit@2.0.15/node_modules/@portabletext/toolkit/dist/index.js","../src/editor/plugins/createWithPortableTextMarkModel.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/usePortableTextEditorKeyGenerator.ts","../src/editor/hooks/usePortableTextReadOnly.ts","../src/editor/hooks/useSyncValue.ts","../src/editor/components/Synchronizer.tsx","../src/editor/hooks/usePortableTextEditorSelection.tsx","../src/editor/PortableTextEditor.tsx","../src/editor/components/Leaf.tsx","../src/editor/Editable.tsx"],"sourcesContent":["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 {\n type EditorSelectionPoint,\n type 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\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","/* eslint-disable complexity */\nimport {Point, Range, type BaseRange, type Editor, type Operation} from 'slate'\nimport {\n type EditorSelection,\n type EditorSelectionPoint,\n type 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, type PortableTextBlock} from '@sanity/types'\nimport {isEqual} from 'lodash'\nimport {type EditorSelection, type 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 {\n type PathSegment,\n type PortableTextBlock,\n type PortableTextChild,\n type PortableTextObject,\n type 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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, type Element, type 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, type 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\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","/* eslint-disable complexity */\n/* eslint-disable max-statements */\nimport {\n type Path,\n type PortableTextChild,\n type PortableTextObject,\n type 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 {\n type BlockRenderProps,\n type PortableTextMemberSchemaTypes,\n type RenderBlockFunction,\n type RenderChildFunction,\n type RenderListItemFunction,\n type 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\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\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\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","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 // eslint-disable-next-line no-alert\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","import {\n type ArraySchemaType,\n type BlockSchemaType,\n type ObjectSchemaType,\n type PortableTextBlock,\n type SchemaType,\n type 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} 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 {\n type Path,\n type PortableTextSpan,\n type PortableTextTextBlock,\n} 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 {\n type PortableTextMemberSchemaTypes,\n type 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 {\n isPortableTextSpan,\n type ObjectSchemaType,\n type Path,\n type PortableTextBlock,\n type PortableTextChild,\n type PortableTextObject,\n type PortableTextSpan,\n type PortableTextTextBlock,\n type SchemaType,\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 {ReactEditor} from 'slate-react'\nimport {type DOMNode} from 'slate-react/dist/utils/dom'\nimport {\n type EditableAPI,\n type EditableAPIDeleteOptions,\n type EditorSelection,\n type PortableTextMemberSchemaTypes,\n type 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 PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('API:editable')\n\nexport function createWithEditableAPI(\n portableTextEditor: PortableTextEditor,\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\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 editor.pteToggleMark(mark)\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 editor.pteIsMarkActive(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: (type: SchemaType, value?: {[prop: string]: any}): 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: keyGenerator(),\n _type: types.block.name,\n children: [\n {\n _key: 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: (type: SchemaType, value?: {[prop: string]: any}): Path => {\n const block = toSlateValue(\n [\n {\n _key: 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 (err) {\n // This is fine.\n // debug(err)\n return false\n }\n },\n hasListStyle: (listStyle: string): boolean => {\n try {\n return editor.pteHasListStyle(listStyle)\n } catch (err) {\n // This is fine.\n // debug(err)\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 (err) {\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 (err) {\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 (err) {\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 = 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: (type: ObjectSchemaType): 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 {isEqual} from 'lodash'\nimport {Editor, Node, Path, Range, Transforms} from 'slate'\nimport {\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {type SlateTextBlock, type VoidElement} from '../../types/slate'\n\nexport function createWithInsertBreak(\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n return function withInsertBreak(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {insertBreak} = editor\n\n editor.insertBreak = () => {\n if (!editor.selection) {\n insertBreak()\n return\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 isEndAtStartOfBlock = isEqual(end, {\n path: [...focusBlockPath, 0],\n offset: 0,\n })\n\n if (isEndAtStartOfBlock && Range.isCollapsed(editor.selection)) {\n const focusDecorators = editor.isTextSpan(focusBlock.children[0])\n ? (focusBlock.children[0].marks ?? []).filter((mark) =>\n types.decorators.some((decorator) => decorator.value === mark),\n )\n : []\n\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({decorators: focusDecorators}),\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 editor.onChange()\n return\n }\n\n const lastFocusBlockChild =\n focusBlock.children[focusBlock.children.length - 1]\n const isStartAtEndOfBlock = isEqual(start, {\n path: [...focusBlockPath, focusBlock.children.length - 1],\n offset: editor.isTextSpan(lastFocusBlockChild)\n ? lastFocusBlockChild.text.length\n : 0,\n })\n const isInTheMiddleOfNode = !isEndAtStartOfBlock && !isStartAtEndOfBlock\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 types.decorators.some(\n (decorator) => decorator.value === mark,\n )\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 insertBreak()\n }\n\n return editor\n }\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","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 {\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\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 schemaTypes: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\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: 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: 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 Transforms.setNodes(editor, {_key: keyGenerator()}, {at: path})\n }\n // Set keys on it's children\n for (const [child, childPath] of Node.children(editor, path)) {\n if (!child._key) {\n Transforms.setNodes(editor, {_key: keyGenerator()}, {at: childPath})\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","/* eslint-disable max-statements */\nimport {\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 {\n type KeyedSegment,\n type Path,\n type PathSegment,\n type PortableTextBlock,\n type 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 {\n type PortableTextMemberSchemaTypes,\n type 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 let previousPatch: Patch | undefined\n\n return function (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, previousPatch)\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 previousPatch = patch\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-vars\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(\n editor: PortableTextSlateEditor,\n patch: UnsetPatch,\n previousPatch?: Patch,\n) {\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((c, 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, type 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 {\n type PatchObservable,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue} from '../../utils/values'\nimport {\n setIsRedoing,\n setIsUndoing,\n withRedoing,\n withUndoing,\n} from '../../utils/withUndoRedo'\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 patches$?: PatchObservable\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 {readOnly, patches$, 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 if (patches$) {\n editor.subscriptions.push(() => {\n debug('Subscribing to patches')\n const sub = patches$.subscribe(({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 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 // eslint-disable-next-line max-nested-callbacks\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","/* eslint-disable max-nested-callbacks */\nimport {insert, setIfMissing, unset, type Patch} from '@portabletext/patches'\nimport {type Subject} from 'rxjs'\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 {\n type EditorChange,\n type PatchObservable,\n type PortableTextMemberSchemaTypes,\n type 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 {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 change$: Subject<EditorChange>\n keyGenerator: () => string\n patches$?: PatchObservable\n patchFunctions: PatchFunctions\n readOnly: boolean\n schemaTypes: PortableTextMemberSchemaTypes\n}\n\nexport function createWithPatches({\n change$,\n patches$,\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 if (patches$) {\n editor.subscriptions.push(() => {\n debug('Subscribing to patches$')\n const sub = patches$.subscribe(handlePatches)\n return () => {\n debug('Unsubscribing to patches$')\n sub.unsubscribe()\n }\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 case 'set_selection':\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 change$.next({\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 change$.next({\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, type 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 {\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\n\nconst debug = debugWithName('plugin:withPortableTextBlockStyle')\n\nexport function createWithPortableTextBlockStyle(\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 editor.normalizeNode = (nodeEntry) => {\n normalizeNode(nodeEntry)\n const [, path] = nodeEntry\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 Transforms.setNodes(\n editor,\n {style: defaultStyle},\n {at: [op.path[0] + 1], voids: false},\n )\n break\n }\n }\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 {\n type PortableTextMemberSchemaTypes,\n type 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\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","/* eslint-disable max-statements */\n/* eslint-disable complexity */\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} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {type Subject} from 'rxjs'\nimport {\n Editor,\n Element,\n Node,\n Path,\n Range,\n Text,\n Transforms,\n type Descendant,\n} from 'slate'\nimport {\n type EditorChange,\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toPortableTextRange} from '../../utils/ranges'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\n\nconst debug = debugWithName('plugin:withPortableTextMarkModel')\n\nexport function createWithPortableTextMarkModel(\n types: PortableTextMemberSchemaTypes,\n change$: Subject<EditorChange>,\n keyGenerator: () => string,\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 // Selections are normally emitted automatically via\n // onChange, but they will keep the object reference if\n // the selection is the same as the previous.\n // When toggling marks however, it might not even\n // result in a onChange event (for instance when nothing is selected),\n // and if you toggle marks on a block with one single span,\n // the selection would also stay the same.\n // We should force a new selection object here when toggling marks,\n // because toolbars and other things can very conveniently\n // be memo'ed on the editor selection to update itself.\n const forceNewSelection = () => {\n if (editor.selection) {\n Transforms.select(editor, {...editor.selection})\n editor.selection = {...editor.selection} // Ensure new object\n }\n const ptRange = toPortableTextRange(\n editor.children,\n editor.selection,\n types,\n )\n change$.next({type: 'selection', selection: ptRange})\n }\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 isEqual(child.marks, nextNode.marks)\n ) {\n debug(\n 'Merging spans',\n JSON.stringify(child, null, 2),\n JSON.stringify(nextNode, null, 2),\n )\n Transforms.mergeNodes(editor, {\n at: [childPath[0], childPath[1] + 1],\n voids: true,\n })\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 Transforms.setNodes(editor, {markDefs: []}, {at: path})\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 Transforms.setNodes(editor, {marks: []}, {at: path})\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 Transforms.setNodes(\n editor,\n {marks: node.marks?.filter((mark) => decorators.includes(mark))},\n {at: path},\n )\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 Transforms.setNodes(\n editor,\n {\n marks: marks.filter(\n (mark) => !orphanedAnnotations.includes(mark),\n ),\n },\n {at: childPath},\n )\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 Transforms.setNodes(\n editor,\n {\n marks: marks.filter(\n (mark) => !orphanedAnnotations.includes(mark),\n ),\n },\n {at: path},\n )\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 Transforms.setNodes(editor, {markDefs: newMarkDefs}, {at: path})\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 Transforms.setNodes(\n editor,\n {\n markDefs: newMarkDefs,\n },\n {at: path},\n )\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 // Special hook before inserting text at the end of an annotation.\n if (op.type === 'insert_text') {\n const {selection} = editor\n if (\n selection &&\n Range.isCollapsed(selection) &&\n Editor.marks(editor)?.marks?.some(\n (mark) => !decorators.includes(mark),\n )\n ) {\n const [node] = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: selection.focus,\n match: (n) =>\n (n as unknown as Descendant)._type === types.span.name,\n voids: false,\n }),\n )[0] || [undefined]\n if (\n Text.isText(node) &&\n node.text.length === selection.focus.offset &&\n Array.isArray(node.marks) &&\n node.marks.length > 0\n ) {\n const marksWithoutAnnotationMarks: string[] = (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).filter((mark) => decorators.includes(mark))\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: keyGenerator(),\n text: op.text,\n marks: marksWithoutAnnotationMarks,\n })\n debug('Inserting text at end of annotation')\n return\n }\n }\n }\n\n if (op.type === 'remove_text') {\n const nodeEntry = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: {path: op.path, offset: op.offset},\n match: (n) => n._type === types.span.name,\n voids: false,\n }),\n )[0]\n const node = nodeEntry[0]\n const blockEntry = Editor.node(editor, Path.parent(op.path))\n const block = blockEntry[0]\n\n if (\n node &&\n isPortableTextSpan(node) &&\n block &&\n isPortableTextBlock(block)\n ) {\n const markDefs = block.markDefs ?? []\n const nodeHasAnnotations = (node.marks ?? []).some((mark) =>\n markDefs.find((markDef) => markDef._key === mark),\n )\n const deletingPartOfTheNode = op.offset !== 0\n const deletingFromTheEnd =\n op.offset + op.text.length === node.text.length\n\n if (\n nodeHasAnnotations &&\n deletingPartOfTheNode &&\n deletingFromTheEnd\n ) {\n Editor.withoutNormalizing(editor, () => {\n Transforms.splitNodes(editor, {\n match: Text.isText,\n at: {path: op.path, offset: op.offset},\n })\n Transforms.removeNodes(editor, {at: Path.next(op.path)})\n })\n\n editor.onChange()\n return\n }\n\n const deletingAllText = op.offset === 0 && deletingFromTheEnd\n\n if (nodeHasAnnotations && deletingAllText) {\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 const nodeHasMarks = node.marks !== undefined && node.marks.length > 0\n\n if (nodeHasMarks && deletingAllText) {\n Editor.withoutNormalizing(editor, () => {\n apply(op)\n Transforms.setNodes(editor, {marks: []}, {at: op.path})\n })\n\n editor.onChange()\n return\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 // Override built in addMark function\n editor.addMark = (mark: string) => {\n if (editor.selection) {\n if (Range.isExpanded(editor.selection)) {\n Editor.withoutNormalizing(editor, () => {\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 })\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 forceNewSelection()\n return editor\n }\n }\n editor.onChange()\n forceNewSelection()\n }\n return editor\n }\n\n // Override built in removeMark function\n editor.removeMark = (mark: string) => {\n const {selection} = editor\n if (selection) {\n if (Range.isExpanded(selection)) {\n Editor.withoutNormalizing(editor, () => {\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)\n ? node.marks\n : []\n ).filter((eMark: string) => eMark !== mark),\n _type: 'span',\n },\n {at: path},\n )\n }\n })\n }\n })\n Editor.normalize(editor)\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 forceNewSelection()\n return editor\n }\n }\n editor.onChange()\n forceNewSelection()\n }\n return editor\n }\n\n editor.pteIsMarkActive = (mark: string): boolean => {\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(mark)\n })\n }\n\n return (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).includes(mark)\n }\n\n // Custom editor function to toggle a mark\n editor.pteToggleMark = (mark: string) => {\n const isActive = editor.pteIsMarkActive(mark)\n if (isActive) {\n debug(`Remove mark '${mark}'`)\n Editor.removeMark(editor, mark)\n } else {\n debug(`Add mark '${mark}'`)\n Editor.addMark(editor, mark, true)\n }\n }\n return editor\n }\n}\n","import {type Subject} from 'rxjs'\nimport {type BaseRange} from 'slate'\nimport {\n type EditorChange,\n type EditorSelection,\n type PortableTextMemberSchemaTypes,\n type 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'\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 change$: Subject<EditorChange>,\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 change$.next({type: 'selection', selection: ptRange})\n } else {\n change$.next({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 {\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\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 schemaTypes,\n keyGenerator,\n}: {\n schemaTypes: PortableTextMemberSchemaTypes\n keyGenerator: () => string\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 = span._key || keyGenerator()\n Transforms.setNodes(\n editor,\n {...span, _type: schemaTypes.span.name, _key: key},\n {at: path},\n )\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 = keyGenerator()\n Transforms.setNodes(editor, {_key: key}, {at: path})\n }\n\n normalizeNode(entry)\n }\n return editor\n }\n}\n","import {Editor, Range, Text, Transforms} from 'slate'\nimport {\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toSlateValue} from '../../utils/values'\nimport {type PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('plugin:withUtils')\n\ninterface Options {\n schemaTypes: PortableTextMemberSchemaTypes\n keyGenerator: () => string\n portableTextEditor: PortableTextEditor\n}\n/**\n * This plugin makes various util commands available in the editor\n *\n */\nexport function createWithUtils({\n schemaTypes,\n keyGenerator,\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 isNaN(newStartOffset) ||\n 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: {decorators: Array<string>}) => {\n const block = toSlateValue(\n [\n {\n _type: schemaTypes.block.name,\n _key: keyGenerator(),\n style: schemaTypes.styles[0].value || 'normal',\n markDefs: [],\n children: [\n {\n _type: 'span',\n _key: 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","/* eslint-disable max-statements */\n/* eslint-disable complexity */\nimport {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 {\n type PortableTextMemberSchemaTypes,\n type PortableTextSlateEditor,\n} from '../../types/editor'\nimport {type HotkeyOptions} from '../../types/options'\nimport {type SlateTextBlock, type VoidElement} from '../../types/slate'\nimport {debugWithName} from '../../utils/debug'\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 types: PortableTextMemberSchemaTypes,\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 // eslint-disable-next-line guard-for-in\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 editor.pteToggleMark(mark)\n }\n }\n }\n }\n if (cat === 'custom') {\n // eslint-disable-next-line guard-for-in\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 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 // Enter from another style than the first (default one)\n if (\n editor.isTextBlock(focusBlock) &&\n focusBlock.style &&\n focusBlock.style !== types.styles[0].value\n ) {\n const [, end] = Range.edges(editor.selection)\n const endAtEndOfNode = Editor.isEnd(editor, end, end.path)\n if (endAtEndOfNode) {\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n )\n event.preventDefault()\n editor.onChange()\n return\n }\n }\n // Block object enter key\n if (focusBlock && Editor.isVoid(editor, focusBlock)) {\n Editor.insertNode(editor, editor.pteCreateTextBlock({decorators: []}))\n event.preventDefault()\n editor.onChange()\n return\n }\n // Default enter key behavior\n event.preventDefault()\n editor.insertBreak()\n editor.onChange()\n }\n\n // Soft line breaks\n if (isShiftEnter) {\n event.preventDefault()\n editor.insertText('\\n')\n return\n }\n\n // Undo/redo\n if (isHotkey('mod+z', event.nativeEvent)) {\n event.preventDefault()\n editor.undo()\n return\n }\n if (\n isHotkey('mod+y', event.nativeEvent) ||\n isHotkey('mod+shift+z', event.nativeEvent)\n ) {\n event.preventDefault()\n editor.redo()\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 {\n type InvalidValueResolution,\n type PortableTextMemberSchemaTypes,\n} from '../types/editor'\nimport {EMPTY_MARKDEFS} from './values'\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 // Test that markDefs are valid if they exists\n if (blk.markDefs && !Array.isArray(blk.markDefs)) {\n resolution = {\n patches: [\n set({...textBlock, markDefs: EMPTY_MARKDEFS}, [\n {_key: textBlock._key},\n ]),\n ],\n description: `Block has invalid required property 'markDefs'.`,\n action: 'Add empty markDefs array',\n item: textBlock,\n\n i18n: {\n description:\n 'inputs.portable-text.invalid-value.missing-or-invalid-markdefs.description',\n action:\n 'inputs.portable-text.invalid-value.missing-or-invalid-markdefs.action',\n values: {key: textBlock._key},\n },\n }\n return true\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, type 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 {\n type EditorChanges,\n type PortableTextMemberSchemaTypes,\n type 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'\n\nconst debug = debugWithName('plugin:withInsertData')\n\n/**\n * This plugin handles copy/paste in the editor\n *\n */\nexport function createWithInsertData(\n change$: EditorChanges,\n schemaTypes: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\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 keyGenerator,\n spanTypeName,\n schemaTypes,\n )\n // Validate the result\n const validation = validateValue(parsed, schemaTypes, keyGenerator)\n // Bail out if it's not valid\n if (!validation.valid && !validation.resolution?.autoResolve) {\n const errorDescription = `${validation.resolution?.description}`\n change$.next({\n type: 'error',\n level: 'warning',\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 change$.next({type: 'loading', isLoading: true}) // This could potentially take some time\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\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 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 change$.next({\n type: 'error',\n level: 'warning',\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 change$.next({type: 'loading', isLoading: false})\n return true\n }\n change$.next({type: 'loading', isLoading: false})\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 ? // eslint-disable-next-line max-nested-callbacks\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, type Editor, type Node, type NodeEntry} from 'slate'\nimport {type PortableTextSlateEditor} from '../../types/editor'\nimport {type createEditorOptions} from '../../types/options'\nimport {createOperationToPatches} from '../../utils/operationToPatches'\nimport {createWithEditableAPI} from './createWithEditableAPI'\nimport {createWithInsertBreak} from './createWithInsertBreak'\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 {keyGenerator, portableTextEditor, patches$, readOnly, maxBlocks} =\n options\n const {schemaTypes, change$} = 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(schemaTypes, keyGenerator)\n const withSchemaTypes = createWithSchemaTypes({schemaTypes, keyGenerator})\n const withEditableAPI = createWithEditableAPI(\n portableTextEditor,\n schemaTypes,\n keyGenerator,\n )\n const withPatches = createWithPatches({\n change$,\n keyGenerator,\n patches$,\n patchFunctions: operationToPatches,\n readOnly,\n schemaTypes,\n })\n const withMaxBlocks = createWithMaxBlocks(maxBlocks || -1)\n const withPortableTextLists = createWithPortableTextLists(schemaTypes)\n const withUndoRedo = createWithUndoRedo({\n readOnly,\n patches$,\n blockSchemaType: schemaTypes.block,\n })\n const withPortableTextMarkModel = createWithPortableTextMarkModel(\n schemaTypes,\n change$,\n keyGenerator,\n )\n const withPortableTextBlockStyle =\n createWithPortableTextBlockStyle(schemaTypes)\n\n const withPlaceholderBlock = createWithPlaceholderBlock()\n\n const withInsertBreak = createWithInsertBreak(schemaTypes, keyGenerator)\n\n const withUtils = createWithUtils({\n keyGenerator,\n schemaTypes,\n portableTextEditor,\n })\n const withPortableTextSelections = createWithPortableTextSelections(\n change$,\n schemaTypes,\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 if (readOnly) {\n return {\n editor: withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withUtils(\n withPlaceholderBlock(\n withPortableTextLists(\n withPortableTextSelections(\n withEditableAPI(withInsertBreak(e)),\n ),\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: withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withPortableTextLists(\n withPlaceholderBlock(\n withUtils(\n withMaxBlocks(\n withUndoRedo(\n withPatches(\n withPortableTextSelections(\n withEditableAPI(withInsertBreak(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 {type PatchObservable} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {KEY_TO_SLATE_ELEMENT, KEY_TO_VALUE_ELEMENT} from '../../utils/weakMaps'\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 keyGenerator: () => string\n maxBlocks: number | undefined\n patches$?: PatchObservable\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 {patches$, portableTextEditor, readOnly, maxBlocks, keyGenerator} =\n 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 keyGenerator,\n maxBlocks,\n patches$,\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 keyGenerator,\n maxBlocks,\n patches$,\n portableTextEditor,\n readOnly,\n })\n }, [\n keyGenerator,\n portableTextEditor,\n maxBlocks,\n readOnly,\n patches$,\n slateEditor,\n ])\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","import {randomKey} from '@sanity/util/content'\nimport {createContext, useContext} from 'react'\n\n/**\n * @public\n */\nexport const defaultKeyGenerator = (): string => randomKey(12)\n\n/**\n * A React context for sharing the editor's keyGenerator.\n */\nexport const PortableTextEditorKeyGeneratorContext =\n createContext<() => string>(defaultKeyGenerator)\n\n/**\n * Get the current editor selection from the React context.\n */\nexport const usePortableTextEditorKeyGenerator = (): (() => string) => {\n const keyGenerator = useContext(PortableTextEditorKeyGeneratorContext)\n\n if (keyGenerator === undefined) {\n throw new Error(\n `The \\`usePortableTextEditorKeyGenerator\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n return keyGenerator\n}\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","/* eslint-disable max-nested-callbacks */\nimport {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 {\n type EditorChange,\n type PortableTextSlateEditor,\n} 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 {withoutSaving} from '../plugins/createWithUndoRedo'\nimport {type PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('hook:useSyncValue')\n\n/**\n * @internal\n */\nexport interface UseSyncValueProps {\n keyGenerator: () => string\n onChange: (change: EditorChange) => void\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 {portableTextEditor, readOnly, keyGenerator} = props\n const {change$, schemaTypes} = portableTextEditor\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 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 change$.next({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 change$.next({\n type: 'invalidValue',\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 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 change$.next({\n type: 'invalidValue',\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 change$.next({\n type: 'invalidValue',\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 change$.next({type: 'value', 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 change$,\n keyGenerator,\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, useMemo, useRef} from 'react'\nimport {Editor} from 'slate'\nimport {useSlate} from 'slate-react'\nimport {type EditorChange, type EditorChanges} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {IS_PROCESSING_LOCAL_CHANGES} from '../../utils/weakMaps'\nimport {usePortableTextEditor} from '../hooks/usePortableTextEditor'\nimport {usePortableTextEditorKeyGenerator} from '../hooks/usePortableTextEditorKeyGenerator'\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 change$: EditorChanges\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 keyGenerator = usePortableTextEditorKeyGenerator()\n const readOnly = usePortableTextEditorReadOnlyStatus()\n const {change$, getValue, onChange, value} = props\n const pendingPatches = useRef<Patch[]>([])\n\n const syncValue = useSyncValue({\n keyGenerator,\n onChange,\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 change$.next({\n type: 'mutation',\n patches: pendingPatches.current,\n snapshot,\n })\n pendingPatches.current = []\n }\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, false)\n }, [slateEditor, getValue, change$])\n\n const onFlushPendingPatchesThrottled = useMemo(() => {\n return 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 }, [onFlushPendingPatches, slateEditor])\n\n // Flush pending patches immediately on unmount\n useEffect(() => {\n return () => {\n onFlushPendingPatches()\n }\n }, [onFlushPendingPatches])\n\n // Subscribe to, and handle changes from the editor\n useEffect(() => {\n debug('Subscribing to editor changes$')\n const sub = change$.subscribe((next: EditorChange): void => {\n switch (next.type) {\n case 'patch':\n IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, true)\n pendingPatches.current.push(next.patch)\n onFlushPendingPatchesThrottled()\n onChange(next)\n break\n default:\n onChange(next)\n }\n })\n return () => {\n debug('Unsubscribing to changes$')\n sub.unsubscribe()\n }\n }, [change$, onChange, onFlushPendingPatchesThrottled, slateEditor])\n\n // Sync the value when going online\n const handleOnline = useCallback(() => {\n debug('Editor is online, syncing from props.value')\n change$.next({type: 'connection', value: 'online'})\n syncValue(value)\n }, [change$, syncValue, value])\n\n const handleOffline = useCallback(() => {\n debug('Editor is offline')\n change$.next({type: 'connection', value: 'offline'})\n }, [change$])\n\n // Notify about window online and offline status changes\n useEffect(() => {\n if (portableTextEditor.props.patches$) {\n window.addEventListener('online', handleOnline)\n window.addEventListener('offline', handleOffline)\n }\n return () => {\n if (portableTextEditor.props.patches$) {\n window.removeEventListener('online', handleOnline)\n window.removeEventListener('offline', handleOffline)\n }\n }\n })\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 change$.next({type: 'loading', isLoading: false})\n change$.next({type: 'ready'})\n isInitialValueFromProps.current = false\n }\n }, [change$, syncValue, value])\n\n return null\n}\n","import {\n createContext,\n startTransition,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport {type EditorChanges, type EditorSelection} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\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 change$: EditorChanges\n }>,\n) {\n const {change$} = props\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 = change$.subscribe((next): void => {\n if (next.type === 'selection') {\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(next.selection)\n })\n }\n })\n\n return () => {\n debug('Unsubscribing to selection changes$')\n subscription.unsubscribe()\n }\n }, [change$])\n\n return (\n <PortableTextEditorSelectionContext.Provider value={selection}>\n {props.children}\n </PortableTextEditorSelectionContext.Provider>\n )\n}\n","import {\n type ArrayDefinition,\n type ArraySchemaType,\n type BlockSchemaType,\n type ObjectSchemaType,\n type Path,\n type PortableTextBlock,\n type PortableTextChild,\n type PortableTextObject,\n type SpanSchemaType,\n} from '@sanity/types'\nimport {Component, type MutableRefObject, type PropsWithChildren} from 'react'\nimport {Subject} from 'rxjs'\nimport {\n type EditableAPI,\n type EditableAPIDeleteOptions,\n type EditorChange,\n type EditorChanges,\n type EditorSelection,\n type PatchObservable,\n type 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 {PortableTextEditorContext} from './hooks/usePortableTextEditor'\nimport {\n defaultKeyGenerator,\n PortableTextEditorKeyGeneratorContext,\n} from './hooks/usePortableTextEditorKeyGenerator'\nimport {PortableTextEditorSelectionProvider} from './hooks/usePortableTextEditorSelection'\nimport {PortableTextEditorReadOnlyContext} from './hooks/usePortableTextReadOnly'\n\nconst debug = debugWithName('component:PortableTextEditor')\n\n/**\n * Props for the PortableTextEditor component\n *\n * @public\n */\nexport type PortableTextEditorProps = PropsWithChildren<{\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 * 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 * 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 * A ref to the editor instance\n */\n editorRef?: MutableRefObject<PortableTextEditor | null>\n}>\n\n/**\n * The main Portable Text Editor component.\n * @public\n */\nexport class PortableTextEditor extends Component<PortableTextEditorProps> {\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\n constructor(props: PortableTextEditorProps) {\n super(props)\n\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.change$.next({type: 'loading', isLoading: true})\n\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n props.schemaType.hasOwnProperty('jsonType')\n ? props.schemaType\n : compileType(props.schemaType),\n )\n }\n\n componentDidUpdate(prevProps: PortableTextEditorProps) {\n // Set up the schema type lookup table again if the source schema type changes\n if (this.props.schemaType !== prevProps.schemaType) {\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n this.props.schemaType.hasOwnProperty('jsonType')\n ? this.props.schemaType\n : compileType(this.props.schemaType),\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 {onChange, value, children, patches$, incomingPatches$} = this.props\n const {change$} = this\n const _patches$ = incomingPatches$ || patches$ // Backward compatibility\n\n const maxBlocks =\n typeof this.props.maxBlocks === 'undefined'\n ? undefined\n : parseInt(this.props.maxBlocks.toString(), 10) || undefined\n\n const readOnly = Boolean(this.props.readOnly)\n const keyGenerator = this.props.keyGenerator || defaultKeyGenerator\n return (\n <SlateContainer\n keyGenerator={keyGenerator}\n maxBlocks={maxBlocks}\n patches$={_patches$}\n portableTextEditor={this}\n readOnly={readOnly}\n >\n <PortableTextEditorKeyGeneratorContext.Provider value={keyGenerator}>\n <PortableTextEditorContext.Provider value={this}>\n <PortableTextEditorReadOnlyContext.Provider value={readOnly}>\n <PortableTextEditorSelectionProvider change$={change$}>\n <Synchronizer\n change$={change$}\n getValue={this.getValue}\n onChange={onChange}\n value={value}\n />\n {children}\n </PortableTextEditorSelectionProvider>\n </PortableTextEditorReadOnlyContext.Provider>\n </PortableTextEditorContext.Provider>\n </PortableTextEditorKeyGeneratorContext.Provider>\n </SlateContainer>\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 = (\n editor: PortableTextEditor,\n type: ObjectSchemaType,\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 // eslint-disable-next-line react/no-find-dom-node\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 = (\n editor: PortableTextEditor,\n type: SpanSchemaType | ObjectSchemaType,\n value?: {[prop: string]: unknown},\n ): Path | undefined => {\n debug(`Host inserting child`)\n return editor.editable?.insertChild(type, value)\n }\n static insertBlock = (\n editor: PortableTextEditor,\n type: BlockSchemaType | ObjectSchemaType,\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 = (\n editor: PortableTextEditor,\n type: ObjectSchemaType,\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","import {\n type Path,\n type PortableTextObject,\n type 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 {\n type BlockAnnotationRenderProps,\n type BlockChildRenderProps,\n type BlockDecoratorRenderProps,\n type PortableTextMemberSchemaTypes,\n type RenderAnnotationFunction,\n type RenderChildFunction,\n type RenderDecoratorFunction,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\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 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 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 const sub = portableTextEditor.change$.subscribe((next) => {\n if (next.type === 'blur') {\n setFocused(false)\n setSelected(false)\n return\n }\n if (next.type === '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 return\n }\n if (next.type === 'selection') {\n if (\n next.selection &&\n isEqual(next.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 sub.unsubscribe()\n }\n }, [\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","import {type PortableTextBlock} from '@sanity/types'\nimport {isEqual, noop} from 'lodash'\nimport {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type CSSProperties,\n type FocusEventHandler,\n type ForwardedRef,\n type HTMLProps,\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 {\n type EditorChange,\n type EditorSelection,\n type OnCopyFn,\n type OnPasteFn,\n type RangeDecoration,\n type RenderAnnotationFunction,\n type RenderBlockFunction,\n type RenderChildFunction,\n type RenderDecoratorFunction,\n type RenderListItemFunction,\n type RenderPlaceholderFunction,\n type RenderStyleFunction,\n type ScrollSelectionIntoViewFunction,\n} from '../types/editor'\nimport {type HotkeyOptions} from '../types/options'\nimport {type SlateTextBlock, type 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 {usePortableTextEditor} from './hooks/usePortableTextEditor'\nimport {usePortableTextEditorKeyGenerator} from './hooks/usePortableTextEditorKeyGenerator'\nimport {usePortableTextEditorReadOnlyStatus} from './hooks/usePortableTextReadOnly'\nimport {createWithHotkeys, createWithInsertData} from './plugins'\nimport {PortableTextEditor} from './PortableTextEditor'\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(function PortableTextEditable(\n props: PortableTextEditableProps &\n Omit<HTMLProps<HTMLDivElement>, 'as' | 'onPaste' | 'onBeforeInput'>,\n forwardedRef: ForwardedRef<HTMLDivElement>,\n) {\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 keyGenerator = usePortableTextEditorKeyGenerator()\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 {change$, schemaTypes} = portableTextEditor\n const slateEditor = useSlate()\n\n const blockTypeName = schemaTypes.block.name\n\n // React/UI-specific plugins\n const withInsertData = useMemo(\n () => createWithInsertData(change$, schemaTypes, keyGenerator),\n [change$, keyGenerator, schemaTypes],\n )\n const withHotKeys = useMemo(\n () => createWithHotkeys(schemaTypes, portableTextEditor, hotkeys),\n [hotkeys, portableTextEditor, schemaTypes],\n )\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 if (readOnly) {\n debug('Editable is in read only mode')\n return withInsertData(slateEditor)\n }\n debug('Editable is in edit mode')\n return withInsertData(withHotKeys(slateEditor))\n }, [readOnly, slateEditor, withHotKeys, withInsertData])\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 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 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 change$.next({type: 'selection', selection: normalizedSelection})\n }\n slateEditor.onChange()\n }\n }\n }\n }, [propsSelection, slateEditor, blockTypeName, change$])\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([])\n },\n [portableTextEditor, rangeDecorations, schemaTypes, slateEditor],\n )\n\n // Subscribe to change$ and restore selection from props when the editor has been initialized properly with it's value\n useEffect(() => {\n // debug('Subscribing to editor changes$')\n const sub = change$.subscribe((next: EditorChange): void => {\n switch (next.type) {\n case 'ready':\n restoreSelectionFromProps()\n break\n case 'invalidValue':\n setHasInvalidValue(true)\n break\n case 'value':\n setHasInvalidValue(false)\n break\n default:\n }\n })\n return () => {\n // debug('Unsubscribing to changes$')\n sub.unsubscribe()\n }\n }, [change$, 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 // Store reference to original apply function (see below for usage in useEffect)\n const originalApply = useMemo(() => slateEditor.apply, [slateEditor])\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 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 }, [originalApply, 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 change$.next({type: 'loading', isLoading: true})\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) // eslint-disable-line no-console\n return error\n })\n .finally(() => {\n change$.next({type: 'loading', isLoading: false})\n })\n }\n },\n [change$, 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 change$.next({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 change$.next({\n type: 'selection',\n selection,\n })\n }\n }\n },\n [onFocus, portableTextEditor, change$, 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 change$.next({type: 'blur', event})\n }\n },\n [change$, 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 (error) {\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"],"names":["debug","Element","dragPosition","block","schemaType","SlateElement","ObjectNode","diffMatchPatch","isPortableTextSpan","SlatePath","markDef","isUndoing","isRedoing","apply","diff","debugVerbose","parsePatch","diffMatchPatchApplyPatches","makeDiff","items","position","normalizedIdx","SlateText","decorators","SlateRange","SlateEditable"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAEA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AA,YACA,aAAa;AAAA,UACf;AAAA,QAAA;AAIJ,UAAI,KAAK,WAAW;AAClB,eAAO;AAET,YAAM,SAAS,qBAAqB,OAAO,CAAC,SAEtCA,MAAW,YAAY,IAAI,IAEzB,KAAK,WAAW,IACX,KAGP,KAAK,OAAO,KAAK,MAAM,MAAM,IAAI,KACjC,KAAK,OAAO,KAAK,OAAO,MAAM,IAAI,IAKpCA,MAAW,aAAa,MAAM;AAAA,QAC5B,QAAQ,EAAC,MAAM,QAAQ,EAAC;AAAA,QACxB,OAAO,EAAC,MAAM,QAAQ,EAAC;AAAA,MACxB,CAAA,KAAKA,MAAW,SAAS,MAAM,IAAI,CAEvC;AACD,aAAI,OAAO,SAAS,IACX,SAEF,CAAA;AAAA,IACT;AAAA,IACA,CAAC,aAAa,aAAa,oBAAoB;AAAA,EAAA;AAcjD,SARA,UAAU,MAAM;AACd,QAAI,UAAU,YAAY;AAAA,MACxB;AAAA,MACA;AAAA,IAAA,GAEF,mBAAmB,IAAI,OAAO;AAAA,EAAA,GAC7B,CAAC,aAAa,GAAG,CAAC,GAEhB,qBAGE,kBAAkB,OACvB;AAAA,IAACC;AAAAA,IAAA;AAAA,MACE,GAAG;AAAA,MACJ,WAAW;AAAA,MACX,WAAW,UAAU,aAAa;AAAA,MAClC;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,SAAS;AAAA,MACT,kBAAkB;AAAA,MAClB,SAAS;AAAA,MACT,WAAW;AAAA,MACX,SAAS;AAAA,MACT;AAAA,MAGA,mBAAmB;AAAA,MACnB;AAAA,MACA;AAAA,MACA,yBAAyB;AAAA,IAAA;AAAA,EArBpB,IAAA;AAwBX,CAAC;","x_google_ignoreList":[21,29]}
1
+ {"version":3,"file":"index.esm.js","sources":["../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/getPortableTextMemberSchemaTypes.ts","../src/utils/schema.ts","../src/utils/operationToPatches.ts","../src/editor/plugins/createWithEditableAPI.ts","../src/editor/plugins/createWithInsertBreak.ts","../src/utils/withChanges.ts","../src/utils/withUndoRedo.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","../../../node_modules/.pnpm/@portabletext+toolkit@2.0.15/node_modules/@portabletext/toolkit/dist/index.js","../src/editor/plugins/createWithPortableTextMarkModel.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/usePortableTextEditorKeyGenerator.ts","../src/editor/hooks/usePortableTextReadOnly.ts","../src/editor/hooks/useSyncValue.ts","../src/editor/components/Synchronizer.tsx","../src/editor/editor-machine.ts","../src/editor/hooks/usePortableTextEditorSelection.tsx","../src/editor/PortableTextEditor.tsx","../src/editor/components/Leaf.tsx","../src/editor/Editable.tsx"],"sourcesContent":["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\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","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","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","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} 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 {\n isPortableTextSpan,\n type ObjectSchemaType,\n type Path,\n type PortableTextBlock,\n type PortableTextChild,\n type PortableTextObject,\n type PortableTextSpan,\n type PortableTextTextBlock,\n type SchemaType,\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 {ReactEditor} from 'slate-react'\nimport type {DOMNode} from 'slate-react/dist/utils/dom'\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 {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('API:editable')\n\nexport function createWithEditableAPI(\n portableTextEditor: PortableTextEditor,\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\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 editor.pteToggleMark(mark)\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 editor.pteIsMarkActive(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: (type: SchemaType, value?: {[prop: string]: any}): 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: keyGenerator(),\n _type: types.block.name,\n children: [\n {\n _key: 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: (type: SchemaType, value?: {[prop: string]: any}): Path => {\n const block = toSlateValue(\n [\n {\n _key: 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 (err) {\n // This is fine.\n // debug(err)\n return false\n }\n },\n hasListStyle: (listStyle: string): boolean => {\n try {\n return editor.pteHasListStyle(listStyle)\n } catch (err) {\n // This is fine.\n // debug(err)\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 (err) {\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 (err) {\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 (err) {\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 = 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: (type: ObjectSchemaType): 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 {isEqual} from 'lodash'\nimport {Editor, Node, Path, Range, Transforms} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\n\nexport function createWithInsertBreak(\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\n): (editor: PortableTextSlateEditor) => PortableTextSlateEditor {\n return function withInsertBreak(\n editor: PortableTextSlateEditor,\n ): PortableTextSlateEditor {\n const {insertBreak} = editor\n\n editor.insertBreak = () => {\n if (!editor.selection) {\n insertBreak()\n return\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 isEndAtStartOfBlock = isEqual(end, {\n path: [...focusBlockPath, 0],\n offset: 0,\n })\n\n if (isEndAtStartOfBlock && Range.isCollapsed(editor.selection)) {\n const focusDecorators = editor.isTextSpan(focusBlock.children[0])\n ? (focusBlock.children[0].marks ?? []).filter((mark) =>\n types.decorators.some((decorator) => decorator.value === mark),\n )\n : []\n\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({decorators: focusDecorators}),\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 editor.onChange()\n return\n }\n\n const lastFocusBlockChild =\n focusBlock.children[focusBlock.children.length - 1]\n const isStartAtEndOfBlock = isEqual(start, {\n path: [...focusBlockPath, focusBlock.children.length - 1],\n offset: editor.isTextSpan(lastFocusBlockChild)\n ? lastFocusBlockChild.text.length\n : 0,\n })\n const isInTheMiddleOfNode = !isEndAtStartOfBlock && !isStartAtEndOfBlock\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 types.decorators.some(\n (decorator) => decorator.value === mark,\n )\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 insertBreak()\n }\n\n return editor\n }\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","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 keyGenerator: () => string,\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: 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: 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(editor, {_key: keyGenerator()}, {at: path})\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(editor, {_key: keyGenerator()}, {at: childPath})\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 let previousPatch: Patch | undefined\n\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, previousPatch)\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 previousPatch = patch\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(\n editor: PortableTextSlateEditor,\n patch: UnsetPatch,\n previousPatch?: Patch,\n) {\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((c, 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 {PatchObservable, PortableTextSlateEditor} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {fromSlateValue} from '../../utils/values'\nimport {\n setIsRedoing,\n setIsUndoing,\n withRedoing,\n withUndoing,\n} from '../../utils/withUndoRedo'\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 patches$?: PatchObservable\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 {readOnly, patches$, 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 if (patches$) {\n editor.subscriptions.push(() => {\n debug('Subscribing to patches')\n const sub = patches$.subscribe(({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 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 PatchObservable,\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 keyGenerator: () => string\n patches$?: PatchObservable\n patchFunctions: PatchFunctions\n readOnly: boolean\n schemaTypes: PortableTextMemberSchemaTypes\n}\n\nexport function createWithPatches({\n editorActor,\n patches$,\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 if (patches$) {\n editor.subscriptions.push(() => {\n debug('Subscribing to patches$')\n const sub = patches$.subscribe(handlePatches)\n return () => {\n debug('Unsubscribing to patches$')\n sub.unsubscribe()\n }\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","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(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\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","/**\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} from '@sanity/types'\nimport {isEqual, uniq} from 'lodash'\nimport {\n Editor,\n Element,\n Node,\n Path,\n Range,\n Text,\n Transforms,\n type Descendant,\n} from 'slate'\nimport type {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {toPortableTextRange} from '../../utils/ranges'\nimport {isChangingRemotely} from '../../utils/withChanges'\nimport {isRedoing, isUndoing} from '../../utils/withUndoRedo'\nimport type {EditorActor} from '../editor-machine'\n\nconst debug = debugWithName('plugin:withPortableTextMarkModel')\n\nexport function createWithPortableTextMarkModel(\n editorActor: EditorActor,\n types: PortableTextMemberSchemaTypes,\n keyGenerator: () => string,\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 // Selections are normally emitted automatically via\n // onChange, but they will keep the object reference if\n // the selection is the same as the previous.\n // When toggling marks however, it might not even\n // result in a onChange event (for instance when nothing is selected),\n // and if you toggle marks on a block with one single span,\n // the selection would also stay the same.\n // We should force a new selection object here when toggling marks,\n // because toolbars and other things can very conveniently\n // be memo'ed on the editor selection to update itself.\n const forceNewSelection = () => {\n if (editor.selection) {\n Transforms.select(editor, {...editor.selection})\n editor.selection = {...editor.selection} // Ensure new object\n }\n const ptRange = toPortableTextRange(\n editor.children,\n editor.selection,\n types,\n )\n editorActor.send({type: 'selection', selection: ptRange})\n }\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 isEqual(child.marks, nextNode.marks)\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 // Special hook before inserting text at the end of an annotation.\n if (op.type === 'insert_text') {\n const {selection} = editor\n if (\n selection &&\n Range.isCollapsed(selection) &&\n Editor.marks(editor)?.marks?.some(\n (mark) => !decorators.includes(mark),\n )\n ) {\n const [node] = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: selection.focus,\n match: (n) =>\n (n as unknown as Descendant)._type === types.span.name,\n voids: false,\n }),\n )[0] || [undefined]\n if (\n Text.isText(node) &&\n node.text.length === selection.focus.offset &&\n Array.isArray(node.marks) &&\n node.marks.length > 0\n ) {\n const marksWithoutAnnotationMarks: string[] = (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).filter((mark) => decorators.includes(mark))\n Transforms.insertNodes(editor, {\n _type: 'span',\n _key: keyGenerator(),\n text: op.text,\n marks: marksWithoutAnnotationMarks,\n })\n debug('Inserting text at end of annotation')\n return\n }\n }\n }\n\n if (op.type === 'remove_text') {\n const nodeEntry = Array.from(\n Editor.nodes(editor, {\n mode: 'lowest',\n at: {path: op.path, offset: op.offset},\n match: (n) => n._type === types.span.name,\n voids: false,\n }),\n )[0]\n const node = nodeEntry[0]\n const blockEntry = Editor.node(editor, Path.parent(op.path))\n const block = blockEntry[0]\n\n if (\n node &&\n isPortableTextSpan(node) &&\n block &&\n isPortableTextBlock(block)\n ) {\n const markDefs = block.markDefs ?? []\n const nodeHasAnnotations = (node.marks ?? []).some((mark) =>\n markDefs.find((markDef) => markDef._key === mark),\n )\n const deletingPartOfTheNode = op.offset !== 0\n const deletingFromTheEnd =\n op.offset + op.text.length === node.text.length\n\n if (\n nodeHasAnnotations &&\n deletingPartOfTheNode &&\n deletingFromTheEnd\n ) {\n Editor.withoutNormalizing(editor, () => {\n Transforms.splitNodes(editor, {\n match: Text.isText,\n at: {path: op.path, offset: op.offset},\n })\n Transforms.removeNodes(editor, {at: Path.next(op.path)})\n })\n\n editor.onChange()\n return\n }\n\n const deletingAllText = op.offset === 0 && deletingFromTheEnd\n\n if (nodeHasAnnotations && deletingAllText) {\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 const nodeHasMarks = node.marks !== undefined && node.marks.length > 0\n\n if (nodeHasMarks && deletingAllText) {\n Editor.withoutNormalizing(editor, () => {\n apply(op)\n Transforms.setNodes(editor, {marks: []}, {at: op.path})\n })\n\n editor.onChange()\n return\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 // Override built in addMark function\n editor.addMark = (mark: string) => {\n if (editor.selection) {\n if (Range.isExpanded(editor.selection)) {\n Editor.withoutNormalizing(editor, () => {\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 })\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 forceNewSelection()\n return editor\n }\n }\n editor.onChange()\n forceNewSelection()\n }\n return editor\n }\n\n // Override built in removeMark function\n editor.removeMark = (mark: string) => {\n const {selection} = editor\n if (selection) {\n if (Range.isExpanded(selection)) {\n Editor.withoutNormalizing(editor, () => {\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)\n ? node.marks\n : []\n ).filter((eMark: string) => eMark !== mark),\n _type: 'span',\n },\n {at: path},\n )\n }\n })\n }\n })\n Editor.normalize(editor)\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 forceNewSelection()\n return editor\n }\n }\n editor.onChange()\n forceNewSelection()\n }\n return editor\n }\n\n editor.pteIsMarkActive = (mark: string): boolean => {\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(mark)\n })\n }\n\n return (\n {\n ...(Editor.marks(editor) || {}),\n }.marks || []\n ).includes(mark)\n }\n\n // Custom editor function to toggle a mark\n editor.pteToggleMark = (mark: string) => {\n const isActive = editor.pteIsMarkActive(mark)\n if (isActive) {\n debug(`Remove mark '${mark}'`)\n Editor.removeMark(editor, mark)\n } else {\n debug(`Add mark '${mark}'`)\n Editor.addMark(editor, mark, true)\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 keyGenerator,\n}: {\n editorActor: EditorActor\n schemaTypes: PortableTextMemberSchemaTypes\n keyGenerator: () => string\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 = span._key || 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 = 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 {PortableTextEditor} from '../PortableTextEditor'\n\nconst debug = debugWithName('plugin:withUtils')\n\ninterface Options {\n schemaTypes: PortableTextMemberSchemaTypes\n keyGenerator: () => string\n portableTextEditor: PortableTextEditor\n}\n/**\n * This plugin makes various util commands available in the editor\n *\n */\nexport function createWithUtils({\n schemaTypes,\n keyGenerator,\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: {decorators: Array<string>}) => {\n const block = toSlateValue(\n [\n {\n _type: schemaTypes.block.name,\n _key: keyGenerator(),\n style: schemaTypes.styles[0].value || 'normal',\n markDefs: [],\n children: [\n {\n _type: 'span',\n _key: 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 {\n PortableTextMemberSchemaTypes,\n PortableTextSlateEditor,\n} from '../../types/editor'\nimport type {HotkeyOptions} from '../../types/options'\nimport type {SlateTextBlock, VoidElement} from '../../types/slate'\nimport {debugWithName} from '../../utils/debug'\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 types: PortableTextMemberSchemaTypes,\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 editor.pteToggleMark(mark)\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 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 // Enter from another style than the first (default one)\n if (\n editor.isTextBlock(focusBlock) &&\n focusBlock.style &&\n focusBlock.style !== types.styles[0].value\n ) {\n const [, end] = Range.edges(editor.selection)\n const endAtEndOfNode = Editor.isEnd(editor, end, end.path)\n if (endAtEndOfNode) {\n Editor.insertNode(\n editor,\n editor.pteCreateTextBlock({decorators: []}),\n )\n event.preventDefault()\n editor.onChange()\n return\n }\n }\n // Block object enter key\n if (focusBlock && Editor.isVoid(editor, focusBlock)) {\n Editor.insertNode(editor, editor.pteCreateTextBlock({decorators: []}))\n event.preventDefault()\n editor.onChange()\n return\n }\n // Default enter key behavior\n event.preventDefault()\n editor.insertBreak()\n editor.onChange()\n }\n\n // Soft line breaks\n if (isShiftEnter) {\n event.preventDefault()\n editor.insertText('\\n')\n return\n }\n\n // Undo/redo\n if (isHotkey('mod+z', event.nativeEvent)) {\n event.preventDefault()\n editor.undo()\n return\n }\n if (\n isHotkey('mod+y', event.nativeEvent) ||\n isHotkey('mod+shift+z', event.nativeEvent)\n ) {\n event.preventDefault()\n editor.redo()\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 EditorChanges,\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 keyGenerator: () => string,\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 keyGenerator,\n spanTypeName,\n schemaTypes,\n )\n // Validate the result\n const validation = validateValue(parsed, schemaTypes, keyGenerator)\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 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 {createWithEditableAPI} from './createWithEditableAPI'\nimport {createWithInsertBreak} from './createWithInsertBreak'\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 {keyGenerator, portableTextEditor, patches$, readOnly, maxBlocks} =\n options\n const {editorActor, 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(\n editorActor,\n schemaTypes,\n keyGenerator,\n )\n const withSchemaTypes = createWithSchemaTypes({\n editorActor,\n schemaTypes,\n keyGenerator,\n })\n const withEditableAPI = createWithEditableAPI(\n portableTextEditor,\n schemaTypes,\n keyGenerator,\n )\n const withPatches = createWithPatches({\n editorActor,\n keyGenerator,\n patches$,\n patchFunctions: operationToPatches,\n readOnly,\n schemaTypes,\n })\n const withMaxBlocks = createWithMaxBlocks(maxBlocks || -1)\n const withPortableTextLists = createWithPortableTextLists(schemaTypes)\n const withUndoRedo = createWithUndoRedo({\n readOnly,\n patches$,\n blockSchemaType: schemaTypes.block,\n })\n const withPortableTextMarkModel = createWithPortableTextMarkModel(\n editorActor,\n schemaTypes,\n keyGenerator,\n )\n const withPortableTextBlockStyle = createWithPortableTextBlockStyle(\n editorActor,\n schemaTypes,\n )\n\n const withPlaceholderBlock = createWithPlaceholderBlock()\n\n const withInsertBreak = createWithInsertBreak(schemaTypes, keyGenerator)\n\n const withUtils = createWithUtils({\n keyGenerator,\n schemaTypes,\n portableTextEditor,\n })\n const withPortableTextSelections = createWithPortableTextSelections(\n editorActor,\n schemaTypes,\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 if (readOnly) {\n return {\n editor: withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withUtils(\n withPlaceholderBlock(\n withPortableTextLists(\n withPortableTextSelections(\n withEditableAPI(withInsertBreak(e)),\n ),\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: withSchemaTypes(\n withObjectKeys(\n withPortableTextMarkModel(\n withPortableTextBlockStyle(\n withPortableTextLists(\n withPlaceholderBlock(\n withUtils(\n withMaxBlocks(\n withUndoRedo(\n withPatches(\n withPortableTextSelections(\n withEditableAPI(withInsertBreak(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 type {PatchObservable} from '../../types/editor'\nimport {debugWithName} from '../../utils/debug'\nimport {KEY_TO_SLATE_ELEMENT, KEY_TO_VALUE_ELEMENT} from '../../utils/weakMaps'\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 keyGenerator: () => string\n maxBlocks: number | undefined\n patches$?: PatchObservable\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 {patches$, portableTextEditor, readOnly, maxBlocks, keyGenerator} =\n 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 keyGenerator,\n maxBlocks,\n patches$,\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 keyGenerator,\n maxBlocks,\n patches$,\n portableTextEditor,\n readOnly,\n })\n }, [\n keyGenerator,\n portableTextEditor,\n maxBlocks,\n readOnly,\n patches$,\n slateEditor,\n ])\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","import {randomKey} from '@sanity/util/content'\nimport {createContext, useContext} from 'react'\n\n/**\n * @public\n */\nexport const defaultKeyGenerator = (): string => randomKey(12)\n\n/**\n * A React context for sharing the editor's keyGenerator.\n */\nexport const PortableTextEditorKeyGeneratorContext =\n createContext<() => string>(defaultKeyGenerator)\n\n/**\n * Get the current editor selection from the React context.\n */\nexport const usePortableTextEditorKeyGenerator = (): (() => string) => {\n const keyGenerator = useContext(PortableTextEditorKeyGeneratorContext)\n\n if (keyGenerator === undefined) {\n throw new Error(\n `The \\`usePortableTextEditorKeyGenerator\\` hook must be used inside the <PortableTextEditor> component's context.`,\n )\n }\n return keyGenerator\n}\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 keyGenerator: () => string\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, keyGenerator} = props\n const {schemaTypes} = portableTextEditor\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 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 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 keyGenerator,\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, useMemo, useRef} from 'react'\nimport {Editor} from 'slate'\nimport {useSlate} from 'slate-react'\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 {usePortableTextEditorKeyGenerator} from '../hooks/usePortableTextEditorKeyGenerator'\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 keyGenerator = usePortableTextEditorKeyGenerator()\n const readOnly = usePortableTextEditorReadOnlyStatus()\n const {editorActor, getValue, onChange, value} = props\n const pendingPatches = useRef<Patch[]>([])\n\n const syncValue = useSyncValue({\n editorActor,\n keyGenerator,\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 const onFlushPendingPatchesThrottled = useMemo(() => {\n return 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 }, [onFlushPendingPatches, slateEditor])\n\n // Flush pending patches immediately on unmount\n useEffect(() => {\n return () => {\n onFlushPendingPatches()\n }\n }, [onFlushPendingPatches])\n\n // Subscribe to, and handle changes from the editor\n useEffect(() => {\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 onChange(event)\n break\n case 'loading': {\n onChange({type: 'loading', isLoading: true})\n break\n }\n case 'done loading': {\n onChange({type: 'loading', isLoading: false})\n break\n }\n case 'offline': {\n onChange({type: 'connection', value: 'offline'})\n break\n }\n case 'online': {\n onChange({type: 'connection', value: 'online'})\n break\n }\n case 'value changed': {\n onChange({type: 'value', value: event.value})\n break\n }\n case 'invalid value': {\n onChange({\n type: 'invalidValue',\n resolution: event.resolution,\n value: event.value,\n })\n break\n }\n case 'error': {\n onChange({\n ...event,\n level: 'warning',\n })\n break\n }\n default:\n onChange(event)\n }\n })\n return () => {\n debug('Unsubscribing to changes')\n sub.unsubscribe()\n }\n }, [editorActor, onFlushPendingPatchesThrottled, 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', () => {\n if (portableTextEditor.props.patches$) {\n handleOnline()\n }\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [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","import type {Patch} from '@portabletext/patches'\nimport type {PortableTextBlock} from '@sanity/types'\nimport type {FocusEvent} from 'react'\nimport {\n assertEvent,\n assign,\n emit,\n enqueueActions,\n fromCallback,\n setup,\n type ActorRefFrom,\n} from 'xstate'\nimport type {EditorSelection, InvalidValueResolution} from '../types/editor'\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 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 | EditorEmittedEvent\n\ntype EditorEmittedEvent =\n | {type: 'ready'}\n | PatchEvent\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 pendingEvents: Array<PatchEvent | MutationEvent>\n },\n events: {} as EditorEvent,\n emitted: {} as EditorEmittedEvent,\n },\n actions: {\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 },\n actors: {\n networkLogic,\n },\n}).createMachine({\n id: 'editor',\n context: {\n pendingEvents: [],\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 'done loading': {actions: emit({type: 'done loading'})},\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 {EditorChanges, 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 type {\n ArrayDefinition,\n ArraySchemaType,\n BlockSchemaType,\n ObjectSchemaType,\n Path,\n PortableTextBlock,\n PortableTextChild,\n PortableTextObject,\n SpanSchemaType,\n} from '@sanity/types'\nimport {Component, type MutableRefObject, type PropsWithChildren} from 'react'\nimport {Subject} from 'rxjs'\nimport {createActor, type Subscription} from 'xstate'\nimport type {\n EditableAPI,\n EditableAPIDeleteOptions,\n EditorChange,\n EditorChanges,\n EditorSelection,\n MutationChange,\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 {editorMachine, type EditorActor} from './editor-machine'\nimport {PortableTextEditorContext} from './hooks/usePortableTextEditor'\nimport {\n defaultKeyGenerator,\n PortableTextEditorKeyGeneratorContext,\n} from './hooks/usePortableTextEditorKeyGenerator'\nimport {PortableTextEditorSelectionProvider} from './hooks/usePortableTextEditorSelection'\nimport {PortableTextEditorReadOnlyContext} from './hooks/usePortableTextReadOnly'\n\nconst debug = debugWithName('component:PortableTextEditor')\n\n/**\n * Props for the PortableTextEditor component\n *\n * @public\n */\nexport type PortableTextEditorProps = PropsWithChildren<{\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 * 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 * 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 * A ref to the editor instance\n */\n editorRef?: MutableRefObject<PortableTextEditor | null>\n}>\n\n/**\n * The main Portable Text Editor component.\n * @public\n */\nexport class PortableTextEditor extends Component<PortableTextEditorProps> {\n /**\n * @internal\n * Don't use this API directly. It's subject to change.\n */\n public editorActor: EditorActor\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\n constructor(props: PortableTextEditorProps) {\n super(props)\n\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.editorActor = createActor(editorMachine)\n this.editorActor.start()\n\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n props.schemaType.hasOwnProperty('jsonType')\n ? props.schemaType\n : compileType(props.schemaType),\n )\n }\n\n componentDidUpdate(prevProps: PortableTextEditorProps) {\n // Set up the schema type lookup table again if the source schema type changes\n if (this.props.schemaType !== prevProps.schemaType) {\n this.schemaTypes = getPortableTextMemberSchemaTypes(\n this.props.schemaType.hasOwnProperty('jsonType')\n ? this.props.schemaType\n : compileType(this.props.schemaType),\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 {value, children, patches$, incomingPatches$} = this.props\n const _patches$ = incomingPatches$ || patches$ // Backward compatibility\n\n const maxBlocks =\n typeof this.props.maxBlocks === 'undefined'\n ? undefined\n : Number.parseInt(this.props.maxBlocks.toString(), 10) || undefined\n\n const readOnly = Boolean(this.props.readOnly)\n const keyGenerator = this.props.keyGenerator || defaultKeyGenerator\n return (\n <SlateContainer\n keyGenerator={keyGenerator}\n maxBlocks={maxBlocks}\n patches$={_patches$}\n portableTextEditor={this}\n readOnly={readOnly}\n >\n <PortableTextEditorKeyGeneratorContext.Provider value={keyGenerator}>\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 this.props.onChange(change)\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={value}\n />\n {children}\n </PortableTextEditorSelectionProvider>\n </PortableTextEditorReadOnlyContext.Provider>\n </PortableTextEditorContext.Provider>\n </PortableTextEditorKeyGeneratorContext.Provider>\n </SlateContainer>\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 = (\n editor: PortableTextEditor,\n type: ObjectSchemaType,\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 = (\n editor: PortableTextEditor,\n type: SpanSchemaType | ObjectSchemaType,\n value?: {[prop: string]: unknown},\n ): Path | undefined => {\n debug(`Host inserting child`)\n return editor.editable?.insertChild(type, value)\n }\n static insertBlock = (\n editor: PortableTextEditor,\n type: BlockSchemaType | ObjectSchemaType,\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 = (\n editor: PortableTextEditor,\n type: ObjectSchemaType,\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","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 {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 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 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 = portableTextEditor.editorActor.on('blur', () => {\n setFocused(false)\n setSelected(false)\n })\n\n const onFocus = portableTextEditor.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 = portableTextEditor.editorActor.on(\n 'selection',\n (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\n return () => {\n onBlur.unsubscribe()\n onFocus.unsubscribe()\n onSelection.unsubscribe()\n }\n }, [\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","import type {PortableTextBlock} from '@sanity/types'\nimport {isEqual, noop} from 'lodash'\nimport {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type CSSProperties,\n type FocusEventHandler,\n type ForwardedRef,\n type HTMLProps,\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 EditorChange,\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 {usePortableTextEditor} from './hooks/usePortableTextEditor'\nimport {usePortableTextEditorKeyGenerator} from './hooks/usePortableTextEditorKeyGenerator'\nimport {usePortableTextEditorReadOnlyStatus} from './hooks/usePortableTextReadOnly'\nimport {createWithHotkeys, createWithInsertData} from './plugins'\nimport {PortableTextEditor} from './PortableTextEditor'\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(function PortableTextEditable(\n props: PortableTextEditableProps &\n Omit<HTMLProps<HTMLDivElement>, 'as' | 'onPaste' | 'onBeforeInput'>,\n forwardedRef: ForwardedRef<HTMLDivElement>,\n) {\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 keyGenerator = usePortableTextEditorKeyGenerator()\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, schemaTypes} = portableTextEditor\n const slateEditor = useSlate()\n\n const blockTypeName = schemaTypes.block.name\n\n // React/UI-specific plugins\n const withInsertData = useMemo(\n () => createWithInsertData(editorActor, schemaTypes, keyGenerator),\n [editorActor, keyGenerator, schemaTypes],\n )\n const withHotKeys = useMemo(\n () => createWithHotkeys(schemaTypes, portableTextEditor, hotkeys),\n [hotkeys, portableTextEditor, schemaTypes],\n )\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 if (readOnly) {\n debug('Editable is in read only mode')\n return withInsertData(slateEditor)\n }\n debug('Editable is in edit mode')\n return withInsertData(withHotKeys(slateEditor))\n }, [readOnly, slateEditor, withHotKeys, withInsertData])\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 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 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 }, [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 if (rangeDecorationState.length > 0) {\n setRangeDecorationsState([])\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 // Store reference to original apply function (see below for usage in useEffect)\n const originalApply = useMemo(() => slateEditor.apply, [slateEditor])\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 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 }, [originalApply, 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 [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 (error) {\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"],"names":["debug","Element","dragPosition","block","schemaType","SlateElement","ObjectNode","diffMatchPatch","isPortableTextSpan","SlatePath","markDef","isUndoing","isRedoing","apply","diff","debugVerbose","parsePatch","diffMatchPatchApplyPatches","makeDiff","items","position","normalizedIdx","SlateText","decorators","SlateRange","SlateEditable"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAM,WAAW;AAEFA,QAAM,QAAQ;AACtB,SAAS,cAAc,MAA8B;AAC1D,QAAM,YAAY,GAAG,QAAQ,GAAG,IAAI;AAChC,SAAAA,WAASA,QAAM,QAAQ,SAAS,IAC3BA,QAAM,SAAS,IAEjBA,QAAM,QAAQ;AACvB;ACIgB,SAAA,gBACd,OACA,OACA,OACa;AACb,QAAM,YAAY,CAAC,MAAM,KAAK,CAAC,CAAC;AAChC,MAAI,CAAC;AACI,WAAA;AAET,QAAM,QAAQ,MAAM,UAAU,CAAC,CAAC;AAChC,MAAI,CAAC;AACI,W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