@platejs/ai 50.2.2 → 50.3.4
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.
- package/dist/react/index.d.mts +1 -2
- package/dist/react/index.d.ts +1 -2
- package/dist/react/index.js +117 -2763
- package/dist/react/index.js.map +1 -1
- package/dist/react/index.mjs +30 -2676
- package/dist/react/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/react/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/ai/AIPlugin.ts","../../src/lib/BaseAIPlugin.ts","../../src/lib/transforms/insertAINodes.ts","../../src/lib/transforms/removeAIMarks.ts","../../src/lib/transforms/removeAINodes.ts","../../src/lib/transforms/undoAI.ts","../../src/lib/transforms/withAIBatch.ts","../../src/lib/utils/getEditorPrompt.ts","../../src/react/ai/utils/aiCommentToRange.ts","../../src/react/ai/utils/findTextRangeInBlock.tsx","../../../../node_modules/immer/src/utils/env.ts","../../../../node_modules/immer/src/utils/errors.ts","../../../../node_modules/immer/src/utils/common.ts","../../../../node_modules/immer/src/utils/plugins.ts","../../../../node_modules/immer/src/core/scope.ts","../../../../node_modules/immer/src/core/finalize.ts","../../../../node_modules/immer/src/core/proxy.ts","../../../../node_modules/immer/src/core/immerClass.ts","../../../../node_modules/immer/src/core/current.ts","../../../../node_modules/immer/src/plugins/patches.ts","../../../../node_modules/immer/src/plugins/mapset.ts","../../../../node_modules/immer/src/immer.ts","../../../../node_modules/slate/src/interfaces/path-ref.ts","../../../../node_modules/slate/src/interfaces/point-ref.ts","../../../../node_modules/slate/src/interfaces/range-ref.ts","../../../../node_modules/slate/src/utils/weak-maps.ts","../../../../node_modules/slate/src/interfaces/path.ts","../../../../../../../.yarn/berry/cache/@babel-runtime-npm-7.23.2-d013d6cf7e-10.zip/node_modules/@babel/runtime/helpers/esm/typeof.js","../../../../../../../.yarn/berry/cache/@babel-runtime-npm-7.23.2-d013d6cf7e-10.zip/node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../../../../../../../.yarn/berry/cache/@babel-runtime-npm-7.23.2-d013d6cf7e-10.zip/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../../../../../../../.yarn/berry/cache/@babel-runtime-npm-7.23.2-d013d6cf7e-10.zip/node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../../../node_modules/slate/src/interfaces/transforms/general.ts","../../../../node_modules/slate/src/interfaces/transforms/node.ts","../../../../node_modules/slate/src/interfaces/transforms/selection.ts","../../../../node_modules/slate/src/utils/is-object.ts","../../../../node_modules/slate/src/utils/deep-equal.ts","../../../../../../../.yarn/berry/cache/@babel-runtime-npm-7.23.2-d013d6cf7e-10.zip/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../../../../../../../.yarn/berry/cache/@babel-runtime-npm-7.23.2-d013d6cf7e-10.zip/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js","../../../../node_modules/slate/src/interfaces/range.ts","../../../../node_modules/slate/src/interfaces/element.ts","../../../../node_modules/slate/src/interfaces/node.ts","../../../../node_modules/slate/src/interfaces/operation.ts","../../../../node_modules/slate/src/editor/is-editor.ts","../../../../node_modules/slate/src/interfaces/editor.ts","../../../../node_modules/slate/src/interfaces/location.ts","../../../../node_modules/slate/src/interfaces/point.ts","../../../../node_modules/slate/src/interfaces/scrubber.ts","../../../../node_modules/slate/src/interfaces/text.ts","../../../../node_modules/slate/src/utils/get-default-insert-location.ts","../../../../node_modules/slate/src/utils/match-path.ts","../../../../node_modules/slate/src/utils/string.ts","../../../../node_modules/slate/src/interfaces/transforms/text.ts","../../../../node_modules/slate/src/interfaces/transforms/index.ts","../../../../node_modules/slate/src/core/batch-dirty-paths.ts","../../../../node_modules/slate/src/core/update-dirty-paths.ts","../../../../node_modules/slate/src/core/apply.ts","../../../../node_modules/slate/src/core/get-dirty-paths.ts","../../../../node_modules/slate/src/core/get-fragment.ts","../../../../node_modules/slate/src/core/normalize-node.ts","../../../../node_modules/slate/src/core/should-normalize.ts","../../../../node_modules/slate/src/editor/above.ts","../../../../node_modules/slate/src/editor/add-mark.ts","../../../../node_modules/slate/src/editor/after.ts","../../../../node_modules/slate/src/editor/before.ts","../../../../node_modules/slate/src/editor/delete-backward.ts","../../../../node_modules/slate/src/editor/delete-forward.ts","../../../../node_modules/slate/src/editor/delete-fragment.ts","../../../../node_modules/slate/src/editor/edges.ts","../../../../node_modules/slate/src/editor/element-read-only.ts","../../../../node_modules/slate/src/editor/end.ts","../../../../node_modules/slate/src/editor/first.ts","../../../../node_modules/slate/src/editor/fragment.ts","../../../../node_modules/slate/src/editor/get-void.ts","../../../../node_modules/slate/src/editor/has-blocks.ts","../../../../node_modules/slate/src/editor/has-inlines.ts","../../../../node_modules/slate/src/editor/has-path.ts","../../../../node_modules/slate/src/editor/has-texts.ts","../../../../node_modules/slate/src/editor/insert-break.ts","../../../../node_modules/slate/src/editor/insert-node.ts","../../../../node_modules/slate/src/editor/insert-soft-break.ts","../../../../node_modules/slate/src/editor/insert-text.ts","../../../../node_modules/slate/src/editor/is-block.ts","../../../../node_modules/slate/src/editor/is-edge.ts","../../../../node_modules/slate/src/editor/is-empty.ts","../../../../node_modules/slate/src/editor/is-end.ts","../../../../node_modules/slate/src/editor/is-normalizing.ts","../../../../node_modules/slate/src/editor/is-start.ts","../../../../node_modules/slate/src/editor/last.ts","../../../../node_modules/slate/src/editor/leaf.ts","../../../../node_modules/slate/src/editor/levels.ts","../../../../node_modules/slate/src/editor/marks.ts","../../../../node_modules/slate/src/editor/next.ts","../../../../node_modules/slate/src/editor/node.ts","../../../../node_modules/slate/src/editor/nodes.ts","../../../../node_modules/slate/src/editor/normalize.ts","../../../../node_modules/slate/src/editor/parent.ts","../../../../node_modules/slate/src/editor/path-ref.ts","../../../../node_modules/slate/src/editor/path-refs.ts","../../../../node_modules/slate/src/editor/path.ts","../../../../node_modules/slate/src/editor/point-ref.ts","../../../../node_modules/slate/src/editor/point-refs.ts","../../../../node_modules/slate/src/editor/point.ts","../../../../node_modules/slate/src/editor/positions.ts","../../../../node_modules/slate/src/editor/previous.ts","../../../../node_modules/slate/src/editor/range-ref.ts","../../../../node_modules/slate/src/editor/range-refs.ts","../../../../node_modules/slate/src/editor/range.ts","../../../../node_modules/slate/src/editor/remove-mark.ts","../../../../node_modules/slate/src/editor/set-normalizing.ts","../../../../node_modules/slate/src/editor/start.ts","../../../../node_modules/slate/src/editor/string.ts","../../../../node_modules/slate/src/editor/unhang-range.ts","../../../../node_modules/slate/src/editor/without-normalizing.ts","../../../../node_modules/slate/src/editor/should-merge-nodes-remove-prev-node.ts","../../../../node_modules/slate/src/transforms-text/delete-text.ts","../../../../node_modules/slate/src/transforms-text/insert-fragment.ts","../../../../node_modules/slate/src/transforms-selection/collapse.ts","../../../../node_modules/slate/src/transforms-selection/deselect.ts","../../../../node_modules/slate/src/transforms-selection/move.ts","../../../../node_modules/slate/src/transforms-selection/select.ts","../../../../node_modules/slate/src/transforms-selection/set-point.ts","../../../../node_modules/slate/src/transforms-selection/set-selection.ts","../../../../node_modules/slate/src/transforms-node/insert-nodes.ts","../../../../node_modules/slate/src/transforms-node/lift-nodes.ts","../../../../node_modules/slate/src/transforms-node/merge-nodes.ts","../../../../node_modules/slate/src/transforms-node/move-nodes.ts","../../../../node_modules/slate/src/transforms-node/remove-nodes.ts","../../../../node_modules/slate/src/transforms-node/set-nodes.ts","../../../../node_modules/slate/src/transforms-node/split-nodes.ts","../../../../node_modules/slate/src/transforms-node/unset-nodes.ts","../../../../node_modules/slate/src/transforms-node/unwrap-nodes.ts","../../../../node_modules/slate/src/transforms-node/wrap-nodes.ts","../../../../node_modules/slate/src/create-editor.ts","../../src/react/ai-chat/AIChatPlugin.ts","../../src/react/ai-chat/transforms/acceptAIChat.ts","../../src/react/ai-chat/transforms/insertBelowAIChat.ts","../../src/react/ai-chat/transforms/replaceSelectionAIChat.ts","../../src/react/ai-chat/transforms/removeAnchorAIChat.ts","../../src/react/ai-chat/utils/resetAIChat.ts","../../src/react/ai-chat/utils/submitAIChat.ts","../../src/react/ai-chat/withAIChat.ts","../../src/react/ai-chat/hooks/useAIChatEditor.ts","../../src/react/ai-chat/hooks/useChatChunk.ts","../../src/react/ai-chat/utils/getLastAssistantMessage.ts","../../src/react/ai-chat/hooks/useEditorChat.ts","../../src/react/ai-chat/streaming/streamDeserializeInlineMd.ts","../../src/react/ai-chat/streaming/streamDeserializeMd.ts","../../src/react/ai-chat/streaming/utils/utils.ts","../../src/react/ai-chat/streaming/utils/escapeInput.ts","../../src/react/ai-chat/streaming/utils/getListNode.ts","../../src/react/ai-chat/streaming/utils/isSameNode.ts","../../src/react/ai-chat/streaming/utils/nodesWithProps.ts","../../src/react/ai-chat/streaming/streamInsertChunk.ts","../../src/react/ai-chat/streaming/streamSerializeMd.ts","../../src/react/ai-chat/utils/applyAISuggestions.ts","../../src/react/copilot/CopilotPlugin.tsx","../../src/react/copilot/renderCopilotBelowNodes.tsx","../../src/react/copilot/transforms/acceptCopilot.ts","../../src/react/copilot/transforms/acceptCopilotNextWord.ts","../../src/react/copilot/utils/callCompletionApi.ts","../../src/react/copilot/utils/getNextWord.ts","../../src/react/copilot/utils/triggerCopilotSuggestion.ts","../../src/react/copilot/utils/withoutAbort.ts","../../src/react/copilot/withCopilot.ts"],"sourcesContent":["import type { ExtendConfig } from 'platejs';\n\nimport { toPlatePlugin } from 'platejs/react';\n\nimport { type BaseAIPluginConfig, BaseAIPlugin } from '../../lib';\n\nexport type AIPluginConfig = ExtendConfig<BaseAIPluginConfig>;\n\nexport const AIPlugin = toPlatePlugin(BaseAIPlugin);\n","import {\n type OmitFirst,\n type PluginConfig,\n bindFirst,\n createTSlatePlugin,\n KEYS,\n} from 'platejs';\n\nimport { removeAIMarks, undoAI } from './transforms';\nimport { insertAINodes } from './transforms/insertAINodes';\nimport { removeAINodes } from './transforms/removeAINodes';\n\nexport type BaseAIPluginConfig = PluginConfig<\n 'ai',\n {},\n {},\n {\n ai: {\n insertNodes: OmitFirst<typeof insertAINodes>;\n removeMarks: OmitFirst<typeof removeAIMarks>;\n removeNodes: OmitFirst<typeof removeAINodes>;\n };\n }\n>;\n\nexport const BaseAIPlugin = createTSlatePlugin({\n key: KEYS.ai,\n node: { isDecoration: false, isLeaf: true },\n}).extendTransforms(({ editor }) => ({\n insertNodes: bindFirst(insertAINodes, editor),\n removeMarks: bindFirst(removeAIMarks, editor),\n removeNodes: bindFirst(removeAINodes, editor),\n undo: bindFirst(undoAI, editor),\n}));\n","import type { Descendant, Path, SlateEditor } from 'platejs';\n\nexport const insertAINodes = (\n editor: SlateEditor,\n nodes: Descendant[],\n {\n target,\n }: {\n target?: Path;\n } = {}\n) => {\n if (!target && !editor.selection?.focus.path) return;\n\n const aiNodes = nodes.map((node) => ({\n ...node,\n ai: true,\n }));\n\n editor.tf.withoutNormalizing(() => {\n editor.tf.insertNodes(aiNodes, {\n at: editor.api.end(target || editor.selection!.focus.path),\n select: true,\n });\n editor.tf.collapse({ edge: 'end' });\n });\n};\n","import { type SlateEditor, type TLocation, getPluginType, KEYS } from 'platejs';\n\nexport const removeAIMarks = (\n editor: SlateEditor,\n { at = [] }: { at?: TLocation } = {}\n) => {\n const nodeType = getPluginType(editor, KEYS.ai);\n\n editor.tf.unsetNodes(nodeType, {\n at,\n match: (n) => (n as any)[nodeType],\n });\n};\n","import { type Path, type SlateEditor, TextApi } from 'platejs';\n\nexport const removeAINodes = (\n editor: SlateEditor,\n { at = [] }: { at?: Path } = {}\n) => {\n editor.tf.removeNodes({\n at,\n match: (n) => TextApi.isText(n) && !!(n as any).ai,\n });\n};\n","import type { SlateEditor } from 'platejs';\n\nimport { getTransientSuggestionKey } from '@platejs/suggestion';\n\nexport const undoAI = (editor: SlateEditor) => {\n const hasAINodeOrAISuggestion =\n editor.api.some({\n at: [],\n match: (n) => !!(n as any).ai,\n }) ||\n editor.api.some({\n at: [],\n match: (n) => !!n[getTransientSuggestionKey()],\n });\n\n if ((editor.history.undos.at(-1) as any)?.ai && hasAINodeOrAISuggestion) {\n editor.undo();\n editor.history.redos.pop();\n }\n};\n","import type { History, SlateEditor } from 'platejs';\n\nexport type AIBatch = History['undos'][number] & { ai?: boolean };\n\nexport const withAIBatch = (\n editor: SlateEditor,\n fn: () => void,\n {\n split,\n }: {\n split?: boolean;\n } = {}\n) => {\n if (split) {\n editor.tf.withNewBatch(fn);\n } else {\n editor.tf.withMerging(fn);\n }\n\n const lastBatch = editor.history.undos?.at(-1) as AIBatch | undefined;\n\n if (lastBatch) {\n lastBatch.ai = true;\n }\n};\n","import { isSelecting } from '@platejs/selection';\nimport { type SlateEditor, KEYS } from 'platejs';\n\nexport type EditorPrompt =\n | ((params: EditorPromptParams) => string)\n | PromptConfig\n | string;\n\nexport interface EditorPromptParams {\n editor: SlateEditor;\n isBlockSelecting: boolean;\n isSelecting: boolean;\n}\n\nexport interface PromptConfig {\n default: string;\n blockSelecting?: string;\n selecting?: string;\n}\n\nconst createPromptFromConfig = (\n config: PromptConfig,\n params: EditorPromptParams\n): string => {\n const { isBlockSelecting, isSelecting } = params;\n\n if (isBlockSelecting && config.blockSelecting) {\n return config.blockSelecting ?? config.default;\n } else if (isSelecting && config.selecting) {\n return config.selecting ?? config.default;\n } else {\n return config.default;\n }\n};\n\nexport const getEditorPrompt = (\n editor: SlateEditor,\n {\n prompt = '',\n }: {\n prompt?: EditorPrompt;\n }\n): string => {\n const params: EditorPromptParams = {\n editor,\n isBlockSelecting: editor.getOption(\n { key: KEYS.blockSelection },\n 'isSelectingSome'\n ),\n isSelecting: isSelecting(editor),\n };\n\n let promptText = '';\n\n if (typeof prompt === 'function') {\n promptText = prompt(params);\n } else if (typeof prompt === 'object') {\n promptText = createPromptFromConfig(prompt, params);\n } else {\n promptText = prompt;\n }\n\n return promptText;\n};\n","import { deserializeMd } from '@platejs/markdown';\nimport {\n type NodeEntry,\n type Range,\n type SlateEditor,\n type TElement,\n NodeApi,\n} from 'platejs';\n\nimport type { TComment } from '../../ai-chat/internal/types';\n\nimport { findTextRangeInBlock } from './findTextRangeInBlock';\n\nexport const aiCommentToRange = (\n editor: SlateEditor,\n aiComment: TComment\n): Range | undefined => {\n const { blockId, content } = aiComment;\n\n const contentNodes = deserializeMd(editor, content);\n\n let firstBlock: NodeEntry<TElement> | undefined;\n\n const ranges: Range[] = [];\n contentNodes.forEach((node, index) => {\n let currentBlock: NodeEntry<TElement> | undefined;\n\n if (index === 0) {\n firstBlock = editor.api.node<TElement>({ id: blockId, at: [] });\n currentBlock = firstBlock;\n } else {\n if (!firstBlock) return;\n\n const [_, firstBlockPath] = firstBlock;\n\n const blockPath = [firstBlockPath[0] + index];\n currentBlock = editor.api.node(blockPath);\n }\n\n if (!currentBlock) return;\n\n const range = findTextRangeInBlock({\n block: currentBlock,\n findText: NodeApi.string(node),\n });\n\n if (!range) return;\n\n ranges.push(range);\n });\n\n if (ranges.length === 0) return;\n\n if (ranges.length > 1) {\n const startRange = ranges[0];\n const endRange = ranges.at(-1)!;\n\n return {\n anchor: startRange.anchor,\n focus: endRange.focus,\n };\n }\n\n if (ranges.length === 1) {\n return ranges[0];\n }\n};\n","import type { NodeEntry } from 'platejs';\n\nimport { distance } from 'fastest-levenshtein';\nimport { type Path, type Range, Node } from 'slate';\n\nfunction maxAllowedDistance(len: number): number {\n if (len <= 2) return 0;\n if (len <= 5) return 1;\n if (len <= 10) return 2;\n if (len <= 20) return 3;\n // Maximum allowed distance is 5, regardless of text length\n return 5;\n}\n\n/** Find text within a block, supporting fuzzy matching. */\nexport function findTextRangeInBlock({\n block,\n findText,\n}: {\n block: NodeEntry;\n findText: string;\n}): Range | null {\n const [blockNode, blockPath] = block;\n\n // Collect all text content and map positions\n const textSegments: { offset: number; path: Path; text: string }[] = [];\n let fullText = '';\n\n // Iterate through all text nodes in the block\n for (const [textNode, textPath] of Node.texts(blockNode)) {\n const startOffset = fullText.length;\n // textPath is relative to blockNode, not absolute\n const absolutePath = [...blockPath, ...textPath];\n textSegments.push({\n offset: startOffset,\n path: absolutePath,\n text: textNode.text,\n });\n fullText += textNode.text;\n }\n\n if (!fullText) return null;\n\n // Try exact match first\n let matchStart = fullText.indexOf(findText);\n let matchEnd = matchStart >= 0 ? matchStart + findText.length : -1;\n\n // If no exact match, try fuzzy matching\n if (matchStart === -1) {\n const maxDist = maxAllowedDistance(findText.length);\n let bestMatch = { distance: Infinity, end: -1, start: -1 };\n\n // Sliding window to find best fuzzy match\n for (let i = 0; i <= fullText.length - findText.length; i++) {\n // Try different lengths around the target length\n for (let lenOffset = -maxDist; lenOffset <= maxDist; lenOffset++) {\n const len = findText.length + lenOffset;\n if (len <= 0 || i + len > fullText.length) continue;\n\n const candidate = fullText.slice(i, i + len);\n const dist = distance(candidate, findText);\n\n if (dist <= maxDist && dist < bestMatch.distance) {\n bestMatch = { distance: dist, end: i + len, start: i };\n }\n }\n }\n\n if (bestMatch.start !== -1) {\n matchStart = bestMatch.start;\n matchEnd = bestMatch.end;\n }\n }\n\n // If still no match, try prefix matching as fallback\n if (matchStart === -1) {\n // Find longest prefix match\n for (let prefixLen = findText.length - 1; prefixLen > 0; prefixLen--) {\n const prefix = findText.slice(0, Math.max(0, prefixLen));\n const idx = fullText.indexOf(prefix);\n if (idx !== -1) {\n matchStart = idx;\n matchEnd = idx + prefixLen;\n break;\n }\n }\n }\n\n if (matchStart === -1) return null;\n\n // Convert character offsets to Slate paths and offsets\n const findPoint = (\n charOffset: number,\n isEnd = false\n ): { offset: number; path: Path } => {\n const accumulated = 0;\n\n // For start positions, if offset lands exactly at the beginning of a segment, use that segment\n if (!isEnd) {\n for (const segment of textSegments) {\n if (charOffset === segment.offset) {\n return {\n offset: 0,\n path: segment.path,\n };\n }\n }\n }\n\n // Normal search through segments\n for (const segment of textSegments) {\n const segmentEnd = segment.offset + segment.text.length;\n\n if (charOffset >= segment.offset && charOffset <= segmentEnd) {\n const localOffset = charOffset - segment.offset;\n return {\n offset: localOffset,\n path: segment.path,\n };\n }\n }\n\n // Fallback to last position\n const lastSegment = textSegments.at(-1);\n if (!lastSegment) {\n return { offset: 0, path: blockPath };\n }\n return {\n offset: lastSegment.text.length,\n path: lastSegment.path,\n };\n };\n\n const anchor = findPoint(matchStart, false);\n const focus = findPoint(matchEnd, true);\n\n return {\n anchor,\n focus,\n };\n}\n","// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","export const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = typeof e === \"function\" ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie,\n\tStrictMode\n} from \"../internal\"\n\nexport const getPrototypeOf = Object.getPrototypeOf\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original<T>(value: T): T | undefined\nexport function original(value: Drafted<any>): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/**\n * Each iterates a map, set or array.\n * Or, if any other kind of object, all of its own properties.\n * Regardless whether they are enumerable or symbols\n */\nexport function each<T extends Objectish>(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void\n): void\nexport function each(obj: any, iter: any) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\tReflect.ownKeys(obj).forEach(key => {\n\t\t\titer(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: Array.isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === ArchType.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (t === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: StrictMode) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\n\tconst isPlain = isPlainObject(base)\n\n\tif (strict === true || (strict === \"class_only\" && !isPlain)) {\n\t\t// Perform a strict copy\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(base)\n\t\tdelete descriptors[DRAFT_STATE as any]\n\t\tlet keys = Reflect.ownKeys(descriptors)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tconst key: any = keys[i]\n\t\t\tconst desc = descriptors[key]\n\t\t\tif (desc.writable === false) {\n\t\t\t\tdesc.writable = true\n\t\t\t\tdesc.configurable = true\n\t\t\t}\n\t\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t\t// with libraries that trap values, like mobx or vue\n\t\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\t\tif (desc.get || desc.set)\n\t\t\t\tdescriptors[key] = {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\t\tvalue: base[key]\n\t\t\t\t}\n\t\t}\n\t\treturn Object.create(getPrototypeOf(base), descriptors)\n\t} else {\n\t\t// perform a sloppy copy\n\t\tconst proto = getPrototypeOf(base)\n\t\tif (proto !== null && isPlain) {\n\t\t\treturn {...base} // assumption: better inner class optimization than the assign below\n\t\t}\n\t\tconst obj = Object.create(proto)\n\t\treturn Object.assign(obj, base)\n\t}\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze<T>(obj: T, deep?: boolean): T\nexport function freeze<T>(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep)\n\t\t// See #590, don't recurse into non-enumerable / Symbol properties when freezing\n\t\t// So use Object.entries (only string-like, enumerables) instead of each()\n\t\tObject.entries(obj).forEach(([key, value]) => freeze(value, true))\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\treturn Object.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\tbase: any,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_<T>(draft: T, patches: readonly Patch[]): T\n\t}\n\tMapSet?: {\n\t\tproxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T\n\t\tproxySet_<T extends AnySet>(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin<K extends keyof Plugins>(\n\tpluginKey: K\n): Exclude<Plugins[K], undefined> {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin<K extends keyof Plugins>(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map<any, boolean> | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted<AnyMap, MapState>\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map<any, Drafted> // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted<AnySet, SetState>\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(value, (key, childValue) =>\n\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path)\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result = state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\t// And we let finalizeProperty know it needs to re-add non-draft children back to the target\n\t\tlet resultEach = result\n\t\tlet isSet = false\n\t\tif (state.type_ === ArchType.Set) {\n\t\t\tresultEach = new Set(result)\n\t\t\tresult.clear()\n\t\t\tisSet = true\n\t\t}\n\t\teach(resultEach, (key, childValue) =>\n\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path, isSet)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath,\n\ttargetIsSet?: boolean\n) {\n\tif (process.env.NODE_ENV !== \"production\" && childValue === targetObject)\n\t\tdie(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ArchType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude<ImmerState, SetState>).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t} else if (targetIsSet) {\n\t\ttargetObject.add(childValue)\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// Immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\t// Per #590, we never freeze symbolic properties. Just to make sure don't accidentally interfere\n\t\t// with other frameworks.\n\t\tif (\n\t\t\t(!parentState || !parentState.scope_.parent_) &&\n\t\t\ttypeof prop !== \"symbol\" &&\n\t\t\tObject.prototype.propertyIsEnumerable.call(targetObject, prop)\n\t\t)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n","import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\tImmerScope\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted<AnyObject, ProxyObjectState>\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted<AnyArray, ProxyArrayState>\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy<T extends Objectish>(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted<T, ProxyState> {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler<object | Array<any>> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler<ProxyState> = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(value, state))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\t(state.copy_![prop] === value &&\n\t\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t\t(value !== undefined || prop in state.copy_)) ||\n\t\t\t// special case: NaN\n\t\t\t(Number.isNaN(value) && Number.isNaN(state.copy_![prop]))\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\tif (state.copy_) {\n\t\t\tdelete state.copy_[prop]\n\t\t}\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ArchType.Array || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop as any)))\n\t\tdie(13)\n\t// @ts-ignore\n\treturn arrayTraps.set!.call(this, state, prop, undefined)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (\n\t\tprocess.env.NODE_ENV !== \"production\" &&\n\t\tprop !== \"length\" &&\n\t\tisNaN(parseInt(prop as any))\n\t)\n\t\tdie(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {\n\tbase_: any\n\tcopy_: any\n\tscope_: ImmerScope\n}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(\n\t\t\tstate.base_,\n\t\t\tstate.scope_.immer_.useStrictShallowCopy_\n\t\t)\n\t}\n}\n","import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport type StrictMode = boolean | \"class_only\";\n\nexport class Immer implements ProducersFns {\n\tautoFreeze_: boolean = true\n\tuseStrictShallowCopy_: StrictMode = false\n\n\tconstructor(config?: {\n\t\tautoFreeze?: boolean\n\t\tuseStrictShallowCopy?: StrictMode\n\t}) {\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t\tif (typeof config?.useStrictShallowCopy === \"boolean\")\n\t\t\tthis.setUseStrictShallowCopy(config!.useStrictShallowCopy)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === undefined) result = base\n\t\t\tif (result === NOTHING) result = undefined\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\tif (patchListener) {\n\t\t\t\tconst p: Patch[] = []\n\t\t\t\tconst ip: Patch[] = []\n\t\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(base, result, p, ip)\n\t\t\t\tpatchListener(p, ip)\n\t\t\t}\n\t\t\treturn result\n\t\t} else die(1, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => base(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [result, patches!, inversePatches!]\n\t}\n\n\tcreateDraft<T extends Objectish>(base: T): Draft<T> {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft<D extends Draft<any>>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft<infer T> ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (!state || !state.isManual_) die(9)\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to enable strict shallow copy.\n\t *\n\t * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n\t */\n\tsetUseStrictShallowCopy(value: StrictMode) {\n\t\tthis.useStrictShallowCopy_ = value\n\t}\n\n\tapplyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy<T extends Objectish>(\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted<T, ImmerState> {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: createProxyProxy(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n","import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tisFrozen\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current<T>(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(10, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value) || isFrozen(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tif (state) {\n\t\tif (!state.modified_) return state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)\n\t} else {\n\t\tcopy = shallowCopy(value, true)\n\t}\n\t// recurse\n\teach(copy, (key, childValue) => {\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\tif (state) {\n\t\tstate.finalized_ = false\n\t}\n\treturn copy\n}\n","import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tProxyArrayState,\n\tMapState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tgetPrototypeOf,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tArchType,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING,\n\terrors\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst errorOffset = 16\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\terrors.push(\n\t\t\t'Sets cannot have \"replace\" patches.',\n\t\t\tfunction(op: string) {\n\t\t\t\treturn \"Unsupported patch operation: \" + op\n\t\t\t},\n\t\t\tfunction(path: string) {\n\t\t\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t\t\t},\n\t\t\t\"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n\t\t)\n\t}\n\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tswitch (state.type_) {\n\t\t\tcase ArchType.Object:\n\t\t\tcase ArchType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t\tcase ArchType.Array:\n\t\t\t\treturn generateArrayPatches(state, basePath, patches, inversePatches)\n\t\t\tcase ArchType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tif (assigned_[i] && copy_[i] !== base_[i]) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(base_[i])\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tfor (let i = copy_.length - 1; base_.length <= i; --i) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tinversePatches.push({\n\t\t\t\top: REMOVE,\n\t\t\t\tpath\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key)\n\t\t\tconst value = get(copy_!, key)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(op === REMOVE ? {op, path} : {op, path, value})\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\tbaseValue: any,\n\t\treplacement: any,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tpatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: baseValue\n\t\t})\n\t}\n\n\tfunction applyPatches_<T>(draft: T, patches: readonly Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tlet p = path[i]\n\t\t\t\tif (typeof p !== \"string\" && typeof p !== \"number\") {\n\t\t\t\t\tp = \"\" + p\n\t\t\t\t}\n\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === ArchType.Object || parentType === ArchType.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\")\n\t\t\t\t\tdie(errorOffset + 3)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(errorOffset + 2, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\tdie(errorOffset)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase ArchType.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase ArchType.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase ArchType.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(errorOffset + 1, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue<T>(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (Array.isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded<T>(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(\"Patches\", {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_\n\t})\n}\n","// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tdie,\n\tArchType,\n\teach\n} from \"../internal\"\n\nexport function enableMapSet() {\n\tclass DraftMap extends Map {\n\t\t[DRAFT_STATE]: MapState\n\n\t\tconstructor(target: AnyMap, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tset(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tif (state.base_.has(key)) {\n\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t} else {\n\t\t\t\tstate.assigned_!.delete(key)\n\t\t\t}\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tforEach(cb: (value: any, key: any, self: any) => void, thisArg?: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tget(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(value, state)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[Symbol.iterator]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.entries()\n\t\t}\n\t}\n\n\tfunction proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftMap(target, parent)\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tclass DraftSet extends Set {\n\t\t[DRAFT_STATE]: SetState\n\t\tconstructor(target: AnySet, parent?: ImmerState) {\n\t\t\tsuper()\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ArchType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false\n\t\t\t}\n\t\t}\n\n\t\tget size(): number {\n\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t}\n\n\t\thas(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tadd(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tdelete(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tclear() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tvalues(): IterableIterator<any> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tentries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tkeys(): IterableIterator<any> {\n\t\t\treturn this.values()\n\t\t}\n\n\t\t[Symbol.iterator]() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tforEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\t}\n\tfunction proxySet_<T extends AnySet>(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftSet(target, parent)\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(value, state)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"MapSet\", {proxyMap_, proxySet_})\n}\n","import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tWritableDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\tProducer,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze,\n\tObjectish,\n\tStrictMode\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\nexport const setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft<T>(value: T): Draft<T> {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable<T>(value: T): Immutable<T> {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\n","import { Operation, Path } from '..'\n\n/**\n * `PathRef` objects keep a specific path in a document synced over time as new\n * operations are applied to the editor. You can access their `current` property\n * at any time for the up-to-date path value.\n */\n\nexport interface PathRef {\n current: Path | null\n affinity: 'forward' | 'backward' | null\n unref(): Path | null\n}\n\nexport interface PathRefInterface {\n /**\n * Transform the path ref's current value by an operation.\n */\n transform: (ref: PathRef, op: Operation) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const PathRef: PathRefInterface = {\n transform(ref: PathRef, op: Operation): void {\n const { current, affinity } = ref\n\n if (current == null) {\n return\n }\n\n const path = Path.transform(current, op, { affinity })\n ref.current = path\n\n if (path == null) {\n ref.unref()\n }\n },\n}\n","import { Operation, Point } from '..'\nimport { TextDirection } from '../types/types'\n\n/**\n * `PointRef` objects keep a specific point in a document synced over time as new\n * operations are applied to the editor. You can access their `current` property\n * at any time for the up-to-date point value.\n */\n\nexport interface PointRef {\n current: Point | null\n affinity: TextDirection | null\n unref(): Point | null\n}\n\nexport interface PointRefInterface {\n /**\n * Transform the point ref's current value by an operation.\n */\n transform: (ref: PointRef, op: Operation) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const PointRef: PointRefInterface = {\n transform(ref: PointRef, op: Operation): void {\n const { current, affinity } = ref\n\n if (current == null) {\n return\n }\n\n const point = Point.transform(current, op, { affinity })\n ref.current = point\n\n if (point == null) {\n ref.unref()\n }\n },\n}\n","import { Operation, Range } from '..'\n\n/**\n * `RangeRef` objects keep a specific range in a document synced over time as new\n * operations are applied to the editor. You can access their `current` property\n * at any time for the up-to-date range value.\n */\n\nexport interface RangeRef {\n current: Range | null\n affinity: 'forward' | 'backward' | 'outward' | 'inward' | null\n unref(): Range | null\n}\n\nexport interface RangeRefInterface {\n /**\n * Transform the range ref's current value by an operation.\n */\n transform: (ref: RangeRef, op: Operation) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const RangeRef: RangeRefInterface = {\n transform(ref: RangeRef, op: Operation): void {\n const { current, affinity } = ref\n\n if (current == null) {\n return\n }\n\n const path = Range.transform(current, op, { affinity })\n ref.current = path\n\n if (path == null) {\n ref.unref()\n }\n },\n}\n","import { Editor, Path, PathRef, PointRef, RangeRef } from '..'\n\nexport const DIRTY_PATHS: WeakMap<Editor, Path[]> = new WeakMap()\nexport const DIRTY_PATH_KEYS: WeakMap<Editor, Set<string>> = new WeakMap()\nexport const FLUSHING: WeakMap<Editor, boolean> = new WeakMap()\nexport const NORMALIZING: WeakMap<Editor, boolean> = new WeakMap()\nexport const PATH_REFS: WeakMap<Editor, Set<PathRef>> = new WeakMap()\nexport const POINT_REFS: WeakMap<Editor, Set<PointRef>> = new WeakMap()\nexport const RANGE_REFS: WeakMap<Editor, Set<RangeRef>> = new WeakMap()\n","import {\n InsertNodeOperation,\n MergeNodeOperation,\n MoveNodeOperation,\n Operation,\n RemoveNodeOperation,\n SplitNodeOperation,\n} from '..'\nimport { TextDirection } from '../types/types'\n\n/**\n * `Path` arrays are a list of indexes that describe a node's exact position in\n * a Slate node tree. Although they are usually relative to the root `Editor`\n * object, they can be relative to any `Node` object.\n */\n\nexport type Path = number[]\n\nexport interface PathAncestorsOptions {\n reverse?: boolean\n}\n\nexport interface PathLevelsOptions {\n reverse?: boolean\n}\n\nexport interface PathTransformOptions {\n affinity?: TextDirection | null\n}\n\nexport interface PathInterface {\n /**\n * Get a list of ancestor paths for a given path.\n *\n * The paths are sorted from shallowest to deepest ancestor. However, if the\n * `reverse: true` option is passed, they are reversed.\n */\n ancestors: (path: Path, options?: PathAncestorsOptions) => Path[]\n\n /**\n * Get the common ancestor path of two paths.\n */\n common: (path: Path, another: Path) => Path\n\n /**\n * Compare a path to another, returning an integer indicating whether the path\n * was before, at, or after the other.\n *\n * Note: Two paths of unequal length can still receive a `0` result if one is\n * directly above or below the other. If you want exact matching, use\n * [[Path.equals]] instead.\n */\n compare: (path: Path, another: Path) => -1 | 0 | 1\n\n /**\n * Check if a path ends after one of the indexes in another.\n */\n endsAfter: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path ends at one of the indexes in another.\n */\n endsAt: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path ends before one of the indexes in another.\n */\n endsBefore: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is exactly equal to another.\n */\n equals: (path: Path, another: Path) => boolean\n\n /**\n * Check if the path of previous sibling node exists\n */\n hasPrevious: (path: Path) => boolean\n\n /**\n * Check if a path is after another.\n */\n isAfter: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is an ancestor of another.\n */\n isAncestor: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is before another.\n */\n isBefore: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is a child of another.\n */\n isChild: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is equal to or an ancestor of another.\n */\n isCommon: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is a descendant of another.\n */\n isDescendant: (path: Path, another: Path) => boolean\n\n /**\n * Check if a path is the parent of another.\n */\n isParent: (path: Path, another: Path) => boolean\n\n /**\n * Check is a value implements the `Path` interface.\n */\n isPath: (value: any) => value is Path\n\n /**\n * Check if a path is a sibling of another.\n */\n isSibling: (path: Path, another: Path) => boolean\n\n /**\n * Get a list of paths at every level down to a path. Note: this is the same\n * as `Path.ancestors`, but including the path itself.\n *\n * The paths are sorted from shallowest to deepest. However, if the `reverse:\n * true` option is passed, they are reversed.\n */\n levels: (path: Path, options?: PathLevelsOptions) => Path[]\n\n /**\n * Given a path, get the path to the next sibling node.\n */\n next: (path: Path) => Path\n\n /**\n * Returns whether this operation can affect paths or not. Used as an\n * optimization when updating dirty paths during normalization\n *\n * NOTE: This *must* be kept in sync with the implementation of 'transform'\n * below\n */\n operationCanTransformPath: (\n operation: Operation\n ) => operation is\n | InsertNodeOperation\n | RemoveNodeOperation\n | MergeNodeOperation\n | SplitNodeOperation\n | MoveNodeOperation\n\n /**\n * Given a path, return a new path referring to the parent node above it.\n */\n parent: (path: Path) => Path\n\n /**\n * Given a path, get the path to the previous sibling node.\n */\n previous: (path: Path) => Path\n\n /**\n * Get a path relative to an ancestor.\n */\n relative: (path: Path, ancestor: Path) => Path\n\n /**\n * Transform a path by an operation.\n */\n transform: (\n path: Path,\n operation: Operation,\n options?: PathTransformOptions\n ) => Path | null\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Path: PathInterface = {\n ancestors(path: Path, options: PathAncestorsOptions = {}): Path[] {\n const { reverse = false } = options\n let paths = Path.levels(path, options)\n\n if (reverse) {\n paths = paths.slice(1)\n } else {\n paths = paths.slice(0, -1)\n }\n\n return paths\n },\n\n common(path: Path, another: Path): Path {\n const common: Path = []\n\n for (let i = 0; i < path.length && i < another.length; i++) {\n const av = path[i]\n const bv = another[i]\n\n if (av !== bv) {\n break\n }\n\n common.push(av)\n }\n\n return common\n },\n\n compare(path: Path, another: Path): -1 | 0 | 1 {\n const min = Math.min(path.length, another.length)\n\n for (let i = 0; i < min; i++) {\n if (path[i] < another[i]) return -1\n if (path[i] > another[i]) return 1\n }\n\n return 0\n },\n\n endsAfter(path: Path, another: Path): boolean {\n const i = path.length - 1\n const as = path.slice(0, i)\n const bs = another.slice(0, i)\n const av = path[i]\n const bv = another[i]\n return Path.equals(as, bs) && av > bv\n },\n\n endsAt(path: Path, another: Path): boolean {\n const i = path.length\n const as = path.slice(0, i)\n const bs = another.slice(0, i)\n return Path.equals(as, bs)\n },\n\n endsBefore(path: Path, another: Path): boolean {\n const i = path.length - 1\n const as = path.slice(0, i)\n const bs = another.slice(0, i)\n const av = path[i]\n const bv = another[i]\n return Path.equals(as, bs) && av < bv\n },\n\n equals(path: Path, another: Path): boolean {\n return (\n path.length === another.length && path.every((n, i) => n === another[i])\n )\n },\n\n hasPrevious(path: Path): boolean {\n return path[path.length - 1] > 0\n },\n\n isAfter(path: Path, another: Path): boolean {\n return Path.compare(path, another) === 1\n },\n\n isAncestor(path: Path, another: Path): boolean {\n return path.length < another.length && Path.compare(path, another) === 0\n },\n\n isBefore(path: Path, another: Path): boolean {\n return Path.compare(path, another) === -1\n },\n\n isChild(path: Path, another: Path): boolean {\n return (\n path.length === another.length + 1 && Path.compare(path, another) === 0\n )\n },\n\n isCommon(path: Path, another: Path): boolean {\n return path.length <= another.length && Path.compare(path, another) === 0\n },\n\n isDescendant(path: Path, another: Path): boolean {\n return path.length > another.length && Path.compare(path, another) === 0\n },\n\n isParent(path: Path, another: Path): boolean {\n return (\n path.length + 1 === another.length && Path.compare(path, another) === 0\n )\n },\n\n isPath(value: any): value is Path {\n return (\n Array.isArray(value) &&\n (value.length === 0 || typeof value[0] === 'number')\n )\n },\n\n isSibling(path: Path, another: Path): boolean {\n if (path.length !== another.length) {\n return false\n }\n\n const as = path.slice(0, -1)\n const bs = another.slice(0, -1)\n const al = path[path.length - 1]\n const bl = another[another.length - 1]\n return al !== bl && Path.equals(as, bs)\n },\n\n levels(path: Path, options: PathLevelsOptions = {}): Path[] {\n const { reverse = false } = options\n const list: Path[] = []\n\n for (let i = 0; i <= path.length; i++) {\n list.push(path.slice(0, i))\n }\n\n if (reverse) {\n list.reverse()\n }\n\n return list\n },\n\n next(path: Path): Path {\n if (path.length === 0) {\n throw new Error(\n `Cannot get the next path of a root path [${path}], because it has no next index.`\n )\n }\n\n const last = path[path.length - 1]\n return path.slice(0, -1).concat(last + 1)\n },\n\n operationCanTransformPath(\n operation: Operation\n ): operation is\n | InsertNodeOperation\n | RemoveNodeOperation\n | MergeNodeOperation\n | SplitNodeOperation\n | MoveNodeOperation {\n switch (operation.type) {\n case 'insert_node':\n case 'remove_node':\n case 'merge_node':\n case 'split_node':\n case 'move_node':\n return true\n default:\n return false\n }\n },\n\n parent(path: Path): Path {\n if (path.length === 0) {\n throw new Error(`Cannot get the parent path of the root path [${path}].`)\n }\n\n return path.slice(0, -1)\n },\n\n previous(path: Path): Path {\n if (path.length === 0) {\n throw new Error(\n `Cannot get the previous path of a root path [${path}], because it has no previous index.`\n )\n }\n\n const last = path[path.length - 1]\n\n if (last <= 0) {\n throw new Error(\n `Cannot get the previous path of a first child path [${path}] because it would result in a negative index.`\n )\n }\n\n return path.slice(0, -1).concat(last - 1)\n },\n\n relative(path: Path, ancestor: Path): Path {\n if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {\n throw new Error(\n `Cannot get the relative path of [${path}] inside ancestor [${ancestor}], because it is not above or equal to the path.`\n )\n }\n\n return path.slice(ancestor.length)\n },\n\n transform(\n path: Path | null,\n operation: Operation,\n options: PathTransformOptions = {}\n ): Path | null {\n if (!path) return null\n\n // PERF: use destructing instead of immer\n const p = [...path]\n const { affinity = 'forward' } = options\n\n // PERF: Exit early if the operation is guaranteed not to have an effect.\n if (path.length === 0) {\n return p\n }\n\n switch (operation.type) {\n case 'insert_node': {\n const { path: op } = operation\n\n if (\n Path.equals(op, p) ||\n Path.endsBefore(op, p) ||\n Path.isAncestor(op, p)\n ) {\n p[op.length - 1] += 1\n }\n\n break\n }\n\n case 'remove_node': {\n const { path: op } = operation\n\n if (Path.equals(op, p) || Path.isAncestor(op, p)) {\n return null\n } else if (Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n }\n\n break\n }\n\n case 'merge_node': {\n const { path: op, position } = operation\n\n if (Path.equals(op, p) || Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n } else if (Path.isAncestor(op, p)) {\n p[op.length - 1] -= 1\n p[op.length] += position\n }\n\n break\n }\n\n case 'split_node': {\n const { path: op, position } = operation\n\n if (Path.equals(op, p)) {\n if (affinity === 'forward') {\n p[p.length - 1] += 1\n } else if (affinity === 'backward') {\n // Nothing, because it still refers to the right path.\n } else {\n return null\n }\n } else if (Path.endsBefore(op, p)) {\n p[op.length - 1] += 1\n } else if (Path.isAncestor(op, p) && path[op.length] >= position) {\n p[op.length - 1] += 1\n p[op.length] -= position\n }\n\n break\n }\n\n case 'move_node': {\n const { path: op, newPath: onp } = operation\n\n // If the old and new path are the same, it's a no-op.\n if (Path.equals(op, onp)) {\n return p\n }\n\n if (Path.isAncestor(op, p) || Path.equals(op, p)) {\n const copy = onp.slice()\n\n if (Path.endsBefore(op, onp) && op.length < onp.length) {\n copy[op.length - 1] -= 1\n }\n\n return copy.concat(p.slice(op.length))\n } else if (\n Path.isSibling(op, onp) &&\n (Path.isAncestor(onp, p) || Path.equals(onp, p))\n ) {\n if (Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n } else {\n p[op.length - 1] += 1\n }\n } else if (\n Path.endsBefore(onp, p) ||\n Path.equals(onp, p) ||\n Path.isAncestor(onp, p)\n ) {\n if (Path.endsBefore(op, p)) {\n p[op.length - 1] -= 1\n }\n\n p[onp.length - 1] += 1\n } else if (Path.endsBefore(op, p)) {\n if (Path.equals(onp, p)) {\n p[onp.length - 1] += 1\n }\n\n p[op.length - 1] -= 1\n }\n\n break\n }\n }\n\n return p\n },\n}\n","export default function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}","import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}","import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}","import {\n Ancestor,\n Descendant,\n Editor,\n Element,\n Node,\n NodeEntry,\n Operation,\n Path,\n Point,\n Range,\n Scrubber,\n Selection,\n Text,\n} from '../../index'\n\nexport interface GeneralTransforms {\n /**\n * Transform the editor by an operation.\n */\n transform: (editor: Editor, op: Operation) => void\n}\n\nconst insertChildren = <T>(xs: T[], index: number, ...newValues: T[]) => [\n ...xs.slice(0, index),\n ...newValues,\n ...xs.slice(index),\n]\n\nconst replaceChildren = <T>(\n xs: T[],\n index: number,\n removeCount: number,\n ...newValues: T[]\n) => [...xs.slice(0, index), ...newValues, ...xs.slice(index + removeCount)]\n\nconst removeChildren = replaceChildren\n\n/**\n * Replace a descendant with a new node, replacing all ancestors\n */\nconst modifyDescendant = <N extends Descendant>(\n editor: Editor,\n path: Path,\n f: (node: N) => N\n) => {\n if (path.length === 0) {\n throw new Error('Cannot modify the editor')\n }\n\n const node = Node.get(editor, path) as N\n const slicedPath = path.slice()\n let modifiedNode: Node = f(node)\n\n while (slicedPath.length > 1) {\n const index = slicedPath.pop()!\n const ancestorNode = Node.get(editor, slicedPath) as Ancestor\n\n modifiedNode = {\n ...ancestorNode,\n children: replaceChildren(ancestorNode.children, index, 1, modifiedNode),\n }\n }\n\n const index = slicedPath.pop()!\n editor.children = replaceChildren(editor.children, index, 1, modifiedNode)\n}\n\n/**\n * Replace the children of a node, replacing all ancestors\n */\nconst modifyChildren = (\n editor: Editor,\n path: Path,\n f: (children: Descendant[]) => Descendant[]\n) => {\n if (path.length === 0) {\n editor.children = f(editor.children)\n } else {\n modifyDescendant<Element>(editor, path, node => {\n if (Text.isText(node)) {\n throw new Error(\n `Cannot get the element at path [${path}] because it refers to a leaf node: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return { ...node, children: f(node.children) }\n })\n }\n}\n\n/**\n * Replace a leaf, replacing all ancestors\n */\nconst modifyLeaf = (editor: Editor, path: Path, f: (leaf: Text) => Text) =>\n modifyDescendant(editor, path, node => {\n if (!Text.isText(node)) {\n throw new Error(\n `Cannot get the leaf node at path [${path}] because it refers to a non-leaf node: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return f(node)\n })\n\n// eslint-disable-next-line no-redeclare\nexport const GeneralTransforms: GeneralTransforms = {\n transform(editor: Editor, op: Operation): void {\n let transformSelection = false\n\n switch (op.type) {\n case 'insert_node': {\n const { path, node } = op\n\n modifyChildren(editor, Path.parent(path), children => {\n const index = path[path.length - 1]\n\n if (index > children.length) {\n throw new Error(\n `Cannot apply an \"insert_node\" operation at path [${path}] because the destination is past the end of the node.`\n )\n }\n\n return insertChildren(children, index, node)\n })\n\n transformSelection = true\n break\n }\n\n case 'insert_text': {\n const { path, offset, text } = op\n if (text.length === 0) break\n\n modifyLeaf(editor, path, node => {\n const before = node.text.slice(0, offset)\n const after = node.text.slice(offset)\n\n return {\n ...node,\n text: before + text + after,\n }\n })\n\n transformSelection = true\n break\n }\n\n case 'merge_node': {\n const { path } = op\n const index = path[path.length - 1]\n const prevPath = Path.previous(path)\n const prevIndex = prevPath[prevPath.length - 1]\n\n modifyChildren(editor, Path.parent(path), children => {\n const node = children[index]\n const prev = children[prevIndex]\n let newNode: Descendant\n\n if (Text.isText(node) && Text.isText(prev)) {\n newNode = { ...prev, text: prev.text + node.text }\n } else if (!Text.isText(node) && !Text.isText(prev)) {\n newNode = { ...prev, children: prev.children.concat(node.children) }\n } else {\n throw new Error(\n `Cannot apply a \"merge_node\" operation at path [${path}] to nodes of different interfaces: ${Scrubber.stringify(\n node\n )} ${Scrubber.stringify(prev)}`\n )\n }\n\n return replaceChildren(children, prevIndex, 2, newNode)\n })\n\n transformSelection = true\n break\n }\n\n case 'move_node': {\n const { path, newPath } = op\n const index = path[path.length - 1]\n\n if (Path.isAncestor(path, newPath)) {\n throw new Error(\n `Cannot move a path [${path}] to new path [${newPath}] because the destination is inside itself.`\n )\n }\n\n const node = Node.get(editor, path)\n\n modifyChildren(editor, Path.parent(path), children =>\n removeChildren(children, index, 1)\n )\n\n // This is tricky, but since the `path` and `newPath` both refer to\n // the same snapshot in time, there's a mismatch. After either\n // removing the original position, the second step's path can be out\n // of date. So instead of using the `op.newPath` directly, we\n // transform `op.path` to ascertain what the `newPath` would be after\n // the operation was applied.\n const truePath = Path.transform(path, op)!\n const newIndex = truePath[truePath.length - 1]\n\n modifyChildren(editor, Path.parent(truePath), children =>\n insertChildren(children, newIndex, node)\n )\n\n transformSelection = true\n break\n }\n\n case 'remove_node': {\n const { path } = op\n const index = path[path.length - 1]\n\n modifyChildren(editor, Path.parent(path), children =>\n removeChildren(children, index, 1)\n )\n\n // Transform all the points in the value, but if the point was in the\n // node that was removed we need to update the range or remove it.\n if (editor.selection) {\n let selection: Selection = { ...editor.selection }\n\n for (const [point, key] of Range.points(selection)) {\n const result = Point.transform(point, op)\n\n if (selection != null && result != null) {\n selection[key] = result\n } else {\n let prev: NodeEntry<Text> | undefined\n let next: NodeEntry<Text> | undefined\n\n for (const [n, p] of Node.texts(editor)) {\n if (Path.compare(p, path) === -1) {\n prev = [n, p]\n } else {\n next = [n, p]\n break\n }\n }\n\n let preferNext = false\n if (prev && next) {\n if (Path.isSibling(prev[1], path)) {\n preferNext = false\n } else if (Path.equals(next[1], path)) {\n preferNext = true\n } else {\n preferNext =\n Path.common(prev[1], path).length <\n Path.common(next[1], path).length\n }\n }\n\n if (prev && !preferNext) {\n selection![key] = { path: prev[1], offset: prev[0].text.length }\n } else if (next) {\n selection![key] = { path: next[1], offset: 0 }\n } else {\n selection = null\n }\n }\n }\n\n if (!selection || !Range.equals(selection, editor.selection)) {\n editor.selection = selection\n }\n }\n\n break\n }\n\n case 'remove_text': {\n const { path, offset, text } = op\n if (text.length === 0) break\n\n modifyLeaf(editor, path, node => {\n const before = node.text.slice(0, offset)\n const after = node.text.slice(offset + text.length)\n\n return {\n ...node,\n text: before + after,\n }\n })\n\n transformSelection = true\n break\n }\n\n case 'set_node': {\n const { path, properties, newProperties } = op\n\n if (path.length === 0) {\n throw new Error(`Cannot set properties on the root node!`)\n }\n\n modifyDescendant(editor, path, node => {\n const newNode = { ...node }\n\n for (const key in newProperties) {\n if (key === 'children' || key === 'text') {\n throw new Error(`Cannot set the \"${key}\" property of nodes!`)\n }\n\n const value = newProperties[<keyof Node>key]\n\n if (value == null) {\n delete newNode[<keyof Node>key]\n } else {\n newNode[<keyof Node>key] = value\n }\n }\n\n // properties that were previously defined, but are now missing, must be deleted\n for (const key in properties) {\n if (!newProperties.hasOwnProperty(key)) {\n delete newNode[<keyof Node>key]\n }\n }\n\n return newNode\n })\n\n break\n }\n\n case 'set_selection': {\n const { newProperties } = op\n\n if (newProperties == null) {\n editor.selection = null\n break\n }\n\n if (editor.selection == null) {\n if (!Range.isRange(newProperties)) {\n throw new Error(\n `Cannot apply an incomplete \"set_selection\" operation properties ${Scrubber.stringify(\n newProperties\n )} when there is no current selection.`\n )\n }\n\n editor.selection = { ...newProperties }\n break\n }\n\n const selection = { ...editor.selection }\n\n for (const key in newProperties) {\n const value = newProperties[<keyof Range>key]\n\n if (value == null) {\n if (key === 'anchor' || key === 'focus') {\n throw new Error(`Cannot remove the \"${key}\" selection property`)\n }\n\n delete selection[<keyof Range>key]\n } else {\n selection[<keyof Range>key] = value\n }\n }\n\n editor.selection = selection\n\n break\n }\n\n case 'split_node': {\n const { path, position, properties } = op\n const index = path[path.length - 1]\n\n if (path.length === 0) {\n throw new Error(\n `Cannot apply a \"split_node\" operation at path [${path}] because the root node cannot be split.`\n )\n }\n\n modifyChildren(editor, Path.parent(path), children => {\n const node = children[index]\n let newNode: Descendant\n let nextNode: Descendant\n\n if (Text.isText(node)) {\n const before = node.text.slice(0, position)\n const after = node.text.slice(position)\n newNode = {\n ...node,\n text: before,\n }\n nextNode = {\n ...(properties as Partial<Text>),\n text: after,\n }\n } else {\n const before = node.children.slice(0, position)\n const after = node.children.slice(position)\n newNode = {\n ...node,\n children: before,\n }\n nextNode = {\n ...(properties as Partial<Element>),\n children: after,\n }\n }\n\n return replaceChildren(children, index, 1, newNode, nextNode)\n })\n\n transformSelection = true\n break\n }\n }\n\n if (transformSelection && editor.selection) {\n const selection = { ...editor.selection }\n\n for (const [point, key] of Range.points(selection)) {\n selection[key] = Point.transform(point, op)!\n }\n\n if (!Range.equals(selection, editor.selection)) {\n editor.selection = selection\n }\n }\n },\n}\n","import { Editor, Element, Location, Node, Path } from '../../index'\nimport { NodeMatch, PropsCompare, PropsMerge } from '../editor'\nimport { MaximizeMode, RangeMode } from '../../types/types'\n\nexport interface NodeInsertNodesOptions<T extends Node> {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n select?: boolean\n voids?: boolean\n batchDirty?: boolean\n}\n\nexport interface NodeTransforms {\n /**\n * Insert nodes in the editor\n * at the specified location or (if not defined) the current selection or (if not defined) the end of the document.\n */\n insertNodes: <T extends Node>(\n editor: Editor,\n nodes: Node | Node[],\n options?: NodeInsertNodesOptions<T>\n ) => void\n\n /**\n * Lift nodes at a specific location upwards in the document tree, splitting\n * their parent in two if necessary.\n */\n liftNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n voids?: boolean\n }\n ) => void\n\n /**\n * Merge a node at a location with the previous node of the same depth,\n * removing any empty containing nodes after the merge if necessary.\n */\n mergeNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n voids?: boolean\n }\n ) => void\n\n /**\n * Move the nodes at a location to a new location.\n */\n moveNodes: <T extends Node>(\n editor: Editor,\n options: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n to: Path\n voids?: boolean\n }\n ) => void\n\n /**\n * Remove the nodes at a specific location in the document.\n */\n removeNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n hanging?: boolean\n voids?: boolean\n }\n ) => void\n\n /**\n * Set new properties on the nodes at a location.\n */\n setNodes: <T extends Node>(\n editor: Editor,\n props: Partial<T>,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n hanging?: boolean\n split?: boolean\n voids?: boolean\n compare?: PropsCompare\n merge?: PropsMerge\n }\n ) => void\n\n /**\n * Split the nodes at a specific location.\n */\n splitNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: RangeMode\n always?: boolean\n height?: number\n voids?: boolean\n }\n ) => void\n\n /**\n * Unset properties on the nodes at a location.\n */\n unsetNodes: <T extends Node>(\n editor: Editor,\n props: string | string[],\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n hanging?: boolean\n split?: boolean\n voids?: boolean\n }\n ) => void\n\n /**\n * Unwrap the nodes at a location from a parent node, splitting the parent if\n * necessary to ensure that only the content in the range is unwrapped.\n */\n unwrapNodes: <T extends Node>(\n editor: Editor,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n }\n ) => void\n\n /**\n * Wrap the nodes at a location in a new container node, splitting the edges\n * of the range first to ensure that only the content in the range is wrapped.\n */\n wrapNodes: <T extends Node>(\n editor: Editor,\n element: Element,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n split?: boolean\n voids?: boolean\n }\n ) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const NodeTransforms: NodeTransforms = {\n insertNodes(editor, nodes, options) {\n editor.insertNodes(nodes, options)\n },\n liftNodes(editor, options) {\n editor.liftNodes(options)\n },\n mergeNodes(editor, options) {\n editor.mergeNodes(options)\n },\n moveNodes(editor, options) {\n editor.moveNodes(options)\n },\n removeNodes(editor, options) {\n editor.removeNodes(options)\n },\n setNodes(editor, props, options) {\n editor.setNodes(props, options)\n },\n splitNodes(editor, options) {\n editor.splitNodes(options)\n },\n unsetNodes(editor, props, options) {\n editor.unsetNodes(props, options)\n },\n unwrapNodes(editor, options) {\n editor.unwrapNodes(options)\n },\n wrapNodes(editor, element, options) {\n editor.wrapNodes(element, options)\n },\n}\n","import { Editor, Location, Point, Range } from '../../index'\nimport { MoveUnit, SelectionEdge } from '../../types/types'\n\nexport interface SelectionCollapseOptions {\n edge?: SelectionEdge\n}\n\nexport interface SelectionMoveOptions {\n distance?: number\n unit?: MoveUnit\n reverse?: boolean\n edge?: SelectionEdge\n}\n\nexport interface SelectionSetPointOptions {\n edge?: SelectionEdge\n}\n\nexport interface SelectionTransforms {\n /**\n * Collapse the selection.\n */\n collapse: (editor: Editor, options?: SelectionCollapseOptions) => void\n\n /**\n * Unset the selection.\n */\n deselect: (editor: Editor) => void\n\n /**\n * Move the selection's point forward or backward.\n */\n move: (editor: Editor, options?: SelectionMoveOptions) => void\n\n /**\n * Set the selection to a new value.\n */\n select: (editor: Editor, target: Location) => void\n\n /**\n * Set new properties on one of the selection's points.\n */\n setPoint: (\n editor: Editor,\n props: Partial<Point>,\n options?: SelectionSetPointOptions\n ) => void\n\n /**\n * Set new properties on the selection.\n */\n setSelection: (editor: Editor, props: Partial<Range>) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const SelectionTransforms: SelectionTransforms = {\n collapse(editor, options) {\n editor.collapse(options)\n },\n deselect(editor) {\n editor.deselect()\n },\n move(editor, options) {\n editor.move(options)\n },\n select(editor, target) {\n editor.select(target)\n },\n setPoint(editor, props, options) {\n editor.setPoint(props, options)\n },\n setSelection(editor, props) {\n editor.setSelection(props)\n },\n}\n","export const isObject = (value: any) =>\n typeof value === 'object' && value !== null\n","import { isObject } from './is-object'\n\n/*\n Custom deep equal comparison for Slate nodes.\n\n We don't need general purpose deep equality;\n Slate only supports plain values, Arrays, and nested objects.\n Complex values nested inside Arrays are not supported.\n\n Slate objects are designed to be serialised, so\n missing keys are deliberately normalised to undefined.\n */\nexport const isDeepEqual = (\n node: Record<string, any>,\n another: Record<string, any>\n): boolean => {\n for (const key in node) {\n const a = node[key]\n const b = another[key]\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false\n }\n } else if (isObject(a) && isObject(b)) {\n if (!isDeepEqual(a, b)) return false\n } else if (a !== b) {\n return false\n }\n }\n\n /*\n Deep object equality is only necessary in one direction; in the reverse direction\n we are only looking for keys that are missing.\n As above, undefined keys are normalised to missing.\n */\n\n for (const key in another) {\n if (node[key] === undefined && another[key] !== undefined) {\n return false\n }\n }\n\n return true\n}\n","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}","import { ExtendedType, Operation, Path, Point, PointEntry, isObject } from '..'\nimport { RangeDirection } from '../types/types'\n\n/**\n * `Range` objects are a set of points that refer to a specific span of a Slate\n * document. They can define a span inside a single node or a can span across\n * multiple nodes.\n */\n\nexport interface BaseRange {\n anchor: Point\n focus: Point\n}\n\nexport type Range = ExtendedType<'Range', BaseRange>\n\nexport interface RangeEdgesOptions {\n reverse?: boolean\n}\n\nexport interface RangeTransformOptions {\n affinity?: RangeDirection | null\n}\n\nexport interface RangeInterface {\n /**\n * Get the start and end points of a range, in the order in which they appear\n * in the document.\n */\n edges: (range: Range, options?: RangeEdgesOptions) => [Point, Point]\n\n /**\n * Get the end point of a range.\n */\n end: (range: Range) => Point\n\n /**\n * Check if a range is exactly equal to another.\n */\n equals: (range: Range, another: Range) => boolean\n\n /**\n * Check if a range includes a path, a point or part of another range.\n */\n includes: (range: Range, target: Path | Point | Range) => boolean\n\n /**\n * Check if a range includes another range.\n */\n surrounds: (range: Range, target: Range) => boolean\n\n /**\n * Get the intersection of a range with another.\n */\n intersection: (range: Range, another: Range) => Range | null\n\n /**\n * Check if a range is backward, meaning that its anchor point appears in the\n * document _after_ its focus point.\n */\n isBackward: (range: Range) => boolean\n\n /**\n * Check if a range is collapsed, meaning that both its anchor and focus\n * points refer to the exact same position in the document.\n */\n isCollapsed: (range: Range) => boolean\n\n /**\n * Check if a range is expanded.\n *\n * This is the opposite of [[Range.isCollapsed]] and is provided for legibility.\n */\n isExpanded: (range: Range) => boolean\n\n /**\n * Check if a range is forward.\n *\n * This is the opposite of [[Range.isBackward]] and is provided for legibility.\n */\n isForward: (range: Range) => boolean\n\n /**\n * Check if a value implements the [[Range]] interface.\n */\n isRange: (value: any) => value is Range\n\n /**\n * Iterate through all of the point entries in a range.\n */\n points: (range: Range) => Generator<PointEntry, void, undefined>\n\n /**\n * Get the start point of a range.\n */\n start: (range: Range) => Point\n\n /**\n * Transform a range by an operation.\n */\n transform: (\n range: Range,\n op: Operation,\n options?: RangeTransformOptions\n ) => Range | null\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Range: RangeInterface = {\n edges(range: Range, options: RangeEdgesOptions = {}): [Point, Point] {\n const { reverse = false } = options\n const { anchor, focus } = range\n return Range.isBackward(range) === reverse\n ? [anchor, focus]\n : [focus, anchor]\n },\n\n end(range: Range): Point {\n const [, end] = Range.edges(range)\n return end\n },\n\n equals(range: Range, another: Range): boolean {\n return (\n Point.equals(range.anchor, another.anchor) &&\n Point.equals(range.focus, another.focus)\n )\n },\n\n surrounds(range: Range, target: Range): boolean {\n const intersectionRange = Range.intersection(range, target)\n if (!intersectionRange) {\n return false\n }\n return Range.equals(intersectionRange, target)\n },\n\n includes(range: Range, target: Path | Point | Range): boolean {\n if (Range.isRange(target)) {\n if (\n Range.includes(range, target.anchor) ||\n Range.includes(range, target.focus)\n ) {\n return true\n }\n\n const [rs, re] = Range.edges(range)\n const [ts, te] = Range.edges(target)\n return Point.isBefore(rs, ts) && Point.isAfter(re, te)\n }\n\n const [start, end] = Range.edges(range)\n let isAfterStart = false\n let isBeforeEnd = false\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0\n isBeforeEnd = Point.compare(target, end) <= 0\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0\n isBeforeEnd = Path.compare(target, end.path) <= 0\n }\n\n return isAfterStart && isBeforeEnd\n },\n\n intersection(range: Range, another: Range): Range | null {\n const { anchor, focus, ...rest } = range\n const [s1, e1] = Range.edges(range)\n const [s2, e2] = Range.edges(another)\n const start = Point.isBefore(s1, s2) ? s2 : s1\n const end = Point.isBefore(e1, e2) ? e1 : e2\n\n if (Point.isBefore(end, start)) {\n return null\n } else {\n return { anchor: start, focus: end, ...rest }\n }\n },\n\n isBackward(range: Range): boolean {\n const { anchor, focus } = range\n return Point.isAfter(anchor, focus)\n },\n\n isCollapsed(range: Range): boolean {\n const { anchor, focus } = range\n return Point.equals(anchor, focus)\n },\n\n isExpanded(range: Range): boolean {\n return !Range.isCollapsed(range)\n },\n\n isForward(range: Range): boolean {\n return !Range.isBackward(range)\n },\n\n isRange(value: any): value is Range {\n return (\n isObject(value) &&\n Point.isPoint(value.anchor) &&\n Point.isPoint(value.focus)\n )\n },\n\n *points(range: Range): Generator<PointEntry, void, undefined> {\n yield [range.anchor, 'anchor']\n yield [range.focus, 'focus']\n },\n\n start(range: Range): Point {\n const [start] = Range.edges(range)\n return start\n },\n\n transform(\n range: Range | null,\n op: Operation,\n options: RangeTransformOptions = {}\n ): Range | null {\n if (range === null) {\n return null\n }\n\n const { affinity = 'inward' } = options\n let affinityAnchor: 'forward' | 'backward' | null\n let affinityFocus: 'forward' | 'backward' | null\n\n if (affinity === 'inward') {\n // If the range is collapsed, make sure to use the same affinity to\n // avoid the two points passing each other and expanding in the opposite\n // direction\n const isCollapsed = Range.isCollapsed(range)\n if (Range.isForward(range)) {\n affinityAnchor = 'forward'\n affinityFocus = isCollapsed ? affinityAnchor : 'backward'\n } else {\n affinityAnchor = 'backward'\n affinityFocus = isCollapsed ? affinityAnchor : 'forward'\n }\n } else if (affinity === 'outward') {\n if (Range.isForward(range)) {\n affinityAnchor = 'backward'\n affinityFocus = 'forward'\n } else {\n affinityAnchor = 'forward'\n affinityFocus = 'backward'\n }\n } else {\n affinityAnchor = affinity\n affinityFocus = affinity\n }\n const anchor = Point.transform(range.anchor, op, {\n affinity: affinityAnchor,\n })\n const focus = Point.transform(range.focus, op, { affinity: affinityFocus })\n\n if (!anchor || !focus) {\n return null\n }\n\n return { anchor, focus }\n },\n}\n","import {\n Ancestor,\n Descendant,\n Editor,\n ExtendedType,\n Node,\n Path,\n isObject,\n} from '..'\n\n/**\n * `Element` objects are a type of node in a Slate document that contain other\n * element nodes or text nodes. They can be either \"blocks\" or \"inlines\"\n * depending on the Slate editor's configuration.\n */\n\nexport interface BaseElement {\n children: Descendant[]\n}\n\nexport type Element = ExtendedType<'Element', BaseElement>\n\nexport interface ElementIsElementOptions {\n deep?: boolean\n}\n\nexport interface ElementInterface {\n /**\n * Check if a value implements the 'Ancestor' interface.\n */\n isAncestor: (\n value: any,\n options?: ElementIsElementOptions\n ) => value is Ancestor\n\n /**\n * Check if a value implements the `Element` interface.\n */\n isElement: (value: any, options?: ElementIsElementOptions) => value is Element\n\n /**\n * Check if a value is an array of `Element` objects.\n */\n isElementList: (\n value: any,\n options?: ElementIsElementOptions\n ) => value is Element[]\n\n /**\n * Check if a set of props is a partial of Element.\n */\n isElementProps: (props: any) => props is Partial<Element>\n\n /**\n * Check if a value implements the `Element` interface and has elementKey with selected value.\n * Default it check to `type` key value\n */\n isElementType: <T extends Element>(\n value: any,\n elementVal: string,\n elementKey?: string\n ) => value is T\n\n /**\n * Check if an element matches set of properties.\n *\n * Note: this checks custom properties, and it does not ensure that any\n * children are equivalent.\n */\n matches: (element: Element, props: Partial<Element>) => boolean\n}\n\n/**\n * Shared the function with isElementType utility\n */\nconst isElement = (\n value: any,\n { deep = false }: ElementIsElementOptions = {}\n): value is Element => {\n if (!isObject(value)) return false\n\n // PERF: No need to use the full Editor.isEditor here\n const isEditor = typeof value.apply === 'function'\n if (isEditor) return false\n\n const isChildrenValid = deep\n ? Node.isNodeList(value.children)\n : Array.isArray(value.children)\n\n return isChildrenValid\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Element: ElementInterface = {\n isAncestor(\n value: any,\n { deep = false }: ElementIsElementOptions = {}\n ): value is Ancestor {\n return isObject(value) && Node.isNodeList(value.children, { deep })\n },\n\n isElement,\n\n isElementList(\n value: any,\n { deep = false }: ElementIsElementOptions = {}\n ): value is Element[] {\n return (\n Array.isArray(value) &&\n value.every(val => Element.isElement(val, { deep }))\n )\n },\n\n isElementProps(props: any): props is Partial<Element> {\n return (props as Partial<Element>).children !== undefined\n },\n\n isElementType: <T extends Element>(\n value: any,\n elementVal: string,\n elementKey: string = 'type'\n ): value is T => {\n return (\n isElement(value) && value[<keyof Descendant>elementKey] === elementVal\n )\n },\n\n matches(element: Element, props: Partial<Element>): boolean {\n for (const key in props) {\n if (key === 'children') {\n continue\n }\n\n if (element[<keyof Descendant>key] !== props[<keyof Descendant>key]) {\n return false\n }\n }\n\n return true\n },\n}\n\n/**\n * `ElementEntry` objects refer to an `Element` and the `Path` where it can be\n * found inside a root node.\n */\nexport type ElementEntry = [Element, Path]\n","import { produce } from 'immer'\nimport { Editor, Path, Range, Scrubber, Text } from '..'\nimport { Element, ElementEntry } from './element'\n\n/**\n * The `Node` union type represents all of the different types of nodes that\n * occur in a Slate document tree.\n */\n\nexport type BaseNode = Editor | Element | Text\nexport type Node = Editor | Element | Text\n\nexport interface NodeAncestorsOptions {\n reverse?: boolean\n}\n\nexport interface NodeChildrenOptions {\n reverse?: boolean\n}\n\nexport interface NodeDescendantsOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (node: NodeEntry) => boolean\n}\n\nexport interface NodeElementsOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (node: NodeEntry) => boolean\n}\n\nexport interface NodeIsNodeOptions {\n deep?: boolean\n}\n\nexport interface NodeLevelsOptions {\n reverse?: boolean\n}\n\nexport interface NodeNodesOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (entry: NodeEntry) => boolean\n}\n\nexport interface NodeTextsOptions {\n from?: Path\n to?: Path\n reverse?: boolean\n pass?: (node: NodeEntry) => boolean\n}\n\nexport interface NodeInterface {\n /**\n * Get the node at a specific path, asserting that it's an ancestor node.\n */\n ancestor: (root: Node, path: Path) => Ancestor\n\n /**\n * Return a generator of all the ancestor nodes above a specific path.\n *\n * By default the order is top-down, from highest to lowest ancestor in\n * the tree, but you can pass the `reverse: true` option to go bottom-up.\n */\n ancestors: (\n root: Node,\n path: Path,\n options?: NodeAncestorsOptions\n ) => Generator<NodeEntry<Ancestor>, void, undefined>\n\n /**\n * Get the child of a node at a specific index.\n */\n child: (root: Node, index: number) => Descendant\n\n /**\n * Iterate over the children of a node at a specific path.\n */\n children: (\n root: Node,\n path: Path,\n options?: NodeChildrenOptions\n ) => Generator<NodeEntry<Descendant>, void, undefined>\n\n /**\n * Get an entry for the common ancesetor node of two paths.\n */\n common: (root: Node, path: Path, another: Path) => NodeEntry\n\n /**\n * Get the node at a specific path, asserting that it's a descendant node.\n */\n descendant: (root: Node, path: Path) => Descendant\n\n /**\n * Return a generator of all the descendant node entries inside a root node.\n */\n descendants: (\n root: Node,\n options?: NodeDescendantsOptions\n ) => Generator<NodeEntry<Descendant>, void, undefined>\n\n /**\n * Return a generator of all the element nodes inside a root node. Each iteration\n * will return an `ElementEntry` tuple consisting of `[Element, Path]`. If the\n * root node is an element it will be included in the iteration as well.\n */\n elements: (\n root: Node,\n options?: NodeElementsOptions\n ) => Generator<ElementEntry, void, undefined>\n\n /**\n * Extract props from a Node.\n */\n extractProps: (node: Node) => NodeProps\n\n /**\n * Get the first leaf node entry in a root node from a path.\n */\n first: (root: Node, path: Path) => NodeEntry\n\n /**\n * Get the sliced fragment represented by a range inside a root node.\n */\n fragment: <T extends Ancestor = Editor>(\n root: T,\n range: Range\n ) => T['children']\n\n /**\n * Get the descendant node referred to by a specific path. If the path is an\n * empty array, it refers to the root node itself.\n */\n get: (root: Node, path: Path) => Node\n\n /**\n * Similar to get, but returns undefined if the node does not exist.\n */\n getIf: (root: Node, path: Path) => Node | undefined\n\n /**\n * Check if a descendant node exists at a specific path.\n */\n has: (root: Node, path: Path) => boolean\n\n /**\n * Check if a value implements the `Node` interface.\n */\n isNode: (value: any, options?: NodeIsNodeOptions) => value is Node\n\n /**\n * Check if a value is a list of `Node` objects.\n */\n isNodeList: (value: any, options?: NodeIsNodeOptions) => value is Node[]\n\n /**\n * Get the last leaf node entry in a root node from a path.\n */\n last: (root: Node, path: Path) => NodeEntry\n\n /**\n * Get the node at a specific path, ensuring it's a leaf text node.\n */\n leaf: (root: Node, path: Path) => Text\n\n /**\n * Return a generator of the in a branch of the tree, from a specific path.\n *\n * By default the order is top-down, from highest to lowest node in the tree,\n * but you can pass the `reverse: true` option to go bottom-up.\n */\n levels: (\n root: Node,\n path: Path,\n options?: NodeLevelsOptions\n ) => Generator<NodeEntry, void, undefined>\n\n /**\n * Check if a node matches a set of props.\n */\n matches: (node: Node, props: Partial<Node>) => boolean\n\n /**\n * Return a generator of all the node entries of a root node. Each entry is\n * returned as a `[Node, Path]` tuple, with the path referring to the node's\n * position inside the root node.\n */\n nodes: (\n root: Node,\n options?: NodeNodesOptions\n ) => Generator<NodeEntry, void, undefined>\n\n /**\n * Get the parent of a node at a specific path.\n */\n parent: (root: Node, path: Path) => Ancestor\n\n /**\n * Get the concatenated text string of a node's content.\n *\n * Note that this will not include spaces or line breaks between block nodes.\n * It is not a user-facing string, but a string for performing offset-related\n * computations for a node.\n */\n string: (node: Node) => string\n\n /**\n * Return a generator of all leaf text nodes in a root node.\n */\n texts: (\n root: Node,\n options?: NodeTextsOptions\n ) => Generator<NodeEntry<Text>, void, undefined>\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Node: NodeInterface = {\n ancestor(root: Node, path: Path): Ancestor {\n const node = Node.get(root, path)\n\n if (Text.isText(node)) {\n throw new Error(\n `Cannot get the ancestor node at path [${path}] because it refers to a text node instead: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return node\n },\n\n *ancestors(\n root: Node,\n path: Path,\n options: NodeAncestorsOptions = {}\n ): Generator<NodeEntry<Ancestor>, void, undefined> {\n for (const p of Path.ancestors(path, options)) {\n const n = Node.ancestor(root, p)\n const entry: NodeEntry<Ancestor> = [n, p]\n yield entry\n }\n },\n\n child(root: Node, index: number): Descendant {\n if (Text.isText(root)) {\n throw new Error(\n `Cannot get the child of a text node: ${Scrubber.stringify(root)}`\n )\n }\n\n const c = root.children[index] as Descendant\n\n if (c == null) {\n throw new Error(\n `Cannot get child at index \\`${index}\\` in node: ${Scrubber.stringify(\n root\n )}`\n )\n }\n\n return c\n },\n\n *children(\n root: Node,\n path: Path,\n options: NodeChildrenOptions = {}\n ): Generator<NodeEntry<Descendant>, void, undefined> {\n const { reverse = false } = options\n const ancestor = Node.ancestor(root, path)\n const { children } = ancestor\n let index = reverse ? children.length - 1 : 0\n\n while (reverse ? index >= 0 : index < children.length) {\n const child = Node.child(ancestor, index)\n const childPath = path.concat(index)\n yield [child, childPath]\n index = reverse ? index - 1 : index + 1\n }\n },\n\n common(root: Node, path: Path, another: Path): NodeEntry {\n const p = Path.common(path, another)\n const n = Node.get(root, p)\n return [n, p]\n },\n\n descendant(root: Node, path: Path): Descendant {\n const node = Node.get(root, path)\n\n if (Editor.isEditor(node)) {\n throw new Error(\n `Cannot get the descendant node at path [${path}] because it refers to the root editor node instead: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return node\n },\n\n *descendants(\n root: Node,\n options: NodeDescendantsOptions = {}\n ): Generator<NodeEntry<Descendant>, void, undefined> {\n for (const [node, path] of Node.nodes(root, options)) {\n if (path.length !== 0) {\n // NOTE: we have to coerce here because checking the path's length does\n // guarantee that `node` is not a `Editor`, but TypeScript doesn't know.\n yield [node, path] as NodeEntry<Descendant>\n }\n }\n },\n\n *elements(\n root: Node,\n options: NodeElementsOptions = {}\n ): Generator<ElementEntry, void, undefined> {\n for (const [node, path] of Node.nodes(root, options)) {\n if (Element.isElement(node)) {\n yield [node, path]\n }\n }\n },\n\n extractProps(node: Node): NodeProps {\n if (Element.isAncestor(node)) {\n const { children, ...properties } = node\n\n return properties\n } else {\n const { text, ...properties } = node\n\n return properties\n }\n },\n\n first(root: Node, path: Path): NodeEntry {\n const p = path.slice()\n let n = Node.get(root, p)\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break\n } else {\n n = n.children[0]\n p.push(0)\n }\n }\n\n return [n, p]\n },\n\n fragment<T extends Ancestor = Editor>(root: T, range: Range): T['children'] {\n const newRoot = produce({ children: root.children }, r => {\n const [start, end] = Range.edges(range)\n const nodeEntries = Node.nodes(r, {\n reverse: true,\n pass: ([, path]) => !Range.includes(range, path),\n })\n\n for (const [, path] of nodeEntries) {\n if (!Range.includes(range, path)) {\n const parent = Node.parent(r, path)\n const index = path[path.length - 1]\n parent.children.splice(index, 1)\n }\n\n if (Path.equals(path, end.path)) {\n const leaf = Node.leaf(r, path)\n leaf.text = leaf.text.slice(0, end.offset)\n }\n\n if (Path.equals(path, start.path)) {\n const leaf = Node.leaf(r, path)\n leaf.text = leaf.text.slice(start.offset)\n }\n }\n\n if (Editor.isEditor(r)) {\n r.selection = null\n }\n })\n\n return newRoot.children\n },\n\n get(root: Node, path: Path): Node {\n const node = Node.getIf(root, path)\n if (node === undefined) {\n throw new Error(\n `Cannot find a descendant at path [${path}] in node: ${Scrubber.stringify(\n root\n )}`\n )\n }\n return node\n },\n\n getIf(root: Node, path: Path): Node | undefined {\n let node = root\n\n for (let i = 0; i < path.length; i++) {\n const p = path[i]\n\n if (Text.isText(node) || !node.children[p]) {\n return\n }\n\n node = node.children[p]\n }\n\n return node\n },\n\n has(root: Node, path: Path): boolean {\n let node = root\n\n for (let i = 0; i < path.length; i++) {\n const p = path[i]\n\n if (Text.isText(node) || !node.children[p]) {\n return false\n }\n\n node = node.children[p]\n }\n\n return true\n },\n\n isNode(value: any, { deep = false }: NodeIsNodeOptions = {}): value is Node {\n return (\n Text.isText(value) ||\n Element.isElement(value, { deep }) ||\n Editor.isEditor(value, { deep })\n )\n },\n\n isNodeList(\n value: any,\n { deep = false }: NodeIsNodeOptions = {}\n ): value is Node[] {\n return (\n Array.isArray(value) && value.every(val => Node.isNode(val, { deep }))\n )\n },\n\n last(root: Node, path: Path): NodeEntry {\n const p = path.slice()\n let n = Node.get(root, p)\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break\n } else {\n const i = n.children.length - 1\n n = n.children[i]\n p.push(i)\n }\n }\n\n return [n, p]\n },\n\n leaf(root: Node, path: Path): Text {\n const node = Node.get(root, path)\n\n if (!Text.isText(node)) {\n throw new Error(\n `Cannot get the leaf node at path [${path}] because it refers to a non-leaf node: ${Scrubber.stringify(\n node\n )}`\n )\n }\n\n return node\n },\n\n *levels(\n root: Node,\n path: Path,\n options: NodeLevelsOptions = {}\n ): Generator<NodeEntry, void, undefined> {\n for (const p of Path.levels(path, options)) {\n const n = Node.get(root, p)\n yield [n, p]\n }\n },\n\n matches(node: Node, props: Partial<Node>): boolean {\n return (\n (Element.isElement(node) &&\n Element.isElementProps(props) &&\n Element.matches(node, props)) ||\n (Text.isText(node) &&\n Text.isTextProps(props) &&\n Text.matches(node, props))\n )\n },\n\n *nodes(\n root: Node,\n options: NodeNodesOptions = {}\n ): Generator<NodeEntry, void, undefined> {\n const { pass, reverse = false } = options\n const { from = [], to } = options\n const visited = new Set()\n let p: Path = []\n let n = root\n\n while (true) {\n if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {\n break\n }\n\n if (!visited.has(n)) {\n yield [n, p]\n }\n\n // If we're allowed to go downward and we haven't descended yet, do.\n if (\n !visited.has(n) &&\n !Text.isText(n) &&\n n.children.length !== 0 &&\n (pass == null || pass([n, p]) === false)\n ) {\n visited.add(n)\n let nextIndex = reverse ? n.children.length - 1 : 0\n\n if (Path.isAncestor(p, from)) {\n nextIndex = from[p.length]\n }\n\n p = p.concat(nextIndex)\n n = Node.get(root, p)\n continue\n }\n\n // If we're at the root and we can't go down, we're done.\n if (p.length === 0) {\n break\n }\n\n // If we're going forward...\n if (!reverse) {\n const newPath = Path.next(p)\n\n if (Node.has(root, newPath)) {\n p = newPath\n n = Node.get(root, p)\n continue\n }\n }\n\n // If we're going backward...\n if (reverse && p[p.length - 1] !== 0) {\n const newPath = Path.previous(p)\n p = newPath\n n = Node.get(root, p)\n continue\n }\n\n // Otherwise we're going upward...\n p = Path.parent(p)\n n = Node.get(root, p)\n visited.add(n)\n }\n },\n\n parent(root: Node, path: Path): Ancestor {\n const parentPath = Path.parent(path)\n const p = Node.get(root, parentPath)\n\n if (Text.isText(p)) {\n throw new Error(\n `Cannot get the parent of path [${path}] because it does not exist in the root.`\n )\n }\n\n return p\n },\n\n string(node: Node): string {\n if (Text.isText(node)) {\n return node.text\n } else {\n return node.children.map(Node.string).join('')\n }\n },\n\n *texts(\n root: Node,\n options: NodeTextsOptions = {}\n ): Generator<NodeEntry<Text>, void, undefined> {\n for (const [node, path] of Node.nodes(root, options)) {\n if (Text.isText(node)) {\n yield [node, path]\n }\n }\n },\n}\n\n/**\n * The `Descendant` union type represents nodes that are descendants in the\n * tree. It is returned as a convenience in certain cases to narrow a value\n * further than the more generic `Node` union.\n */\n\nexport type Descendant = Element | Text\n\n/**\n * The `Ancestor` union type represents nodes that are ancestors in the tree.\n * It is returned as a convenience in certain cases to narrow a value further\n * than the more generic `Node` union.\n */\n\nexport type Ancestor = Editor | Element\n\n/**\n * `NodeEntry` objects are returned when iterating over the nodes in a Slate\n * document tree. They consist of the node and its `Path` relative to the root\n * node in the document.\n */\n\nexport type NodeEntry<T extends Node = Node> = [T, Path]\n\n/**\n * Convenience type for returning the props of a node.\n */\nexport type NodeProps =\n | Omit<Editor, 'children'>\n | Omit<Element, 'children'>\n | Omit<Text, 'text'>\n","import { ExtendedType, Node, Path, Range, isObject } from '..'\n\nexport type BaseInsertNodeOperation = {\n type: 'insert_node'\n path: Path\n node: Node\n}\n\nexport type InsertNodeOperation = ExtendedType<\n 'InsertNodeOperation',\n BaseInsertNodeOperation\n>\n\nexport type BaseInsertTextOperation = {\n type: 'insert_text'\n path: Path\n offset: number\n text: string\n}\n\nexport type InsertTextOperation = ExtendedType<\n 'InsertTextOperation',\n BaseInsertTextOperation\n>\n\nexport type BaseMergeNodeOperation = {\n type: 'merge_node'\n path: Path\n position: number\n properties: Partial<Node>\n}\n\nexport type MergeNodeOperation = ExtendedType<\n 'MergeNodeOperation',\n BaseMergeNodeOperation\n>\n\nexport type BaseMoveNodeOperation = {\n type: 'move_node'\n path: Path\n newPath: Path\n}\n\nexport type MoveNodeOperation = ExtendedType<\n 'MoveNodeOperation',\n BaseMoveNodeOperation\n>\n\nexport type BaseRemoveNodeOperation = {\n type: 'remove_node'\n path: Path\n node: Node\n}\n\nexport type RemoveNodeOperation = ExtendedType<\n 'RemoveNodeOperation',\n BaseRemoveNodeOperation\n>\n\nexport type BaseRemoveTextOperation = {\n type: 'remove_text'\n path: Path\n offset: number\n text: string\n}\n\nexport type RemoveTextOperation = ExtendedType<\n 'RemoveTextOperation',\n BaseRemoveTextOperation\n>\n\nexport type BaseSetNodeOperation = {\n type: 'set_node'\n path: Path\n properties: Partial<Node>\n newProperties: Partial<Node>\n}\n\nexport type SetNodeOperation = ExtendedType<\n 'SetNodeOperation',\n BaseSetNodeOperation\n>\n\nexport type BaseSetSelectionOperation =\n | {\n type: 'set_selection'\n properties: null\n newProperties: Range\n }\n | {\n type: 'set_selection'\n properties: Partial<Range>\n newProperties: Partial<Range>\n }\n | {\n type: 'set_selection'\n properties: Range\n newProperties: null\n }\n\nexport type SetSelectionOperation = ExtendedType<\n 'SetSelectionOperation',\n BaseSetSelectionOperation\n>\n\nexport type BaseSplitNodeOperation = {\n type: 'split_node'\n path: Path\n position: number\n properties: Partial<Node>\n}\n\nexport type SplitNodeOperation = ExtendedType<\n 'SplitNodeOperation',\n BaseSplitNodeOperation\n>\n\nexport type NodeOperation =\n | InsertNodeOperation\n | MergeNodeOperation\n | MoveNodeOperation\n | RemoveNodeOperation\n | SetNodeOperation\n | SplitNodeOperation\n\nexport type SelectionOperation = SetSelectionOperation\n\nexport type TextOperation = InsertTextOperation | RemoveTextOperation\n\n/**\n * `Operation` objects define the low-level instructions that Slate editors use\n * to apply changes to their internal state. Representing all changes as\n * operations is what allows Slate editors to easily implement history,\n * collaboration, and other features.\n */\n\nexport type BaseOperation = NodeOperation | SelectionOperation | TextOperation\nexport type Operation = ExtendedType<'Operation', BaseOperation>\n\nexport interface OperationInterface {\n /**\n * Check if a value is a `NodeOperation` object.\n */\n isNodeOperation: (value: any) => value is NodeOperation\n\n /**\n * Check if a value is an `Operation` object.\n */\n isOperation: (value: any) => value is Operation\n\n /**\n * Check if a value is a list of `Operation` objects.\n */\n isOperationList: (value: any) => value is Operation[]\n\n /**\n * Check if a value is a `SelectionOperation` object.\n */\n isSelectionOperation: (value: any) => value is SelectionOperation\n\n /**\n * Check if a value is a `TextOperation` object.\n */\n isTextOperation: (value: any) => value is TextOperation\n\n /**\n * Invert an operation, returning a new operation that will exactly undo the\n * original when applied.\n */\n inverse: (op: Operation) => Operation\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Operation: OperationInterface = {\n isNodeOperation(value: any): value is NodeOperation {\n return Operation.isOperation(value) && value.type.endsWith('_node')\n },\n\n isOperation(value: any): value is Operation {\n if (!isObject(value)) {\n return false\n }\n\n switch (value.type) {\n case 'insert_node':\n return Path.isPath(value.path) && Node.isNode(value.node)\n case 'insert_text':\n return (\n typeof value.offset === 'number' &&\n typeof value.text === 'string' &&\n Path.isPath(value.path)\n )\n case 'merge_node':\n return (\n typeof value.position === 'number' &&\n Path.isPath(value.path) &&\n isObject(value.properties)\n )\n case 'move_node':\n return Path.isPath(value.path) && Path.isPath(value.newPath)\n case 'remove_node':\n return Path.isPath(value.path) && Node.isNode(value.node)\n case 'remove_text':\n return (\n typeof value.offset === 'number' &&\n typeof value.text === 'string' &&\n Path.isPath(value.path)\n )\n case 'set_node':\n return (\n Path.isPath(value.path) &&\n isObject(value.properties) &&\n isObject(value.newProperties)\n )\n case 'set_selection':\n return (\n (value.properties === null && Range.isRange(value.newProperties)) ||\n (value.newProperties === null && Range.isRange(value.properties)) ||\n (isObject(value.properties) && isObject(value.newProperties))\n )\n case 'split_node':\n return (\n Path.isPath(value.path) &&\n typeof value.position === 'number' &&\n isObject(value.properties)\n )\n default:\n return false\n }\n },\n\n isOperationList(value: any): value is Operation[] {\n return (\n Array.isArray(value) && value.every(val => Operation.isOperation(val))\n )\n },\n\n isSelectionOperation(value: any): value is SelectionOperation {\n return Operation.isOperation(value) && value.type.endsWith('_selection')\n },\n\n isTextOperation(value: any): value is TextOperation {\n return Operation.isOperation(value) && value.type.endsWith('_text')\n },\n\n inverse(op: Operation): Operation {\n switch (op.type) {\n case 'insert_node': {\n return { ...op, type: 'remove_node' }\n }\n\n case 'insert_text': {\n return { ...op, type: 'remove_text' }\n }\n\n case 'merge_node': {\n return { ...op, type: 'split_node', path: Path.previous(op.path) }\n }\n\n case 'move_node': {\n const { newPath, path } = op\n\n // PERF: in this case the move operation is a no-op anyways.\n if (Path.equals(newPath, path)) {\n return op\n }\n\n // If the move happens completely within a single parent the path and\n // newPath are stable with respect to each other.\n if (Path.isSibling(path, newPath)) {\n return { ...op, path: newPath, newPath: path }\n }\n\n // If the move does not happen within a single parent it is possible\n // for the move to impact the true path to the location where the node\n // was removed from and where it was inserted. We have to adjust for this\n // and find the original path. We can accomplish this (only in non-sibling)\n // moves by looking at the impact of the move operation on the node\n // after the original move path.\n const inversePath = Path.transform(path, op)!\n const inverseNewPath = Path.transform(Path.next(path), op)!\n return { ...op, path: inversePath, newPath: inverseNewPath }\n }\n\n case 'remove_node': {\n return { ...op, type: 'insert_node' }\n }\n\n case 'remove_text': {\n return { ...op, type: 'insert_text' }\n }\n\n case 'set_node': {\n const { properties, newProperties } = op\n return { ...op, properties: newProperties, newProperties: properties }\n }\n\n case 'set_selection': {\n const { properties, newProperties } = op\n\n if (properties == null) {\n return {\n ...op,\n properties: newProperties as Range,\n newProperties: null,\n }\n } else if (newProperties == null) {\n return {\n ...op,\n properties: null,\n newProperties: properties as Range,\n }\n } else {\n return { ...op, properties: newProperties, newProperties: properties }\n }\n }\n\n case 'split_node': {\n return { ...op, type: 'merge_node', path: Path.next(op.path) }\n }\n }\n },\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Range } from '../interfaces/range'\nimport { Node } from '../interfaces/node'\nimport { Operation } from '../interfaces/operation'\nimport { isObject } from '../utils'\n\nexport const isEditor: EditorInterface['isEditor'] = (\n value: any,\n { deep = false } = {}\n): value is Editor => {\n if (!isObject(value)) {\n return false\n }\n\n const isEditor =\n typeof value.addMark === 'function' &&\n typeof value.apply === 'function' &&\n typeof value.deleteFragment === 'function' &&\n typeof value.insertBreak === 'function' &&\n typeof value.insertSoftBreak === 'function' &&\n typeof value.insertFragment === 'function' &&\n typeof value.insertNode === 'function' &&\n typeof value.insertText === 'function' &&\n typeof value.isElementReadOnly === 'function' &&\n typeof value.isInline === 'function' &&\n typeof value.isSelectable === 'function' &&\n typeof value.isVoid === 'function' &&\n typeof value.normalizeNode === 'function' &&\n typeof value.onChange === 'function' &&\n typeof value.removeMark === 'function' &&\n typeof value.getDirtyPaths === 'function' &&\n (value.marks === null || isObject(value.marks)) &&\n (value.selection === null || Range.isRange(value.selection)) &&\n (!deep || Node.isNodeList(value.children)) &&\n Operation.isOperationList(value.operations)\n\n return isEditor\n}\n","import {\n Ancestor,\n Descendant,\n Element,\n ExtendedType,\n Location,\n Node,\n NodeEntry,\n Operation,\n Path,\n PathRef,\n Point,\n PointRef,\n Range,\n RangeRef,\n Span,\n Text,\n Transforms,\n} from '..'\nimport {\n LeafEdge,\n MaximizeMode,\n RangeDirection,\n SelectionMode,\n TextDirection,\n TextUnit,\n TextUnitAdjustment,\n} from '../types/types'\nimport { OmitFirstArg } from '../utils/types'\nimport { isEditor } from '../editor/is-editor'\nimport {\n TextInsertFragmentOptions,\n TextInsertTextOptions,\n} from './transforms/text'\nimport { NodeInsertNodesOptions } from './transforms/node'\n\n/**\n * The `Editor` interface stores all the state of a Slate editor. It is extended\n * by plugins that wish to add their own helpers and implement new behaviors.\n */\nexport interface BaseEditor {\n // Core state.\n\n children: Descendant[]\n selection: Selection\n operations: Operation[]\n marks: EditorMarks | null\n\n // Overrideable core methods.\n\n apply: (operation: Operation) => void\n getDirtyPaths: (operation: Operation) => Path[]\n getFragment: () => Descendant[]\n isElementReadOnly: (element: Element) => boolean\n isSelectable: (element: Element) => boolean\n markableVoid: (element: Element) => boolean\n normalizeNode: (\n entry: NodeEntry,\n options?: {\n operation?: Operation\n fallbackElement?: () => Element\n }\n ) => void\n onChange: (options?: { operation?: Operation }) => void\n shouldNormalize: ({\n iteration,\n dirtyPaths,\n operation,\n }: {\n iteration: number\n initialDirtyPathsLength: number\n dirtyPaths: Path[]\n operation?: Operation\n }) => boolean\n\n // Overrideable core transforms.\n\n addMark: OmitFirstArg<typeof Editor.addMark>\n collapse: OmitFirstArg<typeof Transforms.collapse>\n delete: OmitFirstArg<typeof Transforms.delete>\n deleteBackward: (unit: TextUnit) => void\n deleteForward: (unit: TextUnit) => void\n deleteFragment: OmitFirstArg<typeof Editor.deleteFragment>\n deselect: OmitFirstArg<typeof Transforms.deselect>\n insertBreak: OmitFirstArg<typeof Editor.insertBreak>\n insertFragment: OmitFirstArg<typeof Transforms.insertFragment>\n insertNode: OmitFirstArg<typeof Editor.insertNode>\n insertNodes: OmitFirstArg<typeof Transforms.insertNodes>\n insertSoftBreak: OmitFirstArg<typeof Editor.insertSoftBreak>\n insertText: OmitFirstArg<typeof Transforms.insertText>\n liftNodes: OmitFirstArg<typeof Transforms.liftNodes>\n mergeNodes: OmitFirstArg<typeof Transforms.mergeNodes>\n move: OmitFirstArg<typeof Transforms.move>\n moveNodes: OmitFirstArg<typeof Transforms.moveNodes>\n normalize: OmitFirstArg<typeof Editor.normalize>\n removeMark: OmitFirstArg<typeof Editor.removeMark>\n removeNodes: OmitFirstArg<typeof Transforms.removeNodes>\n select: OmitFirstArg<typeof Transforms.select>\n setNodes: <T extends Node>(\n props: Partial<T>,\n options?: {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n hanging?: boolean\n split?: boolean\n voids?: boolean\n compare?: PropsCompare\n merge?: PropsMerge\n }\n ) => void\n setNormalizing: OmitFirstArg<typeof Editor.setNormalizing>\n setPoint: OmitFirstArg<typeof Transforms.setPoint>\n setSelection: OmitFirstArg<typeof Transforms.setSelection>\n splitNodes: OmitFirstArg<typeof Transforms.splitNodes>\n unsetNodes: OmitFirstArg<typeof Transforms.unsetNodes>\n unwrapNodes: OmitFirstArg<typeof Transforms.unwrapNodes>\n withoutNormalizing: OmitFirstArg<typeof Editor.withoutNormalizing>\n wrapNodes: OmitFirstArg<typeof Transforms.wrapNodes>\n\n // Overrideable core queries.\n\n above: <T extends Ancestor>(\n options?: EditorAboveOptions<T>\n ) => NodeEntry<T> | undefined\n after: OmitFirstArg<typeof Editor.after>\n before: OmitFirstArg<typeof Editor.before>\n edges: OmitFirstArg<typeof Editor.edges>\n elementReadOnly: OmitFirstArg<typeof Editor.elementReadOnly>\n end: OmitFirstArg<typeof Editor.end>\n first: OmitFirstArg<typeof Editor.first>\n fragment: OmitFirstArg<typeof Editor.fragment>\n getMarks: OmitFirstArg<typeof Editor.marks>\n hasBlocks: OmitFirstArg<typeof Editor.hasBlocks>\n hasInlines: OmitFirstArg<typeof Editor.hasInlines>\n hasPath: OmitFirstArg<typeof Editor.hasPath>\n hasTexts: OmitFirstArg<typeof Editor.hasTexts>\n isBlock: OmitFirstArg<typeof Editor.isBlock>\n isEdge: OmitFirstArg<typeof Editor.isEdge>\n isEmpty: OmitFirstArg<typeof Editor.isEmpty>\n isEnd: OmitFirstArg<typeof Editor.isEnd>\n isInline: OmitFirstArg<typeof Editor.isInline>\n isNormalizing: OmitFirstArg<typeof Editor.isNormalizing>\n isStart: OmitFirstArg<typeof Editor.isStart>\n isVoid: OmitFirstArg<typeof Editor.isVoid>\n last: OmitFirstArg<typeof Editor.last>\n leaf: OmitFirstArg<typeof Editor.leaf>\n levels: <T extends Node>(\n options?: EditorLevelsOptions<T>\n ) => Generator<NodeEntry<T>, void, undefined>\n next: <T extends Descendant>(\n options?: EditorNextOptions<T>\n ) => NodeEntry<T> | undefined\n node: OmitFirstArg<typeof Editor.node>\n nodes: <T extends Node>(\n options?: EditorNodesOptions<T>\n ) => Generator<NodeEntry<T>, void, undefined>\n parent: OmitFirstArg<typeof Editor.parent>\n path: OmitFirstArg<typeof Editor.path>\n pathRef: OmitFirstArg<typeof Editor.pathRef>\n pathRefs: OmitFirstArg<typeof Editor.pathRefs>\n point: OmitFirstArg<typeof Editor.point>\n pointRef: OmitFirstArg<typeof Editor.pointRef>\n pointRefs: OmitFirstArg<typeof Editor.pointRefs>\n positions: OmitFirstArg<typeof Editor.positions>\n previous: <T extends Node>(\n options?: EditorPreviousOptions<T>\n ) => NodeEntry<T> | undefined\n range: OmitFirstArg<typeof Editor.range>\n rangeRef: OmitFirstArg<typeof Editor.rangeRef>\n rangeRefs: OmitFirstArg<typeof Editor.rangeRefs>\n start: OmitFirstArg<typeof Editor.start>\n string: OmitFirstArg<typeof Editor.string>\n unhangRange: OmitFirstArg<typeof Editor.unhangRange>\n void: OmitFirstArg<typeof Editor.void>\n shouldMergeNodesRemovePrevNode: OmitFirstArg<\n typeof Editor.shouldMergeNodesRemovePrevNode\n >\n}\n\nexport type Editor = ExtendedType<'Editor', BaseEditor>\n\nexport type BaseSelection = Range | null\n\nexport type Selection = ExtendedType<'Selection', BaseSelection>\n\nexport type EditorMarks = Omit<Text, 'text'>\n\nexport interface EditorAboveOptions<T extends Ancestor> {\n at?: Location\n match?: NodeMatch<T>\n mode?: MaximizeMode\n voids?: boolean\n}\n\nexport interface EditorAfterOptions {\n distance?: number\n unit?: TextUnitAdjustment\n voids?: boolean\n}\n\nexport interface EditorBeforeOptions {\n distance?: number\n unit?: TextUnitAdjustment\n voids?: boolean\n}\n\nexport interface EditorDirectedDeletionOptions {\n unit?: TextUnit\n}\n\nexport interface EditorElementReadOnlyOptions {\n at?: Location\n mode?: MaximizeMode\n voids?: boolean\n}\n\nexport interface EditorFragmentDeletionOptions {\n direction?: TextDirection\n}\n\nexport interface EditorIsEditorOptions {\n deep?: boolean\n}\n\nexport interface EditorLeafOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorLevelsOptions<T extends Node> {\n at?: Location\n match?: NodeMatch<T>\n reverse?: boolean\n voids?: boolean\n}\n\nexport interface EditorNextOptions<T extends Descendant> {\n at?: Location\n match?: NodeMatch<T>\n mode?: SelectionMode\n voids?: boolean\n}\n\nexport interface EditorNodeOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorNodesOptions<T extends Node> {\n at?: Location | Span\n match?: NodeMatch<T>\n mode?: SelectionMode\n universal?: boolean\n reverse?: boolean\n voids?: boolean\n pass?: (entry: NodeEntry) => boolean\n}\n\nexport interface EditorNormalizeOptions {\n force?: boolean\n operation?: Operation\n}\n\nexport interface EditorParentOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorPathOptions {\n depth?: number\n edge?: LeafEdge\n}\n\nexport interface EditorPathRefOptions {\n affinity?: TextDirection | null\n}\n\nexport interface EditorPointOptions {\n edge?: LeafEdge\n}\n\nexport interface EditorPointRefOptions {\n affinity?: TextDirection | null\n}\n\nexport interface EditorPositionsOptions {\n at?: Location\n unit?: TextUnitAdjustment\n reverse?: boolean\n voids?: boolean\n}\n\nexport interface EditorPreviousOptions<T extends Node> {\n at?: Location\n match?: NodeMatch<T>\n mode?: SelectionMode\n voids?: boolean\n}\n\nexport interface EditorRangeRefOptions {\n affinity?: RangeDirection | null\n}\n\nexport interface EditorStringOptions {\n voids?: boolean\n}\n\nexport interface EditorUnhangRangeOptions {\n voids?: boolean\n}\n\nexport interface EditorVoidOptions {\n at?: Location\n mode?: MaximizeMode\n voids?: boolean\n}\n\nexport interface EditorInterface {\n /**\n * Get the ancestor above a location in the document.\n */\n above: <T extends Ancestor>(\n editor: Editor,\n options?: EditorAboveOptions<T>\n ) => NodeEntry<T> | undefined\n\n /**\n * Add a custom property to the leaf text nodes in the current selection.\n *\n * If the selection is currently collapsed, the marks will be added to the\n * `editor.marks` property instead, and applied when text is inserted next.\n */\n addMark: (editor: Editor, key: string, value: any) => void\n\n /**\n * Get the point after a location.\n */\n after: (\n editor: Editor,\n at: Location,\n options?: EditorAfterOptions\n ) => Point | undefined\n\n /**\n * Get the point before a location.\n */\n before: (\n editor: Editor,\n at: Location,\n options?: EditorBeforeOptions\n ) => Point | undefined\n\n /**\n * Delete content in the editor backward from the current selection.\n */\n deleteBackward: (\n editor: Editor,\n options?: EditorDirectedDeletionOptions\n ) => void\n\n /**\n * Delete content in the editor forward from the current selection.\n */\n deleteForward: (\n editor: Editor,\n options?: EditorDirectedDeletionOptions\n ) => void\n\n /**\n * Delete the content in the current selection.\n */\n deleteFragment: (\n editor: Editor,\n options?: EditorFragmentDeletionOptions\n ) => void\n\n /**\n * Get the start and end points of a location.\n */\n edges: (editor: Editor, at: Location) => [Point, Point]\n\n /**\n * Match a read-only element in the current branch of the editor.\n */\n elementReadOnly: (\n editor: Editor,\n options?: EditorElementReadOnlyOptions\n ) => NodeEntry<Element> | undefined\n\n /**\n * Get the end point of a location.\n */\n end: (editor: Editor, at: Location) => Point\n\n /**\n * Get the first node at a location.\n */\n first: (editor: Editor, at: Location) => NodeEntry\n\n /**\n * Get the fragment at a location.\n */\n fragment: (editor: Editor, at: Location) => Descendant[]\n\n /**\n * Check if a node has block children.\n */\n hasBlocks: (editor: Editor, element: Element) => boolean\n\n /**\n * Check if a node has inline and text children.\n */\n hasInlines: (editor: Editor, element: Element) => boolean\n\n hasPath: (editor: Editor, path: Path) => boolean\n\n /**\n * Check if a node has text children.\n */\n hasTexts: (editor: Editor, element: Element) => boolean\n\n /**\n * Insert a block break at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n insertBreak: (editor: Editor) => void\n\n /**\n * Inserts a fragment\n * at the specified location or (if not defined) the current selection or (if not defined) the end of the document.\n */\n insertFragment: (\n editor: Editor,\n fragment: Node[],\n options?: TextInsertFragmentOptions\n ) => void\n\n /**\n * Atomically inserts `nodes`\n * at the specified location or (if not defined) the current selection or (if not defined) the end of the document.\n */\n insertNode: <T extends Node>(\n editor: Editor,\n node: Node,\n options?: NodeInsertNodesOptions<T>\n ) => void\n\n /**\n * Insert a soft break at the current selection.\n *\n * If the selection is currently expanded, it will be deleted first.\n */\n insertSoftBreak: (editor: Editor) => void\n\n /**\n * Insert a string of text\n * at the specified location or (if not defined) the current selection or (if not defined) the end of the document.\n */\n insertText: (\n editor: Editor,\n text: string,\n options?: TextInsertTextOptions\n ) => void\n\n /**\n * Check if a value is a block `Element` object.\n */\n isBlock: (editor: Editor, value: Element) => boolean\n\n /**\n * Check if a point is an edge of a location.\n */\n isEdge: (editor: Editor, point: Point, at: Location) => boolean\n\n /**\n * Check if a value is an `Editor` object.\n */\n isEditor: (value: any, options?: EditorIsEditorOptions) => value is Editor\n\n /**\n * Check if a value is a read-only `Element` object.\n */\n isElementReadOnly: (editor: Editor, element: Element) => boolean\n\n /**\n * Check if an element is empty, accounting for void nodes.\n */\n isEmpty: (editor: Editor, element: Element) => boolean\n\n /**\n * Check if a point is the end point of a location.\n */\n isEnd: (editor: Editor, point: Point, at: Location) => boolean\n\n /**\n * Check if a value is an inline `Element` object.\n */\n isInline: (editor: Editor, value: Element) => boolean\n\n /**\n * Check if the editor is currently normalizing after each operation.\n */\n isNormalizing: (editor: Editor) => boolean\n\n /**\n * Check if a value is a selectable `Element` object.\n */\n isSelectable: (editor: Editor, element: Element) => boolean\n\n /**\n * Check if a point is the start point of a location.\n */\n isStart: (editor: Editor, point: Point, at: Location) => boolean\n\n /**\n * Check if a value is a void `Element` object.\n */\n isVoid: (editor: Editor, value: Element) => boolean\n\n /**\n * Get the last node at a location.\n */\n last: (editor: Editor, at: Location) => NodeEntry\n\n /**\n * Get the leaf text node at a location.\n */\n leaf: (\n editor: Editor,\n at: Location,\n options?: EditorLeafOptions\n ) => NodeEntry<Text>\n\n /**\n * Iterate through all of the levels at a location.\n */\n levels: <T extends Node>(\n editor: Editor,\n options?: EditorLevelsOptions<T>\n ) => Generator<NodeEntry<T>, void, undefined>\n\n /**\n * Get the marks that would be added to text at the current selection.\n */\n marks: (editor: Editor) => Omit<Text, 'text'> | null\n\n /**\n * Get the matching node in the branch of the document after a location.\n */\n next: <T extends Descendant>(\n editor: Editor,\n options?: EditorNextOptions<T>\n ) => NodeEntry<T> | undefined\n\n /**\n * Get the node at a location.\n */\n node: (editor: Editor, at: Location, options?: EditorNodeOptions) => NodeEntry\n\n /**\n * Iterate through all of the nodes in the Editor.\n */\n nodes: <T extends Node>(\n editor: Editor,\n options?: EditorNodesOptions<T>\n ) => Generator<NodeEntry<T>, void, undefined>\n\n /**\n * Normalize any dirty objects in the editor.\n */\n normalize: (editor: Editor, options?: EditorNormalizeOptions) => void\n\n /**\n * Get the parent node of a location.\n */\n parent: (\n editor: Editor,\n at: Location,\n options?: EditorParentOptions\n ) => NodeEntry<Ancestor>\n\n /**\n * Get the path of a location.\n */\n path: (editor: Editor, at: Location, options?: EditorPathOptions) => Path\n\n /**\n * Create a mutable ref for a `Path` object, which will stay in sync as new\n * operations are applied to the editor.\n */\n pathRef: (\n editor: Editor,\n path: Path,\n options?: EditorPathRefOptions\n ) => PathRef\n\n /**\n * Get the set of currently tracked path refs of the editor.\n */\n pathRefs: (editor: Editor) => Set<PathRef>\n\n /**\n * Get the start or end point of a location.\n */\n point: (editor: Editor, at: Location, options?: EditorPointOptions) => Point\n\n /**\n * Create a mutable ref for a `Point` object, which will stay in sync as new\n * operations are applied to the editor.\n */\n pointRef: (\n editor: Editor,\n point: Point,\n options?: EditorPointRefOptions\n ) => PointRef\n\n /**\n * Get the set of currently tracked point refs of the editor.\n */\n pointRefs: (editor: Editor) => Set<PointRef>\n\n /**\n * Return all the positions in `at` range where a `Point` can be placed.\n *\n * By default, moves forward by individual offsets at a time, but\n * the `unit` option can be used to to move by character, word, line, or block.\n *\n * The `reverse` option can be used to change iteration direction.\n *\n * Note: By default void nodes are treated as a single point and iteration\n * will not happen inside their content unless you pass in true for the\n * `voids` option, then iteration will occur.\n */\n positions: (\n editor: Editor,\n options?: EditorPositionsOptions\n ) => Generator<Point, void, undefined>\n\n /**\n * Get the matching node in the branch of the document before a location.\n */\n previous: <T extends Node>(\n editor: Editor,\n options?: EditorPreviousOptions<T>\n ) => NodeEntry<T> | undefined\n\n /**\n * Get a range of a location.\n */\n range: (editor: Editor, at: Location, to?: Location) => Range\n\n /**\n * Create a mutable ref for a `Range` object, which will stay in sync as new\n * operations are applied to the editor.\n */\n rangeRef: (\n editor: Editor,\n range: Range,\n options?: EditorRangeRefOptions\n ) => RangeRef\n\n /**\n * Get the set of currently tracked range refs of the editor.\n */\n rangeRefs: (editor: Editor) => Set<RangeRef>\n\n /**\n * Remove a custom property from all of the leaf text nodes in the current\n * selection.\n *\n * If the selection is currently collapsed, the removal will be stored on\n * `editor.marks` and applied to the text inserted next.\n */\n removeMark: (editor: Editor, key: string) => void\n\n /**\n * Manually set if the editor should currently be normalizing.\n *\n * Note: Using this incorrectly can leave the editor in an invalid state.\n *\n */\n setNormalizing: (editor: Editor, isNormalizing: boolean) => void\n\n /**\n * Get the start point of a location.\n */\n start: (editor: Editor, at: Location) => Point\n\n /**\n * Get the text string content of a location.\n *\n * Note: by default the text of void nodes is considered to be an empty\n * string, regardless of content, unless you pass in true for the voids option\n */\n string: (\n editor: Editor,\n at: Location,\n options?: EditorStringOptions\n ) => string\n\n /**\n * Convert a range into a non-hanging one.\n */\n unhangRange: (\n editor: Editor,\n range: Range,\n options?: EditorUnhangRangeOptions\n ) => Range\n\n /**\n * Match a void node in the current branch of the editor.\n */\n void: (\n editor: Editor,\n options?: EditorVoidOptions\n ) => NodeEntry<Element> | undefined\n\n /**\n * Call a function, deferring normalization until after it completes.\n */\n withoutNormalizing: (editor: Editor, fn: () => void) => void\n\n /**\n * Call a function, Determine whether or not remove the previous node when merge.\n */\n shouldMergeNodesRemovePrevNode: (\n editor: Editor,\n prevNodeEntry: NodeEntry,\n curNodeEntry: NodeEntry\n ) => boolean\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Editor: EditorInterface = {\n above(editor, options) {\n return editor.above(options)\n },\n\n addMark(editor, key, value) {\n editor.addMark(key, value)\n },\n\n after(editor, at, options) {\n return editor.after(at, options)\n },\n\n before(editor, at, options) {\n return editor.before(at, options)\n },\n\n deleteBackward(editor, options = {}) {\n const { unit = 'character' } = options\n editor.deleteBackward(unit)\n },\n\n deleteForward(editor, options = {}) {\n const { unit = 'character' } = options\n editor.deleteForward(unit)\n },\n\n deleteFragment(editor, options) {\n editor.deleteFragment(options)\n },\n\n edges(editor, at) {\n return editor.edges(at)\n },\n\n elementReadOnly(editor: Editor, options: EditorElementReadOnlyOptions = {}) {\n return editor.elementReadOnly(options)\n },\n\n end(editor, at) {\n return editor.end(at)\n },\n\n first(editor, at) {\n return editor.first(at)\n },\n\n fragment(editor, at) {\n return editor.fragment(at)\n },\n\n hasBlocks(editor, element) {\n return editor.hasBlocks(element)\n },\n\n hasInlines(editor, element) {\n return editor.hasInlines(element)\n },\n\n hasPath(editor, path) {\n return editor.hasPath(path)\n },\n\n hasTexts(editor, element) {\n return editor.hasTexts(element)\n },\n\n insertBreak(editor) {\n editor.insertBreak()\n },\n\n insertFragment(editor, fragment, options) {\n editor.insertFragment(fragment, options)\n },\n\n insertNode(editor, node) {\n editor.insertNode(node)\n },\n\n insertSoftBreak(editor) {\n editor.insertSoftBreak()\n },\n\n insertText(editor, text) {\n editor.insertText(text)\n },\n\n isBlock(editor, value) {\n return editor.isBlock(value)\n },\n\n isEdge(editor, point, at) {\n return editor.isEdge(point, at)\n },\n\n isEditor(value: any): value is Editor {\n return isEditor(value)\n },\n\n isElementReadOnly(editor, element) {\n return editor.isElementReadOnly(element)\n },\n\n isEmpty(editor, element) {\n return editor.isEmpty(element)\n },\n\n isEnd(editor, point, at) {\n return editor.isEnd(point, at)\n },\n\n isInline(editor, value) {\n return editor.isInline(value)\n },\n\n isNormalizing(editor) {\n return editor.isNormalizing()\n },\n\n isSelectable(editor: Editor, value: Element) {\n return editor.isSelectable(value)\n },\n\n isStart(editor, point, at) {\n return editor.isStart(point, at)\n },\n\n isVoid(editor, value) {\n return editor.isVoid(value)\n },\n\n last(editor, at) {\n return editor.last(at)\n },\n\n leaf(editor, at, options) {\n return editor.leaf(at, options)\n },\n\n levels(editor, options) {\n return editor.levels(options)\n },\n\n marks(editor) {\n return editor.getMarks()\n },\n\n next<T extends Descendant>(\n editor: Editor,\n options?: EditorNextOptions<T>\n ): NodeEntry<T> | undefined {\n return editor.next(options)\n },\n\n node(editor, at, options) {\n return editor.node(at, options)\n },\n\n nodes(editor, options) {\n return editor.nodes(options)\n },\n\n normalize(editor, options) {\n editor.normalize(options)\n },\n\n parent(editor, at, options) {\n return editor.parent(at, options)\n },\n\n path(editor, at, options) {\n return editor.path(at, options)\n },\n\n pathRef(editor, path, options) {\n return editor.pathRef(path, options)\n },\n\n pathRefs(editor) {\n return editor.pathRefs()\n },\n\n point(editor, at, options) {\n return editor.point(at, options)\n },\n\n pointRef(editor, point, options) {\n return editor.pointRef(point, options)\n },\n\n pointRefs(editor) {\n return editor.pointRefs()\n },\n\n positions(editor, options) {\n return editor.positions(options)\n },\n\n previous(editor, options) {\n return editor.previous(options)\n },\n\n range(editor, at, to) {\n return editor.range(at, to)\n },\n\n rangeRef(editor, range, options) {\n return editor.rangeRef(range, options)\n },\n\n rangeRefs(editor) {\n return editor.rangeRefs()\n },\n\n removeMark(editor, key) {\n editor.removeMark(key)\n },\n\n setNormalizing(editor, isNormalizing) {\n editor.setNormalizing(isNormalizing)\n },\n\n start(editor, at) {\n return editor.start(at)\n },\n\n string(editor, at, options) {\n return editor.string(at, options)\n },\n\n unhangRange(editor, range, options) {\n return editor.unhangRange(range, options)\n },\n\n void(editor, options) {\n return editor.void(options)\n },\n\n withoutNormalizing(editor, fn: () => void) {\n editor.withoutNormalizing(fn)\n },\n shouldMergeNodesRemovePrevNode: (editor, prevNode, curNode) => {\n return editor.shouldMergeNodesRemovePrevNode(prevNode, curNode)\n },\n}\n\n/**\n * A helper type for narrowing matched nodes with a predicate.\n */\n\nexport type NodeMatch<T extends Node> =\n | ((node: Node, path: Path) => node is T)\n | ((node: Node, path: Path) => boolean)\n\nexport type PropsCompare = (prop: Partial<Node>, node: Partial<Node>) => boolean\nexport type PropsMerge = (prop: Partial<Node>, node: Partial<Node>) => object\n","import { Path, Point, Range } from '..'\n\n/**\n * The `Location` interface is a union of the ways to refer to a specific\n * location in a Slate document: paths, points or ranges.\n *\n * Methods will often accept a `Location` instead of requiring only a `Path`,\n * `Point` or `Range`. This eliminates the need for developers to manage\n * converting between the different interfaces in their own code base.\n */\n\nexport type Location = Path | Point | Range\n\nexport interface LocationInterface {\n /**\n * Check if a value implements the `Location` interface.\n */\n isLocation: (value: any) => value is Location\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Location: LocationInterface = {\n isLocation(value: any): value is Location {\n return Path.isPath(value) || Point.isPoint(value) || Range.isRange(value)\n },\n}\n\n/**\n * The `Span` interface is a low-level way to refer to locations in nodes\n * without using `Point` which requires leaf text nodes to be present.\n */\n\nexport type Span = [Path, Path]\n\nexport interface SpanInterface {\n /**\n * Check if a value implements the `Span` interface.\n */\n isSpan: (value: any) => value is Span\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Span: SpanInterface = {\n isSpan(value: any): value is Span {\n return (\n Array.isArray(value) && value.length === 2 && value.every(Path.isPath)\n )\n },\n}\n","import { ExtendedType, Operation, Path, isObject } from '..'\nimport { TextDirection } from '../types/types'\n\n/**\n * `Point` objects refer to a specific location in a text node in a Slate\n * document. Its path refers to the location of the node in the tree, and its\n * offset refers to the distance into the node's string of text. Points can\n * only refer to `Text` nodes.\n */\n\nexport interface BasePoint {\n path: Path\n offset: number\n}\n\nexport type Point = ExtendedType<'Point', BasePoint>\n\nexport interface PointTransformOptions {\n affinity?: TextDirection | null\n}\n\nexport interface PointInterface {\n /**\n * Compare a point to another, returning an integer indicating whether the\n * point was before, at, or after the other.\n */\n compare: (point: Point, another: Point) => -1 | 0 | 1\n\n /**\n * Check if a point is after another.\n */\n isAfter: (point: Point, another: Point) => boolean\n\n /**\n * Check if a point is before another.\n */\n isBefore: (point: Point, another: Point) => boolean\n\n /**\n * Check if a point is exactly equal to another.\n */\n equals: (point: Point, another: Point) => boolean\n\n /**\n * Check if a value implements the `Point` interface.\n */\n isPoint: (value: any) => value is Point\n\n /**\n * Transform a point by an operation.\n */\n transform: (\n point: Point,\n op: Operation,\n options?: PointTransformOptions\n ) => Point | null\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Point: PointInterface = {\n compare(point: Point, another: Point): -1 | 0 | 1 {\n const result = Path.compare(point.path, another.path)\n\n if (result === 0) {\n if (point.offset < another.offset) return -1\n if (point.offset > another.offset) return 1\n return 0\n }\n\n return result\n },\n\n isAfter(point: Point, another: Point): boolean {\n return Point.compare(point, another) === 1\n },\n\n isBefore(point: Point, another: Point): boolean {\n return Point.compare(point, another) === -1\n },\n\n equals(point: Point, another: Point): boolean {\n // PERF: ensure the offsets are equal first since they are cheaper to check.\n return (\n point.offset === another.offset && Path.equals(point.path, another.path)\n )\n },\n\n isPoint(value: any): value is Point {\n return (\n isObject(value) &&\n typeof value.offset === 'number' &&\n Path.isPath(value.path)\n )\n },\n\n transform(\n point: Point | null,\n op: Operation,\n options: PointTransformOptions = {}\n ): Point | null {\n if (point === null) {\n return null\n }\n\n const { affinity = 'forward' } = options\n let { path, offset } = point\n\n switch (op.type) {\n case 'insert_node':\n case 'move_node': {\n path = Path.transform(path, op, options)!\n break\n }\n\n case 'insert_text': {\n if (\n Path.equals(op.path, path) &&\n (op.offset < offset ||\n (op.offset === offset && affinity === 'forward'))\n ) {\n offset += op.text.length\n }\n\n break\n }\n\n case 'merge_node': {\n if (Path.equals(op.path, path)) {\n offset += op.position\n }\n\n path = Path.transform(path, op, options)!\n break\n }\n\n case 'remove_text': {\n if (Path.equals(op.path, path) && op.offset <= offset) {\n offset -= Math.min(offset - op.offset, op.text.length)\n }\n\n break\n }\n\n case 'remove_node': {\n if (Path.equals(op.path, path) || Path.isAncestor(op.path, path)) {\n return null\n }\n\n path = Path.transform(path, op, options)!\n break\n }\n\n case 'split_node': {\n if (Path.equals(op.path, path)) {\n if (op.position === offset && affinity == null) {\n return null\n } else if (\n op.position < offset ||\n (op.position === offset && affinity === 'forward')\n ) {\n offset -= op.position\n\n path = Path.transform(path, op, {\n ...options,\n affinity: 'forward',\n })!\n }\n } else {\n path = Path.transform(path, op, options)!\n }\n\n break\n }\n\n default:\n return point\n }\n\n return { path, offset }\n },\n}\n\n/**\n * `PointEntry` objects are returned when iterating over `Point` objects that\n * belong to a range.\n */\n\nexport type PointEntry = [Point, 'anchor' | 'focus']\n","export type Scrubber = (key: string, value: unknown) => unknown\n\nexport interface ScrubberInterface {\n setScrubber(scrubber: Scrubber | undefined): void\n stringify(value: any): string\n}\n\nlet _scrubber: Scrubber | undefined = undefined\n\n/**\n * This interface implements a stringify() function, which is used by Slate\n * internally when generating exceptions containing end user data. Developers\n * using Slate may call Scrubber.setScrubber() to alter the behavior of this\n * stringify() function.\n *\n * For example, to prevent the cleartext logging of 'text' fields within Nodes:\n *\n * import { Scrubber } from 'slate';\n * Scrubber.setScrubber((key, val) => {\n * if (key === 'text') return '...scrubbed...'\n * return val\n * });\n *\n */\n// eslint-disable-next-line no-redeclare\nexport const Scrubber: ScrubberInterface = {\n setScrubber(scrubber: Scrubber | undefined): void {\n _scrubber = scrubber\n },\n\n stringify(value: any): string {\n return JSON.stringify(value, _scrubber)\n },\n}\n","import { Range, isObject } from '..'\nimport { ExtendedType } from '../types/custom-types'\nimport { isDeepEqual } from '../utils/deep-equal'\n\n/**\n * `Text` objects represent the nodes that contain the actual text content of a\n * Slate document along with any formatting properties. They are always leaf\n * nodes in the document tree as they cannot contain any children.\n */\n\nexport interface BaseText {\n text: string\n}\n\nexport type Text = ExtendedType<'Text', BaseText>\n\nexport interface LeafPosition {\n start: number\n end: number\n isFirst?: true\n isLast?: true\n}\n\nexport interface TextEqualsOptions {\n loose?: boolean\n}\n\nexport type DecoratedRange = Range & {\n /**\n * Customize how another decoration is merged into a text node. If not specified, `Object.assign` would be used.\n * It is useful for overlapping decorations with the same key but different values.\n */\n merge?: (leaf: Text, decoration: object) => void\n}\n\nexport interface TextInterface {\n /**\n * Check if two text nodes are equal.\n *\n * When loose is set, the text is not compared. This is\n * used to check whether sibling text nodes can be merged.\n */\n equals: (text: Text, another: Text, options?: TextEqualsOptions) => boolean\n\n /**\n * Check if a value implements the `Text` interface.\n */\n isText: (value: any) => value is Text\n\n /**\n * Check if a value is a list of `Text` objects.\n */\n isTextList: (value: any) => value is Text[]\n\n /**\n * Check if some props are a partial of Text.\n */\n isTextProps: (props: any) => props is Partial<Text>\n\n /**\n * Check if an text matches set of properties.\n *\n * Note: this is for matching custom properties, and it does not ensure that\n * the `text` property are two nodes equal.\n */\n matches: (text: Text, props: Partial<Text>) => boolean\n\n /**\n * Get the leaves for a text node given decorations.\n */\n decorations: (\n node: Text,\n decorations: DecoratedRange[]\n ) => { leaf: Text; position?: LeafPosition }[]\n}\n\n// eslint-disable-next-line no-redeclare\nexport const Text: TextInterface = {\n equals(text: Text, another: Text, options: TextEqualsOptions = {}): boolean {\n const { loose = false } = options\n\n function omitText(obj: Record<any, any>) {\n const { text, ...rest } = obj\n\n return rest\n }\n\n return isDeepEqual(\n loose ? omitText(text) : text,\n loose ? omitText(another) : another\n )\n },\n\n isText(value: any): value is Text {\n return isObject(value) && typeof value.text === 'string'\n },\n\n isTextList(value: any): value is Text[] {\n return Array.isArray(value) && value.every(val => Text.isText(val))\n },\n\n isTextProps(props: any): props is Partial<Text> {\n return (props as Partial<Text>).text !== undefined\n },\n\n matches(text: Text, props: Partial<Text>): boolean {\n for (const key in props) {\n if (key === 'text') {\n continue\n }\n\n if (\n !text.hasOwnProperty(key) ||\n text[<keyof Text>key] !== props[<keyof Text>key]\n ) {\n return false\n }\n }\n\n return true\n },\n\n decorations(\n node: Text,\n decorations: DecoratedRange[]\n ): { leaf: Text; position?: LeafPosition }[] {\n let leaves: { leaf: Text; position?: LeafPosition }[] = [\n { leaf: { ...node } },\n ]\n\n for (const dec of decorations) {\n const { anchor, focus, merge: mergeDecoration, ...rest } = dec\n const [start, end] = Range.edges(dec)\n const next = []\n let leafEnd = 0\n const decorationStart = start.offset\n const decorationEnd = end.offset\n const merge = mergeDecoration ?? Object.assign\n\n for (const { leaf } of leaves) {\n const { length } = leaf.text\n const leafStart = leafEnd\n leafEnd += length\n\n // If the range encompasses the entire leaf, add the range.\n if (decorationStart <= leafStart && leafEnd <= decorationEnd) {\n merge(leaf, rest)\n next.push({ leaf })\n continue\n }\n\n // If the range expanded and match the leaf, or starts after, or ends before it, continue.\n if (\n (decorationStart !== decorationEnd &&\n (decorationStart === leafEnd || decorationEnd === leafStart)) ||\n decorationStart > leafEnd ||\n decorationEnd < leafStart ||\n (decorationEnd === leafStart && leafStart !== 0)\n ) {\n next.push({ leaf })\n continue\n }\n\n // Otherwise we need to split the leaf, at the start, end, or both,\n // and add the range to the middle intersecting section. Do the end\n // split first since we don't need to update the offset that way.\n let middle = leaf\n let before\n let after\n\n if (decorationEnd < leafEnd) {\n const off = decorationEnd - leafStart\n after = { leaf: { ...middle, text: middle.text.slice(off) } }\n middle = { ...middle, text: middle.text.slice(0, off) }\n }\n\n if (decorationStart > leafStart) {\n const off = decorationStart - leafStart\n before = { leaf: { ...middle, text: middle.text.slice(0, off) } }\n middle = { ...middle, text: middle.text.slice(off) }\n }\n\n merge(middle, rest)\n\n if (before) {\n next.push(before)\n }\n\n next.push({ leaf: middle })\n\n if (after) {\n next.push(after)\n }\n }\n\n leaves = next\n }\n\n if (leaves.length > 1) {\n let currentOffset = 0\n for (const [index, item] of leaves.entries()) {\n const start = currentOffset\n const end = start + item.leaf.text.length\n const position: LeafPosition = { start, end }\n\n if (index === 0) position.isFirst = true\n if (index === leaves.length - 1) position.isLast = true\n\n item.position = position\n currentOffset = end\n }\n }\n\n return leaves\n },\n}\n","import { Editor, Location } from '../interfaces'\n\n/**\n * Get the default location to insert content into the editor.\n * By default, use the selection as the target location. But if there is\n * no selection, insert at the end of the document since that is such a\n * common use case when inserting from a non-selected state.\n */\nexport const getDefaultInsertLocation = (editor: Editor): Location => {\n if (editor.selection) {\n return editor.selection\n } else if (editor.children.length > 0) {\n return Editor.end(editor, [])\n } else {\n return [0]\n }\n}\n","import { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { Node } from '../interfaces/node'\n\nexport const matchPath = (\n editor: Editor,\n path: Path\n): ((node: Node) => boolean) => {\n const [node] = Editor.node(editor, path)\n return n => n === node\n}\n","// Character (grapheme cluster) boundaries are determined according to\n// the default grapheme cluster boundary specification, extended grapheme clusters variant[1].\n//\n// References:\n//\n// [1] https://www.unicode.org/reports/tr29/#Default_Grapheme_Cluster_Table\n// [2] https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt\n// [3] https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.html\n// [4] https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.txt\n\n/**\n * Get the distance to the end of the first character in a string of text.\n */\n\nexport const getCharacterDistance = (str: string, isRTL = false): number => {\n const isLTR = !isRTL\n const codepoints = isRTL ? codepointsIteratorRTL(str) : str\n\n let left: CodepointType = CodepointType.None\n let right: CodepointType = CodepointType.None\n let distance = 0\n // Evaluation of these conditions are deferred.\n let gb11: boolean | null = null // Is GB11 applicable?\n let gb12Or13: boolean | null = null // Is GB12 or GB13 applicable?\n\n for (const char of codepoints) {\n const code = char.codePointAt(0)\n if (!code) break\n\n const type = getCodepointType(char, code)\n ;[left, right] = isLTR ? [right, type] : [type, left]\n\n if (\n intersects(left, CodepointType.ZWJ) &&\n intersects(right, CodepointType.ExtPict)\n ) {\n if (isLTR) {\n gb11 = endsWithEmojiZWJ(str.substring(0, distance))\n } else {\n gb11 = endsWithEmojiZWJ(str.substring(0, str.length - distance))\n }\n if (!gb11) break\n }\n\n if (\n intersects(left, CodepointType.RI) &&\n intersects(right, CodepointType.RI)\n ) {\n if (gb12Or13 !== null) {\n gb12Or13 = !gb12Or13\n } else {\n if (isLTR) {\n gb12Or13 = true\n } else {\n gb12Or13 = endsWithOddNumberOfRIs(\n str.substring(0, str.length - distance)\n )\n }\n }\n if (!gb12Or13) break\n }\n\n if (\n left !== CodepointType.None &&\n right !== CodepointType.None &&\n isBoundaryPair(left, right)\n ) {\n break\n }\n\n distance += char.length\n }\n\n return distance || 1\n}\n\nconst SPACE = /\\s/\nconst PUNCTUATION =\n /[\\u002B\\u0021-\\u0023\\u0025-\\u002A\\u002C-\\u002F\\u003A\\u003B\\u003F\\u0040\\u005B-\\u005D\\u005F\\u007B\\u007D\\u00A1\\u00A7\\u00AB\\u00B6\\u00B7\\u00BB\\u00BF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061E\\u061F\\u066A-\\u066D\\u06D4\\u0700-\\u070D\\u07F7-\\u07F9\\u0830-\\u083E\\u085E\\u0964\\u0965\\u0970\\u0AF0\\u0DF4\\u0E4F\\u0E5A\\u0E5B\\u0F04-\\u0F12\\u0F14\\u0F3A-\\u0F3D\\u0F85\\u0FD0-\\u0FD4\\u0FD9\\u0FDA\\u104A-\\u104F\\u10FB\\u1360-\\u1368\\u1400\\u166D\\u166E\\u169B\\u169C\\u16EB-\\u16ED\\u1735\\u1736\\u17D4-\\u17D6\\u17D8-\\u17DA\\u1800-\\u180A\\u1944\\u1945\\u1A1E\\u1A1F\\u1AA0-\\u1AA6\\u1AA8-\\u1AAD\\u1B5A-\\u1B60\\u1BFC-\\u1BFF\\u1C3B-\\u1C3F\\u1C7E\\u1C7F\\u1CC0-\\u1CC7\\u1CD3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205E\\u207D\\u207E\\u208D\\u208E\\u2329\\u232A\\u2768-\\u2775\\u27C5\\u27C6\\u27E6-\\u27EF\\u2983-\\u2998\\u29D8-\\u29DB\\u29FC\\u29FD\\u2CF9-\\u2CFC\\u2CFE\\u2CFF\\u2D70\\u2E00-\\u2E2E\\u2E30-\\u2E3B\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u3030\\u303D\\u30A0\\u30FB\\uA4FE\\uA4FF\\uA60D-\\uA60F\\uA673\\uA67E\\uA6F2-\\uA6F7\\uA874-\\uA877\\uA8CE\\uA8CF\\uA8F8-\\uA8FA\\uA92E\\uA92F\\uA95F\\uA9C1-\\uA9CD\\uA9DE\\uA9DF\\uAA5C-\\uAA5F\\uAADE\\uAADF\\uAAF0\\uAAF1\\uABEB\\uFD3E\\uFD3F\\uFE10-\\uFE19\\uFE30-\\uFE52\\uFE54-\\uFE61\\uFE63\\uFE68\\uFE6A\\uFE6B\\uFF01-\\uFF03\\uFF05-\\uFF0A\\uFF0C-\\uFF0F\\uFF1A\\uFF1B\\uFF1F\\uFF20\\uFF3B-\\uFF3D\\uFF3F\\uFF5B\\uFF5D\\uFF5F-\\uFF65]/\nconst CHAMELEON = /['\\u2018\\u2019]/\n\n/**\n * Get the distance to the end of the first word in a string of text.\n */\n\nexport const getWordDistance = (text: string, isRTL = false): number => {\n let dist = 0\n let started = false\n\n while (text.length > 0) {\n const charDist = getCharacterDistance(text, isRTL)\n const [char, remaining] = splitByCharacterDistance(text, charDist, isRTL)\n\n if (isWordCharacter(char, remaining, isRTL)) {\n started = true\n dist += charDist\n } else if (!started) {\n dist += charDist\n } else {\n break\n }\n\n text = remaining\n }\n\n return dist\n}\n\n/**\n * Split a string in two parts at a given distance starting from the end when\n * `isRTL` is set to `true`.\n */\n\nexport const splitByCharacterDistance = (\n str: string,\n dist: number,\n isRTL?: boolean\n): [string, string] => {\n if (isRTL) {\n const at = str.length - dist\n return [str.slice(at, str.length), str.slice(0, at)]\n }\n\n return [str.slice(0, dist), str.slice(dist)]\n}\n\n/**\n * Check if a character is a word character. The `remaining` argument is used\n * because sometimes you must read subsequent characters to truly determine it.\n */\n\nconst isWordCharacter = (\n char: string,\n remaining: string,\n isRTL = false\n): boolean => {\n if (SPACE.test(char)) {\n return false\n }\n\n // Chameleons count as word characters as long as they're in a word, so\n // recurse to see if the next one is a word character or not.\n if (CHAMELEON.test(char)) {\n const charDist = getCharacterDistance(remaining, isRTL)\n const [nextChar, nextRemaining] = splitByCharacterDistance(\n remaining,\n charDist,\n isRTL\n )\n\n if (isWordCharacter(nextChar, nextRemaining, isRTL)) {\n return true\n }\n }\n\n if (PUNCTUATION.test(char)) {\n return false\n }\n\n return true\n}\n\n/**\n * Iterate on codepoints from right to left.\n */\n\nexport const codepointsIteratorRTL = function* (str: string) {\n const end = str.length - 1\n\n for (let i = 0; i < str.length; i++) {\n const char1 = str.charAt(end - i)\n\n if (isLowSurrogate(char1.charCodeAt(0))) {\n const char2 = str.charAt(end - i - 1)\n if (isHighSurrogate(char2.charCodeAt(0))) {\n yield char2 + char1\n\n i++\n continue\n }\n }\n\n yield char1\n }\n}\n\n/**\n * Is `charCode` a high surrogate.\n *\n * https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates\n */\n\nconst isHighSurrogate = (charCode: number) => {\n return charCode >= 0xd800 && charCode <= 0xdbff\n}\n\n/**\n * Is `charCode` a low surrogate.\n *\n * https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates\n */\n\nconst isLowSurrogate = (charCode: number) => {\n return charCode >= 0xdc00 && charCode <= 0xdfff\n}\n\nenum CodepointType {\n None = 0,\n Extend = 1 << 0,\n ZWJ = 1 << 1,\n RI = 1 << 2,\n Prepend = 1 << 3,\n SpacingMark = 1 << 4,\n L = 1 << 5,\n V = 1 << 6,\n T = 1 << 7,\n LV = 1 << 8,\n LVT = 1 << 9,\n ExtPict = 1 << 10,\n Any = 1 << 11,\n}\n\nconst reExtend = /^[\\p{Gr_Ext}\\p{EMod}]$/u\nconst rePrepend =\n /^[\\u0600-\\u0605\\u06DD\\u070F\\u0890-\\u0891\\u08E2\\u0D4E\\u{110BD}\\u{110CD}\\u{111C2}-\\u{111C3}\\u{1193F}\\u{11941}\\u{11A3A}\\u{11A84}-\\u{11A89}\\u{11D46}]$/u\nconst reSpacingMark =\n /^[\\u0903\\u093B\\u093E-\\u0940\\u0949-\\u094C\\u094E-\\u094F\\u0982-\\u0983\\u09BF-\\u09C0\\u09C7-\\u09C8\\u09CB-\\u09CC\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB-\\u0ACC\\u0B02-\\u0B03\\u0B40\\u0B47-\\u0B48\\u0B4B-\\u0B4C\\u0BBF\\u0BC1-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82-\\u0C83\\u0CBE\\u0CC0-\\u0CC1\\u0CC3-\\u0CC4\\u0CC7-\\u0CC8\\u0CCA-\\u0CCB\\u0D02-\\u0D03\\u0D3F-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D82-\\u0D83\\u0DD0-\\u0DD1\\u0DD8-\\u0DDE\\u0DF2-\\u0DF3\\u0E33\\u0EB3\\u0F3E-\\u0F3F\\u0F7F\\u1031\\u103B-\\u103C\\u1056-\\u1057\\u1084\\u1715\\u1734\\u17B6\\u17BE-\\u17C5\\u17C7-\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930-\\u1931\\u1933-\\u1938\\u1A19-\\u1A1A\\u1A55\\u1A57\\u1A6D-\\u1A72\\u1B04\\u1B3B\\u1B3D-\\u1B41\\u1B43-\\u1B44\\u1B82\\u1BA1\\u1BA6-\\u1BA7\\u1BAA\\u1BE7\\u1BEA-\\u1BEC\\u1BEE\\u1BF2-\\u1BF3\\u1C24-\\u1C2B\\u1C34-\\u1C35\\u1CE1\\u1CF7\\uA823-\\uA824\\uA827\\uA880-\\uA881\\uA8B4-\\uA8C3\\uA952-\\uA953\\uA983\\uA9B4-\\uA9B5\\uA9BA-\\uA9BB\\uA9BE-\\uA9C0\\uAA2F-\\uAA30\\uAA33-\\uAA34\\uAA4D\\uAAEB\\uAAEE-\\uAAEF\\uAAF5\\uABE3-\\uABE4\\uABE6-\\uABE7\\uABE9-\\uABEA\\uABEC\\u{11000}\\u{11002}\\u{11082}\\u{110B0}-\\u{110B2}\\u{110B7}-\\u{110B8}\\u{1112C}\\u{11145}-\\u{11146}\\u{11182}\\u{111B3}-\\u{111B5}\\u{111BF}-\\u{111C0}\\u{111CE}\\u{1122C}-\\u{1122E}\\u{11232}-\\u{11233}\\u{11235}\\u{112E0}-\\u{112E2}\\u{11302}-\\u{11303}\\u{1133F}\\u{11341}-\\u{11344}\\u{11347}-\\u{11348}\\u{1134B}-\\u{1134D}\\u{11362}-\\u{11363}\\u{11435}-\\u{11437}\\u{11440}-\\u{11441}\\u{11445}\\u{114B1}-\\u{114B2}\\u{114B9}\\u{114BB}-\\u{114BC}\\u{114BE}\\u{114C1}\\u{115B0}-\\u{115B1}\\u{115B8}-\\u{115BB}\\u{115BE}\\u{11630}-\\u{11632}\\u{1163B}-\\u{1163C}\\u{1163E}\\u{116AC}\\u{116AE}-\\u{116AF}\\u{116B6}\\u{11726}\\u{1182C}-\\u{1182E}\\u{11838}\\u{11931}-\\u{11935}\\u{11937}-\\u{11938}\\u{1193D}\\u{11940}\\u{11942}\\u{119D1}-\\u{119D3}\\u{119DC}-\\u{119DF}\\u{119E4}\\u{11A39}\\u{11A57}-\\u{11A58}\\u{11A97}\\u{11C2F}\\u{11C3E}\\u{11CA9}\\u{11CB1}\\u{11CB4}\\u{11D8A}-\\u{11D8E}\\u{11D93}-\\u{11D94}\\u{11D96}\\u{11EF5}-\\u{11EF6}\\u{16F51}-\\u{16F87}\\u{16FF0}-\\u{16FF1}\\u{1D166}\\u{1D16D}]$/u\nconst reL = /^[\\u1100-\\u115F\\uA960-\\uA97C]$/u\nconst reV = /^[\\u1160-\\u11A7\\uD7B0-\\uD7C6]$/u\nconst reT = /^[\\u11A8-\\u11FF\\uD7CB-\\uD7FB]$/u\nconst reLV =\n /^[\\uAC00\\uAC1C\\uAC38\\uAC54\\uAC70\\uAC8C\\uACA8\\uACC4\\uACE0\\uACFC\\uAD18\\uAD34\\uAD50\\uAD6C\\uAD88\\uADA4\\uADC0\\uADDC\\uADF8\\uAE14\\uAE30\\uAE4C\\uAE68\\uAE84\\uAEA0\\uAEBC\\uAED8\\uAEF4\\uAF10\\uAF2C\\uAF48\\uAF64\\uAF80\\uAF9C\\uAFB8\\uAFD4\\uAFF0\\uB00C\\uB028\\uB044\\uB060\\uB07C\\uB098\\uB0B4\\uB0D0\\uB0EC\\uB108\\uB124\\uB140\\uB15C\\uB178\\uB194\\uB1B0\\uB1CC\\uB1E8\\uB204\\uB220\\uB23C\\uB258\\uB274\\uB290\\uB2AC\\uB2C8\\uB2E4\\uB300\\uB31C\\uB338\\uB354\\uB370\\uB38C\\uB3A8\\uB3C4\\uB3E0\\uB3FC\\uB418\\uB434\\uB450\\uB46C\\uB488\\uB4A4\\uB4C0\\uB4DC\\uB4F8\\uB514\\uB530\\uB54C\\uB568\\uB584\\uB5A0\\uB5BC\\uB5D8\\uB5F4\\uB610\\uB62C\\uB648\\uB664\\uB680\\uB69C\\uB6B8\\uB6D4\\uB6F0\\uB70C\\uB728\\uB744\\uB760\\uB77C\\uB798\\uB7B4\\uB7D0\\uB7EC\\uB808\\uB824\\uB840\\uB85C\\uB878\\uB894\\uB8B0\\uB8CC\\uB8E8\\uB904\\uB920\\uB93C\\uB958\\uB974\\uB990\\uB9AC\\uB9C8\\uB9E4\\uBA00\\uBA1C\\uBA38\\uBA54\\uBA70\\uBA8C\\uBAA8\\uBAC4\\uBAE0\\uBAFC\\uBB18\\uBB34\\uBB50\\uBB6C\\uBB88\\uBBA4\\uBBC0\\uBBDC\\uBBF8\\uBC14\\uBC30\\uBC4C\\uBC68\\uBC84\\uBCA0\\uBCBC\\uBCD8\\uBCF4\\uBD10\\uBD2C\\uBD48\\uBD64\\uBD80\\uBD9C\\uBDB8\\uBDD4\\uBDF0\\uBE0C\\uBE28\\uBE44\\uBE60\\uBE7C\\uBE98\\uBEB4\\uBED0\\uBEEC\\uBF08\\uBF24\\uBF40\\uBF5C\\uBF78\\uBF94\\uBFB0\\uBFCC\\uBFE8\\uC004\\uC020\\uC03C\\uC058\\uC074\\uC090\\uC0AC\\uC0C8\\uC0E4\\uC100\\uC11C\\uC138\\uC154\\uC170\\uC18C\\uC1A8\\uC1C4\\uC1E0\\uC1FC\\uC218\\uC234\\uC250\\uC26C\\uC288\\uC2A4\\uC2C0\\uC2DC\\uC2F8\\uC314\\uC330\\uC34C\\uC368\\uC384\\uC3A0\\uC3BC\\uC3D8\\uC3F4\\uC410\\uC42C\\uC448\\uC464\\uC480\\uC49C\\uC4B8\\uC4D4\\uC4F0\\uC50C\\uC528\\uC544\\uC560\\uC57C\\uC598\\uC5B4\\uC5D0\\uC5EC\\uC608\\uC624\\uC640\\uC65C\\uC678\\uC694\\uC6B0\\uC6CC\\uC6E8\\uC704\\uC720\\uC73C\\uC758\\uC774\\uC790\\uC7AC\\uC7C8\\uC7E4\\uC800\\uC81C\\uC838\\uC854\\uC870\\uC88C\\uC8A8\\uC8C4\\uC8E0\\uC8FC\\uC918\\uC934\\uC950\\uC96C\\uC988\\uC9A4\\uC9C0\\uC9DC\\uC9F8\\uCA14\\uCA30\\uCA4C\\uCA68\\uCA84\\uCAA0\\uCABC\\uCAD8\\uCAF4\\uCB10\\uCB2C\\uCB48\\uCB64\\uCB80\\uCB9C\\uCBB8\\uCBD4\\uCBF0\\uCC0C\\uCC28\\uCC44\\uCC60\\uCC7C\\uCC98\\uCCB4\\uCCD0\\uCCEC\\uCD08\\uCD24\\uCD40\\uCD5C\\uCD78\\uCD94\\uCDB0\\uCDCC\\uCDE8\\uCE04\\uCE20\\uCE3C\\uCE58\\uCE74\\uCE90\\uCEAC\\uCEC8\\uCEE4\\uCF00\\uCF1C\\uCF38\\uCF54\\uCF70\\uCF8C\\uCFA8\\uCFC4\\uCFE0\\uCFFC\\uD018\\uD034\\uD050\\uD06C\\uD088\\uD0A4\\uD0C0\\uD0DC\\uD0F8\\uD114\\uD130\\uD14C\\uD168\\uD184\\uD1A0\\uD1BC\\uD1D8\\uD1F4\\uD210\\uD22C\\uD248\\uD264\\uD280\\uD29C\\uD2B8\\uD2D4\\uD2F0\\uD30C\\uD328\\uD344\\uD360\\uD37C\\uD398\\uD3B4\\uD3D0\\uD3EC\\uD408\\uD424\\uD440\\uD45C\\uD478\\uD494\\uD4B0\\uD4CC\\uD4E8\\uD504\\uD520\\uD53C\\uD558\\uD574\\uD590\\uD5AC\\uD5C8\\uD5E4\\uD600\\uD61C\\uD638\\uD654\\uD670\\uD68C\\uD6A8\\uD6C4\\uD6E0\\uD6FC\\uD718\\uD734\\uD750\\uD76C\\uD788]$/u\nconst reLVT =\n /^[\\uAC01-\\uAC1B\\uAC1D-\\uAC37\\uAC39-\\uAC53\\uAC55-\\uAC6F\\uAC71-\\uAC8B\\uAC8D-\\uACA7\\uACA9-\\uACC3\\uACC5-\\uACDF\\uACE1-\\uACFB\\uACFD-\\uAD17\\uAD19-\\uAD33\\uAD35-\\uAD4F\\uAD51-\\uAD6B\\uAD6D-\\uAD87\\uAD89-\\uADA3\\uADA5-\\uADBF\\uADC1-\\uADDB\\uADDD-\\uADF7\\uADF9-\\uAE13\\uAE15-\\uAE2F\\uAE31-\\uAE4B\\uAE4D-\\uAE67\\uAE69-\\uAE83\\uAE85-\\uAE9F\\uAEA1-\\uAEBB\\uAEBD-\\uAED7\\uAED9-\\uAEF3\\uAEF5-\\uAF0F\\uAF11-\\uAF2B\\uAF2D-\\uAF47\\uAF49-\\uAF63\\uAF65-\\uAF7F\\uAF81-\\uAF9B\\uAF9D-\\uAFB7\\uAFB9-\\uAFD3\\uAFD5-\\uAFEF\\uAFF1-\\uB00B\\uB00D-\\uB027\\uB029-\\uB043\\uB045-\\uB05F\\uB061-\\uB07B\\uB07D-\\uB097\\uB099-\\uB0B3\\uB0B5-\\uB0CF\\uB0D1-\\uB0EB\\uB0ED-\\uB107\\uB109-\\uB123\\uB125-\\uB13F\\uB141-\\uB15B\\uB15D-\\uB177\\uB179-\\uB193\\uB195-\\uB1AF\\uB1B1-\\uB1CB\\uB1CD-\\uB1E7\\uB1E9-\\uB203\\uB205-\\uB21F\\uB221-\\uB23B\\uB23D-\\uB257\\uB259-\\uB273\\uB275-\\uB28F\\uB291-\\uB2AB\\uB2AD-\\uB2C7\\uB2C9-\\uB2E3\\uB2E5-\\uB2FF\\uB301-\\uB31B\\uB31D-\\uB337\\uB339-\\uB353\\uB355-\\uB36F\\uB371-\\uB38B\\uB38D-\\uB3A7\\uB3A9-\\uB3C3\\uB3C5-\\uB3DF\\uB3E1-\\uB3FB\\uB3FD-\\uB417\\uB419-\\uB433\\uB435-\\uB44F\\uB451-\\uB46B\\uB46D-\\uB487\\uB489-\\uB4A3\\uB4A5-\\uB4BF\\uB4C1-\\uB4DB\\uB4DD-\\uB4F7\\uB4F9-\\uB513\\uB515-\\uB52F\\uB531-\\uB54B\\uB54D-\\uB567\\uB569-\\uB583\\uB585-\\uB59F\\uB5A1-\\uB5BB\\uB5BD-\\uB5D7\\uB5D9-\\uB5F3\\uB5F5-\\uB60F\\uB611-\\uB62B\\uB62D-\\uB647\\uB649-\\uB663\\uB665-\\uB67F\\uB681-\\uB69B\\uB69D-\\uB6B7\\uB6B9-\\uB6D3\\uB6D5-\\uB6EF\\uB6F1-\\uB70B\\uB70D-\\uB727\\uB729-\\uB743\\uB745-\\uB75F\\uB761-\\uB77B\\uB77D-\\uB797\\uB799-\\uB7B3\\uB7B5-\\uB7CF\\uB7D1-\\uB7EB\\uB7ED-\\uB807\\uB809-\\uB823\\uB825-\\uB83F\\uB841-\\uB85B\\uB85D-\\uB877\\uB879-\\uB893\\uB895-\\uB8AF\\uB8B1-\\uB8CB\\uB8CD-\\uB8E7\\uB8E9-\\uB903\\uB905-\\uB91F\\uB921-\\uB93B\\uB93D-\\uB957\\uB959-\\uB973\\uB975-\\uB98F\\uB991-\\uB9AB\\uB9AD-\\uB9C7\\uB9C9-\\uB9E3\\uB9E5-\\uB9FF\\uBA01-\\uBA1B\\uBA1D-\\uBA37\\uBA39-\\uBA53\\uBA55-\\uBA6F\\uBA71-\\uBA8B\\uBA8D-\\uBAA7\\uBAA9-\\uBAC3\\uBAC5-\\uBADF\\uBAE1-\\uBAFB\\uBAFD-\\uBB17\\uBB19-\\uBB33\\uBB35-\\uBB4F\\uBB51-\\uBB6B\\uBB6D-\\uBB87\\uBB89-\\uBBA3\\uBBA5-\\uBBBF\\uBBC1-\\uBBDB\\uBBDD-\\uBBF7\\uBBF9-\\uBC13\\uBC15-\\uBC2F\\uBC31-\\uBC4B\\uBC4D-\\uBC67\\uBC69-\\uBC83\\uBC85-\\uBC9F\\uBCA1-\\uBCBB\\uBCBD-\\uBCD7\\uBCD9-\\uBCF3\\uBCF5-\\uBD0F\\uBD11-\\uBD2B\\uBD2D-\\uBD47\\uBD49-\\uBD63\\uBD65-\\uBD7F\\uBD81-\\uBD9B\\uBD9D-\\uBDB7\\uBDB9-\\uBDD3\\uBDD5-\\uBDEF\\uBDF1-\\uBE0B\\uBE0D-\\uBE27\\uBE29-\\uBE43\\uBE45-\\uBE5F\\uBE61-\\uBE7B\\uBE7D-\\uBE97\\uBE99-\\uBEB3\\uBEB5-\\uBECF\\uBED1-\\uBEEB\\uBEED-\\uBF07\\uBF09-\\uBF23\\uBF25-\\uBF3F\\uBF41-\\uBF5B\\uBF5D-\\uBF77\\uBF79-\\uBF93\\uBF95-\\uBFAF\\uBFB1-\\uBFCB\\uBFCD-\\uBFE7\\uBFE9-\\uC003\\uC005-\\uC01F\\uC021-\\uC03B\\uC03D-\\uC057\\uC059-\\uC073\\uC075-\\uC08F\\uC091-\\uC0AB\\uC0AD-\\uC0C7\\uC0C9-\\uC0E3\\uC0E5-\\uC0FF\\uC101-\\uC11B\\uC11D-\\uC137\\uC139-\\uC153\\uC155-\\uC16F\\uC171-\\uC18B\\uC18D-\\uC1A7\\uC1A9-\\uC1C3\\uC1C5-\\uC1DF\\uC1E1-\\uC1FB\\uC1FD-\\uC217\\uC219-\\uC233\\uC235-\\uC24F\\uC251-\\uC26B\\uC26D-\\uC287\\uC289-\\uC2A3\\uC2A5-\\uC2BF\\uC2C1-\\uC2DB\\uC2DD-\\uC2F7\\uC2F9-\\uC313\\uC315-\\uC32F\\uC331-\\uC34B\\uC34D-\\uC367\\uC369-\\uC383\\uC385-\\uC39F\\uC3A1-\\uC3BB\\uC3BD-\\uC3D7\\uC3D9-\\uC3F3\\uC3F5-\\uC40F\\uC411-\\uC42B\\uC42D-\\uC447\\uC449-\\uC463\\uC465-\\uC47F\\uC481-\\uC49B\\uC49D-\\uC4B7\\uC4B9-\\uC4D3\\uC4D5-\\uC4EF\\uC4F1-\\uC50B\\uC50D-\\uC527\\uC529-\\uC543\\uC545-\\uC55F\\uC561-\\uC57B\\uC57D-\\uC597\\uC599-\\uC5B3\\uC5B5-\\uC5CF\\uC5D1-\\uC5EB\\uC5ED-\\uC607\\uC609-\\uC623\\uC625-\\uC63F\\uC641-\\uC65B\\uC65D-\\uC677\\uC679-\\uC693\\uC695-\\uC6AF\\uC6B1-\\uC6CB\\uC6CD-\\uC6E7\\uC6E9-\\uC703\\uC705-\\uC71F\\uC721-\\uC73B\\uC73D-\\uC757\\uC759-\\uC773\\uC775-\\uC78F\\uC791-\\uC7AB\\uC7AD-\\uC7C7\\uC7C9-\\uC7E3\\uC7E5-\\uC7FF\\uC801-\\uC81B\\uC81D-\\uC837\\uC839-\\uC853\\uC855-\\uC86F\\uC871-\\uC88B\\uC88D-\\uC8A7\\uC8A9-\\uC8C3\\uC8C5-\\uC8DF\\uC8E1-\\uC8FB\\uC8FD-\\uC917\\uC919-\\uC933\\uC935-\\uC94F\\uC951-\\uC96B\\uC96D-\\uC987\\uC989-\\uC9A3\\uC9A5-\\uC9BF\\uC9C1-\\uC9DB\\uC9DD-\\uC9F7\\uC9F9-\\uCA13\\uCA15-\\uCA2F\\uCA31-\\uCA4B\\uCA4D-\\uCA67\\uCA69-\\uCA83\\uCA85-\\uCA9F\\uCAA1-\\uCABB\\uCABD-\\uCAD7\\uCAD9-\\uCAF3\\uCAF5-\\uCB0F\\uCB11-\\uCB2B\\uCB2D-\\uCB47\\uCB49-\\uCB63\\uCB65-\\uCB7F\\uCB81-\\uCB9B\\uCB9D-\\uCBB7\\uCBB9-\\uCBD3\\uCBD5-\\uCBEF\\uCBF1-\\uCC0B\\uCC0D-\\uCC27\\uCC29-\\uCC43\\uCC45-\\uCC5F\\uCC61-\\uCC7B\\uCC7D-\\uCC97\\uCC99-\\uCCB3\\uCCB5-\\uCCCF\\uCCD1-\\uCCEB\\uCCED-\\uCD07\\uCD09-\\uCD23\\uCD25-\\uCD3F\\uCD41-\\uCD5B\\uCD5D-\\uCD77\\uCD79-\\uCD93\\uCD95-\\uCDAF\\uCDB1-\\uCDCB\\uCDCD-\\uCDE7\\uCDE9-\\uCE03\\uCE05-\\uCE1F\\uCE21-\\uCE3B\\uCE3D-\\uCE57\\uCE59-\\uCE73\\uCE75-\\uCE8F\\uCE91-\\uCEAB\\uCEAD-\\uCEC7\\uCEC9-\\uCEE3\\uCEE5-\\uCEFF\\uCF01-\\uCF1B\\uCF1D-\\uCF37\\uCF39-\\uCF53\\uCF55-\\uCF6F\\uCF71-\\uCF8B\\uCF8D-\\uCFA7\\uCFA9-\\uCFC3\\uCFC5-\\uCFDF\\uCFE1-\\uCFFB\\uCFFD-\\uD017\\uD019-\\uD033\\uD035-\\uD04F\\uD051-\\uD06B\\uD06D-\\uD087\\uD089-\\uD0A3\\uD0A5-\\uD0BF\\uD0C1-\\uD0DB\\uD0DD-\\uD0F7\\uD0F9-\\uD113\\uD115-\\uD12F\\uD131-\\uD14B\\uD14D-\\uD167\\uD169-\\uD183\\uD185-\\uD19F\\uD1A1-\\uD1BB\\uD1BD-\\uD1D7\\uD1D9-\\uD1F3\\uD1F5-\\uD20F\\uD211-\\uD22B\\uD22D-\\uD247\\uD249-\\uD263\\uD265-\\uD27F\\uD281-\\uD29B\\uD29D-\\uD2B7\\uD2B9-\\uD2D3\\uD2D5-\\uD2EF\\uD2F1-\\uD30B\\uD30D-\\uD327\\uD329-\\uD343\\uD345-\\uD35F\\uD361-\\uD37B\\uD37D-\\uD397\\uD399-\\uD3B3\\uD3B5-\\uD3CF\\uD3D1-\\uD3EB\\uD3ED-\\uD407\\uD409-\\uD423\\uD425-\\uD43F\\uD441-\\uD45B\\uD45D-\\uD477\\uD479-\\uD493\\uD495-\\uD4AF\\uD4B1-\\uD4CB\\uD4CD-\\uD4E7\\uD4E9-\\uD503\\uD505-\\uD51F\\uD521-\\uD53B\\uD53D-\\uD557\\uD559-\\uD573\\uD575-\\uD58F\\uD591-\\uD5AB\\uD5AD-\\uD5C7\\uD5C9-\\uD5E3\\uD5E5-\\uD5FF\\uD601-\\uD61B\\uD61D-\\uD637\\uD639-\\uD653\\uD655-\\uD66F\\uD671-\\uD68B\\uD68D-\\uD6A7\\uD6A9-\\uD6C3\\uD6C5-\\uD6DF\\uD6E1-\\uD6FB\\uD6FD-\\uD717\\uD719-\\uD733\\uD735-\\uD74F\\uD751-\\uD76B\\uD76D-\\uD787\\uD789-\\uD7A3]$/u\nconst reExtPict = /^\\p{ExtPict}$/u\n\nconst getCodepointType = (char: string, code: number): CodepointType => {\n let type = CodepointType.Any\n if (char.search(reExtend) !== -1) {\n type |= CodepointType.Extend\n }\n if (code === 0x200d) {\n type |= CodepointType.ZWJ\n }\n if (code >= 0x1f1e6 && code <= 0x1f1ff) {\n type |= CodepointType.RI\n }\n if (char.search(rePrepend) !== -1) {\n type |= CodepointType.Prepend\n }\n if (char.search(reSpacingMark) !== -1) {\n type |= CodepointType.SpacingMark\n }\n if (char.search(reL) !== -1) {\n type |= CodepointType.L\n }\n if (char.search(reV) !== -1) {\n type |= CodepointType.V\n }\n if (char.search(reT) !== -1) {\n type |= CodepointType.T\n }\n if (char.search(reLV) !== -1) {\n type |= CodepointType.LV\n }\n if (char.search(reLVT) !== -1) {\n type |= CodepointType.LVT\n }\n if (char.search(reExtPict) !== -1) {\n type |= CodepointType.ExtPict\n }\n\n return type\n}\n\nfunction intersects(x: CodepointType, y: CodepointType) {\n return (x & y) !== 0\n}\n\nconst NonBoundaryPairs: [CodepointType, CodepointType][] = [\n // GB6\n [\n CodepointType.L,\n CodepointType.L | CodepointType.V | CodepointType.LV | CodepointType.LVT,\n ],\n // GB7\n [CodepointType.LV | CodepointType.V, CodepointType.V | CodepointType.T],\n // GB8\n [CodepointType.LVT | CodepointType.T, CodepointType.T],\n // GB9\n [CodepointType.Any, CodepointType.Extend | CodepointType.ZWJ],\n // GB9a\n [CodepointType.Any, CodepointType.SpacingMark],\n // GB9b\n [CodepointType.Prepend, CodepointType.Any],\n // GB11\n [CodepointType.ZWJ, CodepointType.ExtPict],\n // GB12 and GB13\n [CodepointType.RI, CodepointType.RI],\n]\n\nfunction isBoundaryPair(left: CodepointType, right: CodepointType) {\n return (\n NonBoundaryPairs.findIndex(\n r => intersects(left, r[0]) && intersects(right, r[1])\n ) === -1\n )\n}\n\nconst endingEmojiZWJ = /\\p{ExtPict}[\\p{Gr_Ext}\\p{EMod}]*\\u200D$/u\nconst endsWithEmojiZWJ = (str: string): boolean => {\n return str.search(endingEmojiZWJ) !== -1\n}\n\nconst endingRIs = /\\p{RI}+$/gu\nconst endsWithOddNumberOfRIs = (str: string): boolean => {\n const match = str.match(endingRIs)\n if (match === null) {\n return false\n } else {\n // A RI is represented by a surrogate pair.\n const numRIs = match[0].length / 2\n return numRIs % 2 === 1\n }\n}\n","import { Editor, Location, Node, Path, Range, Transforms } from '../../index'\nimport { TextUnit } from '../../types/types'\nimport { getDefaultInsertLocation } from '../../utils'\n\nexport interface TextDeleteOptions {\n at?: Location\n distance?: number\n unit?: TextUnit\n reverse?: boolean\n hanging?: boolean\n voids?: boolean\n}\n\nexport interface TextInsertFragmentOptions {\n at?: Location\n hanging?: boolean\n voids?: boolean\n batchDirty?: boolean\n}\n\nexport interface TextInsertTextOptions {\n at?: Location\n voids?: boolean\n}\n\nexport interface TextTransforms {\n /**\n * Delete content in the editor.\n */\n delete: (editor: Editor, options?: TextDeleteOptions) => void\n\n /**\n * Insert a fragment in the editor\n * at the specified location or (if not defined) the current selection or (if not defined) the end of the document.\n */\n insertFragment: (\n editor: Editor,\n fragment: Node[],\n options?: TextInsertFragmentOptions\n ) => void\n\n /**\n * Insert a string of text in the editor\n * at the specified location or (if not defined) the current selection or (if not defined) the end of the document.\n */\n insertText: (\n editor: Editor,\n text: string,\n options?: TextInsertTextOptions\n ) => void\n}\n\n// eslint-disable-next-line no-redeclare\nexport const TextTransforms: TextTransforms = {\n delete(editor, options) {\n editor.delete(options)\n },\n insertFragment(editor, fragment, options) {\n editor.insertFragment(fragment, options)\n },\n insertText(\n editor: Editor,\n text: string,\n options: TextInsertTextOptions = {}\n ): void {\n Editor.withoutNormalizing(editor, () => {\n const { voids = false } = options\n let { at = getDefaultInsertLocation(editor) } = options\n\n if (Path.isPath(at)) {\n at = Editor.range(editor, at)\n }\n\n if (Range.isRange(at)) {\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const end = Range.end(at)\n if (!voids && Editor.void(editor, { at: end })) {\n return\n }\n const start = Range.start(at)\n const startRef = Editor.pointRef(editor, start)\n const endRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at, voids })\n const startPoint = startRef.unref()\n const endPoint = endRef.unref()\n\n at = startPoint || endPoint!\n Transforms.setSelection(editor, { anchor: at, focus: at })\n }\n }\n\n if (\n (!voids && Editor.void(editor, { at })) ||\n Editor.elementReadOnly(editor, { at })\n ) {\n return\n }\n\n const { path, offset } = at\n if (text.length > 0)\n editor.apply({ type: 'insert_text', path, offset, text })\n })\n },\n}\n","import { GeneralTransforms } from './general'\nimport { NodeTransforms } from './node'\nimport { SelectionTransforms } from './selection'\nimport { TextTransforms } from './text'\n\nexport const Transforms: GeneralTransforms &\n NodeTransforms &\n SelectionTransforms &\n TextTransforms = {\n ...GeneralTransforms,\n ...NodeTransforms,\n ...SelectionTransforms,\n ...TextTransforms,\n}\n","// perf\n\nimport { Editor } from '../interfaces/editor'\n\nconst BATCHING_DIRTY_PATHS: WeakMap<Editor, boolean> = new WeakMap()\n\nexport const isBatchingDirtyPaths = (editor: Editor) => {\n return BATCHING_DIRTY_PATHS.get(editor) || false\n}\n\nexport const batchDirtyPaths = (\n editor: Editor,\n fn: () => void,\n update: () => void\n) => {\n const value = BATCHING_DIRTY_PATHS.get(editor) || false\n BATCHING_DIRTY_PATHS.set(editor, true)\n try {\n fn()\n update()\n } finally {\n BATCHING_DIRTY_PATHS.set(editor, value)\n }\n}\n","import { DIRTY_PATH_KEYS, DIRTY_PATHS } from '../utils/weak-maps'\nimport { Path } from '../interfaces/path'\nimport { Editor } from '../interfaces/editor'\n\n/**\n * update editor dirty paths\n *\n * @param newDirtyPaths: Path[]; new dirty paths\n * @param transform: (p: Path) => Path | null; how to transform existing dirty paths\n */\nexport function updateDirtyPaths(\n editor: Editor,\n newDirtyPaths: Path[],\n transform?: (p: Path) => Path | null\n) {\n const oldDirtyPaths = DIRTY_PATHS.get(editor) || []\n const oldDirtyPathKeys = DIRTY_PATH_KEYS.get(editor) || new Set()\n let dirtyPaths: Path[]\n let dirtyPathKeys: Set<string>\n\n const add = (path: Path | null) => {\n if (path) {\n const key = path.join(',')\n\n if (!dirtyPathKeys.has(key)) {\n dirtyPathKeys.add(key)\n dirtyPaths.push(path)\n }\n }\n }\n\n if (transform) {\n dirtyPaths = []\n dirtyPathKeys = new Set()\n for (const path of oldDirtyPaths) {\n const newPath = transform(path)\n add(newPath)\n }\n } else {\n dirtyPaths = oldDirtyPaths\n dirtyPathKeys = oldDirtyPathKeys\n }\n\n for (const path of newDirtyPaths) {\n add(path)\n }\n\n DIRTY_PATHS.set(editor, dirtyPaths)\n DIRTY_PATH_KEYS.set(editor, dirtyPathKeys)\n}\n","import { PathRef } from '../interfaces/path-ref'\nimport { PointRef } from '../interfaces/point-ref'\nimport { RangeRef } from '../interfaces/range-ref'\nimport { FLUSHING } from '../utils/weak-maps'\nimport { Path } from '../interfaces/path'\nimport { Transforms } from '../interfaces/transforms'\nimport { WithEditorFirstArg } from '../utils/types'\nimport { Editor } from '../interfaces/editor'\nimport { isBatchingDirtyPaths } from './batch-dirty-paths'\nimport { updateDirtyPaths } from './update-dirty-paths'\n\nexport const apply: WithEditorFirstArg<Editor['apply']> = (editor, op) => {\n for (const ref of Editor.pathRefs(editor)) {\n PathRef.transform(ref, op)\n }\n\n for (const ref of Editor.pointRefs(editor)) {\n PointRef.transform(ref, op)\n }\n\n for (const ref of Editor.rangeRefs(editor)) {\n RangeRef.transform(ref, op)\n }\n\n // update dirty paths\n if (!isBatchingDirtyPaths(editor)) {\n const transform = Path.operationCanTransformPath(op)\n ? (p: Path) => Path.transform(p, op)\n : undefined\n updateDirtyPaths(editor, editor.getDirtyPaths(op), transform)\n }\n\n Transforms.transform(editor, op)\n editor.operations.push(op)\n Editor.normalize(editor, {\n operation: op,\n })\n\n // Clear any formats applied to the cursor if the selection changes.\n if (op.type === 'set_selection') {\n editor.marks = null\n }\n\n if (!FLUSHING.get(editor)) {\n FLUSHING.set(editor, true)\n\n Promise.resolve().then(() => {\n FLUSHING.set(editor, false)\n editor.onChange({ operation: op })\n editor.operations = []\n })\n }\n}\n","import { WithEditorFirstArg } from '../utils/types'\nimport { Path } from '../interfaces/path'\nimport { Text } from '../interfaces/text'\nimport { Node } from '../interfaces/node'\nimport { Editor } from '../interfaces/editor'\n\n/**\n * Get the \"dirty\" paths generated from an operation.\n */\nexport const getDirtyPaths: WithEditorFirstArg<Editor['getDirtyPaths']> = (\n editor,\n op\n) => {\n switch (op.type) {\n case 'insert_text':\n case 'remove_text':\n case 'set_node': {\n const { path } = op\n return Path.levels(path)\n }\n\n case 'insert_node': {\n const { node, path } = op\n const levels = Path.levels(path)\n const descendants = Text.isText(node)\n ? []\n : Array.from(Node.nodes(node), ([, p]) => path.concat(p))\n\n return [...levels, ...descendants]\n }\n\n case 'merge_node': {\n const { path } = op\n const ancestors = Path.ancestors(path)\n const previousPath = Path.previous(path)\n return [...ancestors, previousPath]\n }\n\n case 'move_node': {\n const { path, newPath } = op\n\n if (Path.equals(path, newPath)) {\n return []\n }\n\n const oldAncestors: Path[] = []\n const newAncestors: Path[] = []\n\n for (const ancestor of Path.ancestors(path)) {\n const p = Path.transform(ancestor, op)\n oldAncestors.push(p!)\n }\n\n for (const ancestor of Path.ancestors(newPath)) {\n const p = Path.transform(ancestor, op)\n newAncestors.push(p!)\n }\n\n const newParent = newAncestors[newAncestors.length - 1]\n const newIndex = newPath[newPath.length - 1]\n const resultPath = newParent.concat(newIndex)\n\n return [...oldAncestors, ...newAncestors, resultPath]\n }\n\n case 'remove_node': {\n const { path } = op\n const ancestors = Path.ancestors(path)\n return [...ancestors]\n }\n\n case 'split_node': {\n const { path } = op\n const levels = Path.levels(path)\n const nextPath = Path.next(path)\n return [...levels, nextPath]\n }\n\n default: {\n return []\n }\n }\n}\n","import { Editor, Node } from '../interfaces'\nimport { WithEditorFirstArg } from '../utils'\n\nexport const getFragment: WithEditorFirstArg<\n Editor['getFragment']\n> = editor => {\n const { selection } = editor\n\n if (selection) {\n return Node.fragment(editor, selection)\n }\n return []\n}\n","import { WithEditorFirstArg } from '../utils/types'\nimport { Text } from '../interfaces/text'\nimport { Element } from '../interfaces/element'\nimport { Transforms } from '../interfaces/transforms'\nimport { Descendant, Node } from '../interfaces/node'\nimport { Editor } from '../interfaces/editor'\n\nexport const normalizeNode: WithEditorFirstArg<Editor['normalizeNode']> = (\n editor,\n entry,\n options\n) => {\n const [node, path] = entry\n\n // There are no core normalizations for text nodes.\n if (Text.isText(node)) {\n return\n }\n\n // Ensure that block and inline nodes have at least one text child.\n if (Element.isElement(node) && node.children.length === 0) {\n const child = { text: '' }\n Transforms.insertNodes(editor, child, {\n at: path.concat(0),\n voids: true,\n })\n return\n }\n\n // Determine whether the node should have block or inline children.\n const shouldHaveInlines = Editor.isEditor(node)\n ? false\n : Element.isElement(node) &&\n (editor.isInline(node) ||\n node.children.length === 0 ||\n Text.isText(node.children[0]) ||\n editor.isInline(node.children[0]))\n\n // Since we'll be applying operations while iterating, keep track of an\n // index that accounts for any added/removed nodes.\n let n = 0\n\n for (let i = 0; i < node.children.length; i++, n++) {\n const currentNode = Node.get(editor, path)\n if (Text.isText(currentNode)) continue\n const child = currentNode.children[n] as Descendant\n const prev = currentNode.children[n - 1] as Descendant\n const isLast = i === node.children.length - 1\n const isInlineOrText =\n Text.isText(child) || (Element.isElement(child) && editor.isInline(child))\n\n // Only allow block nodes in the top-level children and parent blocks\n // that only contain block nodes. Similarly, only allow inline nodes in\n // other inline nodes, or parent blocks that only contain inlines and\n // text.\n if (isInlineOrText !== shouldHaveInlines) {\n if (isInlineOrText) {\n if (options?.fallbackElement) {\n Transforms.wrapNodes(editor, options.fallbackElement(), {\n at: path.concat(n),\n voids: true,\n })\n } else {\n Transforms.removeNodes(editor, { at: path.concat(n), voids: true })\n }\n } else {\n Transforms.unwrapNodes(editor, { at: path.concat(n), voids: true })\n }\n n--\n } else if (Element.isElement(child)) {\n // Ensure that inline nodes are surrounded by text nodes.\n if (editor.isInline(child)) {\n if (prev == null || !Text.isText(prev)) {\n const newChild = { text: '' }\n Transforms.insertNodes(editor, newChild, {\n at: path.concat(n),\n voids: true,\n })\n n++\n } else if (isLast) {\n const newChild = { text: '' }\n Transforms.insertNodes(editor, newChild, {\n at: path.concat(n + 1),\n voids: true,\n })\n n++\n }\n }\n } else {\n // If the child is not a text node, and doesn't have a `children` field,\n // then we have an invalid node that will upset slate.\n //\n // eg: `{ type: 'some_node' }`.\n //\n // To prevent slate from breaking, we can add the `children` field,\n // and now that it is valid, we can to many more operations easily,\n // such as extend normalizers to fix erronous structure.\n if (!Text.isText(child) && !('children' in child)) {\n const elementChild = child as Element\n elementChild.children = []\n }\n\n // Merge adjacent text nodes that are empty or match.\n if (prev != null && Text.isText(prev)) {\n if (Text.equals(child, prev, { loose: true })) {\n Transforms.mergeNodes(editor, { at: path.concat(n), voids: true })\n n--\n } else if (prev.text === '') {\n Transforms.removeNodes(editor, {\n at: path.concat(n - 1),\n voids: true,\n })\n n--\n } else if (child.text === '') {\n Transforms.removeNodes(editor, {\n at: path.concat(n),\n voids: true,\n })\n n--\n }\n }\n }\n }\n}\n","import { WithEditorFirstArg } from '../utils/types'\nimport { Editor } from '../interfaces/editor'\n\nexport const shouldNormalize: WithEditorFirstArg<Editor['shouldNormalize']> = (\n editor,\n { iteration, initialDirtyPathsLength }\n) => {\n const maxIterations = initialDirtyPathsLength * 42 // HACK: better way?\n\n if (iteration > maxIterations) {\n throw new Error(\n `Could not completely normalize the editor after ${maxIterations} iterations! This is usually due to incorrect normalization logic that leaves a node in an invalid state.`\n )\n }\n\n return true\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Range } from '../interfaces'\nimport { Path } from '../interfaces/path'\n\nexport const above: EditorInterface['above'] = (editor, options = {}) => {\n const {\n voids = false,\n mode = 'lowest',\n at = editor.selection,\n match,\n } = options\n\n if (!at) {\n return\n }\n\n let path = Editor.path(editor, at)\n\n // If `at` is a Range that spans mulitple nodes, `path` will be their common ancestor.\n // Otherwise `path` will be a text node and/or the same as `at`, in which cases we want to start with its parent.\n if (!Range.isRange(at) || Path.equals(at.focus.path, at.anchor.path)) {\n if (path.length === 0) return\n path = Path.parent(path)\n }\n\n const reverse = mode === 'lowest'\n\n const [firstMatch] = Editor.levels(editor, {\n at: path,\n voids,\n match,\n reverse,\n })\n return firstMatch // if nothing matches this returns undefined\n}\n","import { Node } from '../interfaces/node'\nimport { Path } from '../interfaces/path'\nimport { Text } from '../interfaces/text'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { FLUSHING } from '../utils/weak-maps'\nimport { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const addMark: EditorInterface['addMark'] = (editor, key, value) => {\n const { selection } = editor\n\n if (selection) {\n const match = (node: Node, path: Path) => {\n if (!Text.isText(node)) {\n return false // marks can only be applied to text\n }\n const [parentNode, parentPath] = Editor.parent(editor, path)\n return !editor.isVoid(parentNode) || editor.markableVoid(parentNode)\n }\n const expandedSelection = Range.isExpanded(selection)\n let markAcceptingVoidSelected = false\n if (!expandedSelection) {\n const [selectedNode, selectedPath] = Editor.node(editor, selection)\n if (selectedNode && match(selectedNode, selectedPath)) {\n const [parentNode] = Editor.parent(editor, selectedPath)\n markAcceptingVoidSelected =\n parentNode && editor.markableVoid(parentNode)\n }\n }\n if (expandedSelection || markAcceptingVoidSelected) {\n Transforms.setNodes(\n editor,\n { [key]: value },\n {\n match,\n split: true,\n voids: true,\n }\n )\n } else {\n const marks = {\n ...(Editor.marks(editor) || {}),\n [key]: value,\n }\n\n editor.marks = marks\n if (!FLUSHING.get(editor)) {\n editor.onChange()\n }\n }\n }\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const after: EditorInterface['after'] = (editor, at, options = {}) => {\n const anchor = Editor.point(editor, at, { edge: 'end' })\n const focus = Editor.end(editor, [])\n const range = { anchor, focus }\n const { distance = 1 } = options\n let d = 0\n let target\n\n for (const p of Editor.positions(editor, {\n ...options,\n at: range,\n })) {\n if (d > distance) {\n break\n }\n\n if (d !== 0) {\n target = p\n }\n\n d++\n }\n\n return target\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const before: EditorInterface['before'] = (editor, at, options = {}) => {\n const anchor = Editor.start(editor, [])\n const focus = Editor.point(editor, at, { edge: 'start' })\n const range = { anchor, focus }\n const { distance = 1 } = options\n let d = 0\n let target\n\n for (const p of Editor.positions(editor, {\n ...options,\n at: range,\n reverse: true,\n })) {\n if (d > distance) {\n break\n }\n\n if (d !== 0) {\n target = p\n }\n\n d++\n }\n\n return target\n}\n","import { Editor } from '../interfaces/editor'\nimport { Transforms } from '../interfaces/transforms'\nimport { Range } from '../interfaces/range'\nimport { WithEditorFirstArg } from '../utils/types'\n\nexport const deleteBackward: WithEditorFirstArg<Editor['deleteBackward']> = (\n editor,\n unit\n) => {\n const { selection } = editor\n\n if (selection && Range.isCollapsed(selection)) {\n Transforms.delete(editor, { unit, reverse: true })\n }\n}\n","import { Editor } from '../interfaces/editor'\nimport { Transforms } from '../interfaces/transforms'\nimport { Range } from '../interfaces/range'\nimport { WithEditorFirstArg } from '../utils/types'\n\nexport const deleteForward: WithEditorFirstArg<Editor['deleteForward']> = (\n editor,\n unit\n) => {\n const { selection } = editor\n\n if (selection && Range.isCollapsed(selection)) {\n Transforms.delete(editor, { unit })\n }\n}\n","import { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { EditorInterface } from '../interfaces/editor'\n\nexport const deleteFragment: EditorInterface['deleteFragment'] = (\n editor,\n { direction = 'forward' } = {}\n) => {\n const { selection } = editor\n\n if (selection && Range.isExpanded(selection)) {\n Transforms.delete(editor, { reverse: direction === 'backward' })\n }\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const edges: EditorInterface['edges'] = (editor, at) => {\n return [Editor.start(editor, at), Editor.end(editor, at)]\n}\n","import { Element } from '../interfaces/element'\nimport { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const elementReadOnly: EditorInterface['elementReadOnly'] = (\n editor,\n options = {}\n) => {\n return Editor.above(editor, {\n ...options,\n match: n => Element.isElement(n) && Editor.isElementReadOnly(editor, n),\n })\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const end: EditorInterface['end'] = (editor, at) => {\n return Editor.point(editor, at, { edge: 'end' })\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const first: EditorInterface['first'] = (editor, at) => {\n const path = Editor.path(editor, at, { edge: 'start' })\n return Editor.node(editor, path)\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Node } from '../interfaces/node'\n\nexport const fragment: EditorInterface['fragment'] = (editor, at) => {\n const range = Editor.range(editor, at)\n return Node.fragment(editor, range)\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Element } from '../interfaces/element'\n\nexport const getVoid: EditorInterface['void'] = (editor, options = {}) => {\n return Editor.above(editor, {\n ...options,\n match: n => Element.isElement(n) && Editor.isVoid(editor, n),\n })\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Element } from '../interfaces/element'\n\nexport const hasBlocks: EditorInterface['hasBlocks'] = (editor, element) => {\n return element.children.some(\n n => Element.isElement(n) && Editor.isBlock(editor, n)\n )\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Text } from '../interfaces/text'\n\nexport const hasInlines: EditorInterface['hasInlines'] = (editor, element) => {\n return element.children.some(\n n => Text.isText(n) || Editor.isInline(editor, n)\n )\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { Node } from '../interfaces/node'\n\nexport const hasPath: EditorInterface['hasPath'] = (editor, path) => {\n return Node.has(editor, path)\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { Text } from '../interfaces/text'\n\nexport const hasTexts: EditorInterface['hasTexts'] = (editor, element) => {\n return element.children.every(n => Text.isText(n))\n}\n","import { Transforms } from '../interfaces/transforms'\nimport { EditorInterface } from '../interfaces/editor'\n\nexport const insertBreak: EditorInterface['insertBreak'] = editor => {\n Transforms.splitNodes(editor, { always: true })\n}\n","import { Transforms } from '../interfaces/transforms'\nimport { EditorInterface } from '../interfaces/editor'\n\nexport const insertNode: EditorInterface['insertNode'] = (\n editor,\n node,\n options\n) => {\n Transforms.insertNodes(editor, node, options)\n}\n","import { Transforms } from '../interfaces/transforms'\nimport { EditorInterface } from '../interfaces/editor'\n\nexport const insertSoftBreak: EditorInterface['insertSoftBreak'] = editor => {\n Transforms.splitNodes(editor, { always: true })\n}\n","import { Transforms } from '../interfaces/transforms'\nimport { EditorInterface } from '../interfaces/editor'\n\nexport const insertText: EditorInterface['insertText'] = (\n editor,\n text,\n options = {}\n) => {\n const { selection, marks } = editor\n\n if (selection) {\n if (marks) {\n const node = { text, ...marks }\n Transforms.insertNodes(editor, node, {\n at: options.at,\n voids: options.voids,\n })\n } else {\n Transforms.insertText(editor, text, options)\n }\n\n editor.marks = null\n }\n}\n","import { EditorInterface } from '../interfaces/editor'\n\nexport const isBlock: EditorInterface['isBlock'] = (editor, value) => {\n return !editor.isInline(value)\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const isEdge: EditorInterface['isEdge'] = (editor, point, at) => {\n return Editor.isStart(editor, point, at) || Editor.isEnd(editor, point, at)\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { Text } from '../interfaces/text'\n\nexport const isEmpty: EditorInterface['isEmpty'] = (editor, element) => {\n const { children } = element\n const [first] = children\n return (\n children.length === 0 ||\n (children.length === 1 &&\n Text.isText(first) &&\n first.text === '' &&\n !editor.isVoid(element))\n )\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Point } from '../interfaces/point'\n\nexport const isEnd: EditorInterface['isEnd'] = (editor, point, at) => {\n const end = Editor.end(editor, at)\n return Point.equals(point, end)\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { NORMALIZING } from '../utils/weak-maps'\n\nexport const isNormalizing: EditorInterface['isNormalizing'] = editor => {\n const isNormalizing = NORMALIZING.get(editor)\n return isNormalizing === undefined ? true : isNormalizing\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Point } from '../interfaces/point'\n\nexport const isStart: EditorInterface['isStart'] = (editor, point, at) => {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false\n }\n\n const start = Editor.start(editor, at)\n return Point.equals(point, start)\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const last: EditorInterface['last'] = (editor, at) => {\n const path = Editor.path(editor, at, { edge: 'end' })\n return Editor.node(editor, path)\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Node } from '../interfaces/node'\n\nexport const leaf: EditorInterface['leaf'] = (editor, at, options = {}) => {\n const path = Editor.path(editor, at, options)\n const node = Node.leaf(editor, path)\n return [node, path]\n}\n","import { Node, NodeEntry } from '../interfaces/node'\nimport { Editor, EditorLevelsOptions } from '../interfaces/editor'\nimport { Element } from '../interfaces/element'\n\nexport function* levels<T extends Node>(\n editor: Editor,\n options: EditorLevelsOptions<T> = {}\n): Generator<NodeEntry<T>, void, undefined> {\n const { at = editor.selection, reverse = false, voids = false } = options\n let { match } = options\n\n if (match == null) {\n match = () => true\n }\n\n if (!at) {\n return\n }\n\n const levels: NodeEntry<T>[] = []\n const path = Editor.path(editor, at)\n\n for (const [n, p] of Node.levels(editor, path)) {\n if (!match(n, p)) {\n continue\n }\n\n levels.push([n, p] as NodeEntry<T>)\n\n if (!voids && Element.isElement(n) && Editor.isVoid(editor, n)) {\n break\n }\n }\n\n if (reverse) {\n levels.reverse()\n }\n\n yield* levels\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { NodeEntry } from '../interfaces/node'\nimport { Range } from '../interfaces/range'\nimport { Path } from '../interfaces/path'\nimport { Text } from '../interfaces/text'\nimport { Element } from '../interfaces/element'\nimport { Point } from '../interfaces'\n\nexport const marks: EditorInterface['marks'] = (editor, options = {}) => {\n const { marks, selection } = editor\n\n if (!selection) {\n return null\n }\n let { anchor, focus } = selection\n\n if (marks) {\n return marks\n }\n\n if (Range.isExpanded(selection)) {\n const isBackward = Range.isBackward(selection)\n if (isBackward) {\n ;[focus, anchor] = [anchor, focus]\n }\n /**\n * COMPAT: Make sure hanging ranges (caused by double clicking in Firefox)\n * do not adversely affect the returned marks.\n */\n const isEnd = Editor.isEnd(editor, anchor, anchor.path)\n if (isEnd) {\n const after = Editor.after(editor, anchor as Point)\n if (after) {\n anchor = after\n }\n }\n\n const [match] = Editor.nodes(editor, {\n match: Text.isText,\n at: {\n anchor,\n focus,\n },\n })\n\n if (match) {\n const [node] = match as NodeEntry<Text>\n const { text, ...rest } = node\n return rest\n } else {\n return {}\n }\n }\n\n const { path } = anchor\n\n let [node] = Editor.leaf(editor, path)\n\n if (anchor.offset === 0) {\n const prev = Editor.previous(editor, { at: path, match: Text.isText })\n const markedVoid = Editor.above(editor, {\n match: n =>\n Element.isElement(n) &&\n Editor.isVoid(editor, n) &&\n editor.markableVoid(n),\n })\n if (!markedVoid) {\n const block = Editor.above(editor, {\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n })\n\n if (prev && block) {\n const [prevNode, prevPath] = prev\n const [, blockPath] = block\n\n if (Path.isAncestor(blockPath, prevPath)) {\n node = prevNode as Text\n }\n }\n }\n }\n\n const { text, ...rest } = node\n return rest\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Span } from '../interfaces/location'\nimport { Path } from '../interfaces/path'\n\nexport const next: EditorInterface['next'] = (editor, options = {}) => {\n const { mode = 'lowest', voids = false } = options\n let { match, at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n const pointAfterLocation = Editor.after(editor, at, { voids })\n\n if (!pointAfterLocation) return\n\n const [, to] = Editor.last(editor, [])\n\n const span: Span = [pointAfterLocation.path, to]\n\n if (Path.isPath(at) && at.length === 0) {\n throw new Error(`Cannot get the next node from the root node!`)\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n const [parent] = Editor.parent(editor, at)\n match = n => parent.children.includes(n)\n } else {\n match = () => true\n }\n }\n\n const [next] = Editor.nodes(editor, { at: span, match, mode, voids })\n return next\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Node } from '../interfaces/node'\n\nexport const node: EditorInterface['node'] = (editor, at, options = {}) => {\n const path = Editor.path(editor, at, options)\n const node = Node.get(editor, path)\n return [node, path]\n}\n","import { Node, NodeEntry } from '../interfaces/node'\nimport { Editor, EditorNodesOptions } from '../interfaces/editor'\nimport { Span } from '../interfaces/location'\nimport { Element } from '../interfaces/element'\nimport { Path } from '../interfaces/path'\nimport { Text } from '../interfaces/text'\n\nexport function* nodes<T extends Node>(\n editor: Editor,\n options: EditorNodesOptions<T> = {}\n): Generator<NodeEntry<T>, void, undefined> {\n const {\n at = editor.selection,\n mode = 'all',\n universal = false,\n reverse = false,\n voids = false,\n pass,\n } = options\n let { match } = options\n\n if (!match) {\n match = () => true\n }\n\n if (!at) {\n return\n }\n\n let from\n let to\n\n if (Span.isSpan(at)) {\n from = at[0]\n to = at[1]\n } else {\n const first = Editor.path(editor, at, { edge: 'start' })\n const last = Editor.path(editor, at, { edge: 'end' })\n from = reverse ? last : first\n to = reverse ? first : last\n }\n\n const nodeEntries = Node.nodes(editor, {\n reverse,\n from,\n to,\n pass: ([node, path]) => {\n if (pass && pass([node, path])) return true\n if (!Element.isElement(node)) return false\n if (\n !voids &&\n (Editor.isVoid(editor, node) || Editor.isElementReadOnly(editor, node))\n )\n return true\n\n return false\n },\n })\n\n const matches: NodeEntry<T>[] = []\n let hit: NodeEntry<T> | undefined\n\n for (const [node, path] of nodeEntries) {\n const isLower = hit && Path.compare(path, hit[1]) === 0\n\n // In highest mode any node lower than the last hit is not a match.\n if (mode === 'highest' && isLower) {\n continue\n }\n\n if (!match(node, path)) {\n // If we've arrived at a leaf text node that is not lower than the last\n // hit, then we've found a branch that doesn't include a match, which\n // means the match is not universal.\n if (universal && !isLower && Text.isText(node)) {\n return\n } else {\n continue\n }\n }\n\n // If there's a match and it's lower than the last, update the hit.\n if (mode === 'lowest' && isLower) {\n hit = [node, path] as NodeEntry<T>\n continue\n }\n\n // In lowest mode we emit the last hit, once it's guaranteed lowest.\n const emit: NodeEntry<T> | undefined =\n mode === 'lowest' ? hit : ([node, path] as NodeEntry<T>)\n\n if (emit) {\n if (universal) {\n matches.push(emit)\n } else {\n yield emit\n }\n }\n\n hit = [node, path] as NodeEntry<T>\n }\n\n // Since lowest is always emitting one behind, catch up at the end.\n if (mode === 'lowest' && hit) {\n if (universal) {\n matches.push(hit)\n } else {\n yield hit\n }\n }\n\n // Universal defers to ensure that the match occurs in every branch, so we\n // yield all of the matches after iterating.\n if (universal) {\n yield* matches\n }\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { DIRTY_PATH_KEYS, DIRTY_PATHS } from '../utils/weak-maps'\nimport { Path } from '../interfaces/path'\nimport { Node } from '../interfaces/node'\nimport { Element } from '../interfaces/element'\n\nexport const normalize: EditorInterface['normalize'] = (\n editor,\n options = {}\n) => {\n const { force = false, operation } = options\n const getDirtyPaths = (editor: Editor) => {\n return DIRTY_PATHS.get(editor) || []\n }\n\n const getDirtyPathKeys = (editor: Editor) => {\n return DIRTY_PATH_KEYS.get(editor) || new Set()\n }\n\n const popDirtyPath = (editor: Editor): Path => {\n const path = getDirtyPaths(editor).pop()!\n const key = path.join(',')\n getDirtyPathKeys(editor).delete(key)\n return path\n }\n\n if (!Editor.isNormalizing(editor)) {\n return\n }\n\n if (force) {\n const allPaths = Array.from(Node.nodes(editor), ([, p]) => p)\n const allPathKeys = new Set(allPaths.map(p => p.join(',')))\n DIRTY_PATHS.set(editor, allPaths)\n DIRTY_PATH_KEYS.set(editor, allPathKeys)\n }\n\n if (getDirtyPaths(editor).length === 0) {\n return\n }\n\n Editor.withoutNormalizing(editor, () => {\n /*\n Fix dirty elements with no children.\n editor.normalizeNode() does fix this, but some normalization fixes also require it to work.\n Running an initial pass avoids the catch-22 race condition.\n */\n for (const dirtyPath of getDirtyPaths(editor)) {\n if (Node.has(editor, dirtyPath)) {\n const entry = Editor.node(editor, dirtyPath)\n const [node, _] = entry\n\n /*\n The default normalizer inserts an empty text node in this scenario, but it can be customised.\n So there is some risk here.\n\n As long as the normalizer only inserts child nodes for this case it is safe to do in any order;\n by definition adding children to an empty node can't cause other paths to change.\n */\n if (Element.isElement(node) && node.children.length === 0) {\n editor.normalizeNode(entry, { operation })\n }\n }\n }\n\n let dirtyPaths = getDirtyPaths(editor)\n const initialDirtyPathsLength = dirtyPaths.length\n let iteration = 0\n\n while (dirtyPaths.length !== 0) {\n if (\n !editor.shouldNormalize({\n dirtyPaths,\n iteration,\n initialDirtyPathsLength,\n operation,\n })\n ) {\n return\n }\n\n const dirtyPath = popDirtyPath(editor)\n\n // If the node doesn't exist in the tree, it does not need to be normalized.\n if (Node.has(editor, dirtyPath)) {\n const entry = Editor.node(editor, dirtyPath)\n editor.normalizeNode(entry, { operation })\n }\n iteration++\n dirtyPaths = getDirtyPaths(editor)\n }\n })\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { Ancestor, NodeEntry } from '../interfaces/node'\n\nexport const parent: EditorInterface['parent'] = (editor, at, options = {}) => {\n const path = Editor.path(editor, at, options)\n const parentPath = Path.parent(path)\n const entry = Editor.node(editor, parentPath)\n return entry as NodeEntry<Ancestor>\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { PathRef } from '../interfaces/path-ref'\n\nexport const pathRef: EditorInterface['pathRef'] = (\n editor,\n path,\n options = {}\n) => {\n const { affinity = 'forward' } = options\n const ref: PathRef = {\n current: path,\n affinity,\n unref() {\n const { current } = ref\n const pathRefs = Editor.pathRefs(editor)\n pathRefs.delete(ref)\n ref.current = null\n return current\n },\n }\n\n const refs = Editor.pathRefs(editor)\n refs.add(ref)\n return ref\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { PATH_REFS } from '../utils/weak-maps'\n\nexport const pathRefs: EditorInterface['pathRefs'] = editor => {\n let refs = PATH_REFS.get(editor)\n\n if (!refs) {\n refs = new Set()\n PATH_REFS.set(editor, refs)\n }\n\n return refs\n}\n","import { EditorInterface, Node, Path, Point, Range } from '../interfaces'\n\nexport const path: EditorInterface['path'] = (editor, at, options = {}) => {\n const { depth, edge } = options\n\n if (Path.isPath(at)) {\n if (edge === 'start') {\n const [, firstPath] = Node.first(editor, at)\n at = firstPath\n } else if (edge === 'end') {\n const [, lastPath] = Node.last(editor, at)\n at = lastPath\n }\n }\n\n if (Range.isRange(at)) {\n if (edge === 'start') {\n at = Range.start(at)\n } else if (edge === 'end') {\n at = Range.end(at)\n } else {\n at = Path.common(at.anchor.path, at.focus.path)\n }\n }\n\n if (Point.isPoint(at)) {\n at = at.path\n }\n\n if (depth != null) {\n at = at.slice(0, depth)\n }\n\n return at\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { PointRef } from '../interfaces/point-ref'\n\nexport const pointRef: EditorInterface['pointRef'] = (\n editor,\n point,\n options = {}\n) => {\n const { affinity = 'forward' } = options\n const ref: PointRef = {\n current: point,\n affinity,\n unref() {\n const { current } = ref\n const pointRefs = Editor.pointRefs(editor)\n pointRefs.delete(ref)\n ref.current = null\n return current\n },\n }\n\n const refs = Editor.pointRefs(editor)\n refs.add(ref)\n return ref\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { POINT_REFS } from '../utils/weak-maps'\n\nexport const pointRefs: EditorInterface['pointRefs'] = editor => {\n let refs = POINT_REFS.get(editor)\n\n if (!refs) {\n refs = new Set()\n POINT_REFS.set(editor, refs)\n }\n\n return refs\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { Node } from '../interfaces/node'\nimport { Text } from '../interfaces/text'\nimport { Range } from '../interfaces/range'\n\nexport const point: EditorInterface['point'] = (editor, at, options = {}) => {\n const { edge = 'start' } = options\n\n if (Path.isPath(at)) {\n let path\n\n if (edge === 'end') {\n const [, lastPath] = Node.last(editor, at)\n path = lastPath\n } else {\n const [, firstPath] = Node.first(editor, at)\n path = firstPath\n }\n\n const node = Node.get(editor, path)\n\n if (!Text.isText(node)) {\n throw new Error(\n `Cannot get the ${edge} point in the node at path [${at}] because it has no ${edge} text node.`\n )\n }\n\n return { path, offset: edge === 'end' ? node.text.length : 0 }\n }\n\n if (Range.isRange(at)) {\n const [start, end] = Range.edges(at)\n return edge === 'start' ? start : end\n }\n\n return at\n}\n","import { Editor, EditorPositionsOptions } from '../interfaces/editor'\nimport { Point } from '../interfaces/point'\nimport { Range } from '../interfaces/range'\nimport { Element } from '../interfaces/element'\nimport { Path } from '../interfaces/path'\nimport { Text } from '../interfaces/text'\nimport {\n getCharacterDistance,\n getWordDistance,\n splitByCharacterDistance,\n} from '../utils/string'\n\nexport function* positions(\n editor: Editor,\n options: EditorPositionsOptions = {}\n): Generator<Point, void, undefined> {\n const {\n at = editor.selection,\n unit = 'offset',\n reverse = false,\n voids = false,\n } = options\n\n if (!at) {\n return\n }\n\n /**\n * Algorithm notes:\n *\n * Each step `distance` is dynamic depending on the underlying text\n * and the `unit` specified. Each step, e.g., a line or word, may\n * span multiple text nodes, so we iterate through the text both on\n * two levels in step-sync:\n *\n * `leafText` stores the text on a text leaf level, and is advanced\n * through using the counters `leafTextOffset` and `leafTextRemaining`.\n *\n * `blockText` stores the text on a block level, and is shortened\n * by `distance` every time it is advanced.\n *\n * We only maintain a window of one blockText and one leafText because\n * a block node always appears before all of its leaf nodes.\n */\n\n const range = Editor.range(editor, at)\n const [start, end] = Range.edges(range)\n const first = reverse ? end : start\n let isNewBlock = false\n let blockText = ''\n let distance = 0 // Distance for leafText to catch up to blockText.\n let leafTextRemaining = 0\n let leafTextOffset = 0\n const skippedPaths: Path[] = []\n\n // Iterate through all nodes in range, grabbing entire textual content\n // of block nodes in blockText, and text nodes in leafText.\n // Exploits the fact that nodes are sequenced in such a way that we first\n // encounter the block node, then all of its text nodes, so when iterating\n // through the blockText and leafText we just need to remember a window of\n // one block node and leaf node, respectively.\n for (const [node, path] of Editor.nodes(editor, {\n at,\n reverse,\n voids,\n })) {\n // If the node is inside a skipped ancestor, do not return any points, but\n // still process its content so that the iteration state remains correct.\n const hasSkippedAncestor = skippedPaths.some(p => Path.isAncestor(p, path))\n\n function* maybeYield(point: Point) {\n if (!hasSkippedAncestor) {\n yield point\n }\n }\n\n /*\n * ELEMENT NODE - Yield position(s) for voids, collect blockText for blocks\n */\n if (Element.isElement(node)) {\n if (!editor.isSelectable(node)) {\n /**\n * If the node is not selectable, skip it and its descendants\n */\n skippedPaths.push(path)\n if (reverse) {\n if (Path.hasPrevious(path)) {\n yield* maybeYield(Editor.end(editor, Path.previous(path)))\n }\n continue\n } else {\n const nextPath = Path.next(path)\n if (Editor.hasPath(editor, nextPath)) {\n yield* maybeYield(Editor.start(editor, nextPath))\n }\n continue\n }\n }\n\n // Void nodes are a special case, so by default we will always\n // yield their first point. If the `voids` option is set to true,\n // then we will iterate over their content.\n if (!voids && (editor.isVoid(node) || editor.isElementReadOnly(node))) {\n yield* maybeYield(Editor.start(editor, path))\n continue\n }\n\n // Inline element nodes are ignored as they don't themselves\n // contribute to `blockText` or `leafText` - their parent and\n // children do.\n if (editor.isInline(node)) continue\n\n // Block element node - set `blockText` to its text content.\n if (Editor.hasInlines(editor, node)) {\n // We always exhaust block nodes before encountering a new one:\n // console.assert(blockText === '',\n // `blockText='${blockText}' - `+\n // `not exhausted before new block node`, path)\n\n // Ensure range considered is capped to `range`, in the\n // start/end edge cases where block extends beyond range.\n // Equivalent to this, but presumably more performant:\n // blockRange = Editor.range(editor, ...Editor.edges(editor, path))\n // blockRange = Range.intersection(range, blockRange) // intersect\n // blockText = Editor.string(editor, blockRange, { voids })\n const e = Path.isAncestor(path, end.path)\n ? end\n : Editor.end(editor, path)\n const s = Path.isAncestor(path, start.path)\n ? start\n : Editor.start(editor, path)\n\n blockText = Editor.string(editor, { anchor: s, focus: e }, { voids })\n isNewBlock = true\n }\n }\n\n /*\n * TEXT LEAF NODE - Iterate through text content, yielding\n * positions every `distance` offset according to `unit`.\n */\n if (Text.isText(node)) {\n const isFirst = Path.equals(path, first.path)\n\n // Proof that we always exhaust text nodes before encountering a new one:\n // console.assert(leafTextRemaining <= 0,\n // `leafTextRemaining=${leafTextRemaining} - `+\n // `not exhausted before new leaf text node`, path)\n\n // Reset `leafText` counters for new text node.\n if (isFirst) {\n leafTextRemaining = reverse\n ? first.offset\n : node.text.length - first.offset\n leafTextOffset = first.offset // Works for reverse too.\n } else {\n leafTextRemaining = node.text.length\n leafTextOffset = reverse ? leafTextRemaining : 0\n }\n\n // Yield position at the start of node (potentially).\n if (isFirst || isNewBlock || unit === 'offset') {\n yield* maybeYield({ path, offset: leafTextOffset })\n isNewBlock = false\n }\n\n // Yield positions every (dynamically calculated) `distance` offset.\n while (true) {\n // If `leafText` has caught up with `blockText` (distance=0),\n // and if blockText is exhausted, break to get another block node,\n // otherwise advance blockText forward by the new `distance`.\n if (distance === 0) {\n if (blockText === '') break\n distance = calcDistance(blockText, unit, reverse)\n // Split the string at the previously found distance and use the\n // remaining string for the next iteration.\n blockText = splitByCharacterDistance(blockText, distance, reverse)[1]\n }\n\n // Advance `leafText` by the current `distance`.\n leafTextOffset = reverse\n ? leafTextOffset - distance\n : leafTextOffset + distance\n leafTextRemaining = leafTextRemaining - distance\n\n // If `leafText` is exhausted, break to get a new leaf node\n // and set distance to the overflow amount, so we'll (maybe)\n // catch up to blockText in the next leaf text node.\n if (leafTextRemaining < 0) {\n distance = -leafTextRemaining\n break\n }\n\n // Successfully walked `distance` offsets through `leafText`\n // to catch up with `blockText`, so we can reset `distance`\n // and yield this position in this node.\n distance = 0\n yield* maybeYield({ path, offset: leafTextOffset })\n }\n }\n }\n // Proof that upon completion, we've exahusted both leaf and block text:\n // console.assert(leafTextRemaining <= 0, \"leafText wasn't exhausted\")\n // console.assert(blockText === '', \"blockText wasn't exhausted\")\n\n // Helper:\n // Return the distance in offsets for a step of size `unit` on given string.\n function calcDistance(text: string, unit: string, reverse?: boolean) {\n if (unit === 'character') {\n return getCharacterDistance(text, reverse)\n } else if (unit === 'word') {\n return getWordDistance(text, reverse)\n } else if (unit === 'line' || unit === 'block') {\n return text.length\n }\n return 1\n }\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Span } from '../interfaces/location'\nimport { Path } from '../interfaces/path'\n\nexport const previous: EditorInterface['previous'] = (editor, options = {}) => {\n const { mode = 'lowest', voids = false } = options\n let { match, at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n const pointBeforeLocation = Editor.before(editor, at, { voids })\n\n if (!pointBeforeLocation) {\n return\n }\n\n const [, to] = Editor.first(editor, [])\n\n // The search location is from the start of the document to the path of\n // the point before the location passed in\n const span: Span = [pointBeforeLocation.path, to]\n\n if (Path.isPath(at) && at.length === 0) {\n throw new Error(`Cannot get the previous node from the root node!`)\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n const [parent] = Editor.parent(editor, at)\n match = n => parent.children.includes(n)\n } else {\n match = () => true\n }\n }\n\n const [previous] = Editor.nodes(editor, {\n reverse: true,\n at: span,\n match,\n mode,\n voids,\n })\n\n return previous\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { RangeRef } from '../interfaces/range-ref'\n\nexport const rangeRef: EditorInterface['rangeRef'] = (\n editor,\n range,\n options = {}\n) => {\n const { affinity = 'forward' } = options\n const ref: RangeRef = {\n current: range,\n affinity,\n unref() {\n const { current } = ref\n const rangeRefs = Editor.rangeRefs(editor)\n rangeRefs.delete(ref)\n ref.current = null\n return current\n },\n }\n\n const refs = Editor.rangeRefs(editor)\n refs.add(ref)\n return ref\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { RANGE_REFS } from '../utils/weak-maps'\n\nexport const rangeRefs: EditorInterface['rangeRefs'] = editor => {\n let refs = RANGE_REFS.get(editor)\n\n if (!refs) {\n refs = new Set()\n RANGE_REFS.set(editor, refs)\n }\n\n return refs\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Range } from '../interfaces/range'\n\nexport const range: EditorInterface['range'] = (editor, at, to) => {\n if (Range.isRange(at) && !to) {\n return at\n }\n\n const start = Editor.start(editor, at)\n const end = Editor.end(editor, to || at)\n return { anchor: start, focus: end }\n}\n","import { Node } from '../interfaces/node'\nimport { Path } from '../interfaces/path'\nimport { Text } from '../interfaces/text'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { FLUSHING } from '../utils/weak-maps'\nimport { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const removeMark: EditorInterface['removeMark'] = (editor, key) => {\n const { selection } = editor\n\n if (selection) {\n const match = (node: Node, path: Path) => {\n if (!Text.isText(node)) {\n return false // marks can only be applied to text\n }\n const [parentNode, parentPath] = Editor.parent(editor, path)\n return !editor.isVoid(parentNode) || editor.markableVoid(parentNode)\n }\n const expandedSelection = Range.isExpanded(selection)\n let markAcceptingVoidSelected = false\n if (!expandedSelection) {\n const [selectedNode, selectedPath] = Editor.node(editor, selection)\n if (selectedNode && match(selectedNode, selectedPath)) {\n const [parentNode] = Editor.parent(editor, selectedPath)\n markAcceptingVoidSelected =\n parentNode && editor.markableVoid(parentNode)\n }\n }\n if (expandedSelection || markAcceptingVoidSelected) {\n Transforms.unsetNodes(editor, key, {\n match,\n split: true,\n voids: true,\n })\n } else {\n const marks = { ...(Editor.marks(editor) || {}) }\n delete marks[<keyof Node>key]\n editor.marks = marks\n if (!FLUSHING.get(editor)) {\n editor.onChange()\n }\n }\n }\n}\n","import { EditorInterface } from '../interfaces/editor'\nimport { NORMALIZING } from '../utils/weak-maps'\n\nexport const setNormalizing: EditorInterface['setNormalizing'] = (\n editor,\n isNormalizing\n) => {\n NORMALIZING.set(editor, isNormalizing)\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const start: EditorInterface['start'] = (editor, at) => {\n return Editor.point(editor, at, { edge: 'start' })\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Range } from '../interfaces/range'\nimport { Text } from '../interfaces/text'\nimport { Path } from '../interfaces/path'\n\nexport const string: EditorInterface['string'] = (editor, at, options = {}) => {\n const { voids = false } = options\n const range = Editor.range(editor, at)\n const [start, end] = Range.edges(range)\n let text = ''\n\n for (const [node, path] of Editor.nodes(editor, {\n at: range,\n match: Text.isText,\n voids,\n })) {\n let t = node.text\n\n if (Path.equals(path, end.path)) {\n t = t.slice(0, end.offset)\n }\n\n if (Path.equals(path, start.path)) {\n t = t.slice(start.offset)\n }\n\n text += t\n }\n\n return text\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\nimport { Range } from '../interfaces/range'\nimport { Path } from '../interfaces/path'\nimport { Element } from '../interfaces/element'\nimport { Text } from '../interfaces/text'\n\nexport const unhangRange: EditorInterface['unhangRange'] = (\n editor,\n range,\n options = {}\n) => {\n const { voids = false } = options\n let [start, end] = Range.edges(range)\n\n // PERF: exit early if we can guarantee that the range isn't hanging.\n if (\n start.offset !== 0 ||\n end.offset !== 0 ||\n Range.isCollapsed(range) ||\n Path.hasPrevious(end.path)\n ) {\n return range\n }\n\n const endBlock = Editor.above(editor, {\n at: end,\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n voids,\n })\n const blockPath = endBlock ? endBlock[1] : []\n const first = Editor.start(editor, start)\n const before = { anchor: first, focus: end }\n let skip = true\n\n for (const [node, path] of Editor.nodes(editor, {\n at: before,\n match: Text.isText,\n reverse: true,\n voids,\n })) {\n if (skip) {\n skip = false\n continue\n }\n\n if (node.text !== '' || Path.isBefore(path, blockPath)) {\n end = { path, offset: node.text.length }\n break\n }\n }\n\n return { anchor: start, focus: end }\n}\n","import { Editor, EditorInterface } from '../interfaces/editor'\n\nexport const withoutNormalizing: EditorInterface['withoutNormalizing'] = (\n editor,\n fn\n) => {\n const value = Editor.isNormalizing(editor)\n Editor.setNormalizing(editor, false)\n try {\n fn()\n } finally {\n Editor.setNormalizing(editor, value)\n }\n Editor.normalize(editor)\n}\n","import { EditorInterface, Element, Editor, Text } from '../interfaces'\n\nexport const shouldMergeNodesRemovePrevNode: EditorInterface['shouldMergeNodesRemovePrevNode'] =\n (editor, [prevNode, prevPath], [curNode, curNodePath]) => {\n // If the target node that we're merging with is empty, remove it instead\n // of merging the two. This is a common rich text editor behavior to\n // prevent losing formatting when deleting entire nodes when you have a\n // hanging selection.\n // if prevNode is first child in parent,don't remove it.\n\n return (\n (Element.isElement(prevNode) && Editor.isEmpty(editor, prevNode)) ||\n (Text.isText(prevNode) &&\n prevNode.text === '' &&\n prevPath[prevPath.length - 1] !== 0)\n )\n }\n","import { TextTransforms } from '../interfaces/transforms/text'\nimport { Editor } from '../interfaces/editor'\nimport { Range } from '../interfaces/range'\nimport { Point } from '../interfaces/point'\nimport { Path } from '../interfaces/path'\nimport { Transforms } from '../interfaces/transforms'\nimport { Element } from '../interfaces/element'\nimport { NodeEntry } from '../interfaces/node'\n\nexport const deleteText: TextTransforms['delete'] = (editor, options = {}) => {\n Editor.withoutNormalizing(editor, () => {\n const {\n reverse = false,\n unit = 'character',\n distance = 1,\n voids = false,\n } = options\n let { at = editor.selection, hanging = false } = options\n\n if (!at) {\n return\n }\n\n let isCollapsed = false\n if (Range.isRange(at) && Range.isCollapsed(at)) {\n isCollapsed = true\n at = at.anchor\n }\n\n if (Point.isPoint(at)) {\n const furthestVoid = Editor.void(editor, { at, mode: 'highest' })\n\n if (!voids && furthestVoid) {\n const [, voidPath] = furthestVoid\n at = voidPath\n } else {\n const opts = { unit, distance }\n const target = reverse\n ? Editor.before(editor, at, opts) || Editor.start(editor, [])\n : Editor.after(editor, at, opts) || Editor.end(editor, [])\n at = { anchor: at, focus: target }\n hanging = true\n }\n }\n\n if (Path.isPath(at)) {\n Transforms.removeNodes(editor, { at, voids })\n return\n }\n\n if (Range.isCollapsed(at)) {\n return\n }\n\n if (!hanging) {\n const [, end] = Range.edges(at)\n const endOfDoc = Editor.end(editor, [])\n\n if (!Point.equals(end, endOfDoc)) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n }\n\n let [start, end] = Range.edges(at)\n const startBlock = Editor.above(editor, {\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n at: start,\n voids,\n })\n const endBlock = Editor.above(editor, {\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n at: end,\n voids,\n })\n const isAcrossBlocks =\n startBlock && endBlock && !Path.equals(startBlock[1], endBlock[1])\n const isSingleText = Path.equals(start.path, end.path)\n const startNonEditable = voids\n ? null\n : Editor.void(editor, { at: start, mode: 'highest' }) ??\n Editor.elementReadOnly(editor, { at: start, mode: 'highest' })\n const endNonEditable = voids\n ? null\n : Editor.void(editor, { at: end, mode: 'highest' }) ??\n Editor.elementReadOnly(editor, { at: end, mode: 'highest' })\n\n // If the start or end points are inside an inline void, nudge them out.\n if (startNonEditable) {\n const before = Editor.before(editor, start)\n\n if (before && startBlock && Path.isAncestor(startBlock[1], before.path)) {\n start = before\n }\n }\n\n if (endNonEditable) {\n const after = Editor.after(editor, end)\n\n if (after && endBlock && Path.isAncestor(endBlock[1], after.path)) {\n end = after\n }\n }\n\n // Get the highest nodes that are completely inside the range, as well as\n // the start and end nodes.\n const matches: NodeEntry[] = []\n let lastPath: Path | undefined\n\n for (const entry of Editor.nodes(editor, { at, voids })) {\n const [node, path] = entry\n\n if (lastPath && Path.compare(path, lastPath) === 0) {\n continue\n }\n\n if (\n (!voids &&\n Element.isElement(node) &&\n (Editor.isVoid(editor, node) ||\n Editor.isElementReadOnly(editor, node))) ||\n (!Path.isCommon(path, start.path) && !Path.isCommon(path, end.path))\n ) {\n matches.push(entry)\n lastPath = path\n }\n }\n\n const pathRefs = Array.from(matches, ([, p]) => Editor.pathRef(editor, p))\n const startRef = Editor.pointRef(editor, start)\n const endRef = Editor.pointRef(editor, end)\n\n let removedText = ''\n\n if (!isSingleText && !startNonEditable) {\n const point = startRef.current!\n const [node] = Editor.leaf(editor, point)\n const { path } = point\n const { offset } = start\n const text = node.text.slice(offset)\n if (text.length > 0) {\n editor.apply({ type: 'remove_text', path, offset, text })\n removedText = text\n }\n }\n\n pathRefs\n .reverse()\n .map(r => r.unref())\n .filter((r): r is Path => r !== null)\n .forEach(p => Transforms.removeNodes(editor, { at: p, voids }))\n\n if (!endNonEditable) {\n const point = endRef.current!\n const [node] = Editor.leaf(editor, point)\n const { path } = point\n const offset = isSingleText ? start.offset : 0\n const text = node.text.slice(offset, end.offset)\n if (text.length > 0) {\n editor.apply({ type: 'remove_text', path, offset, text })\n removedText = text\n }\n }\n\n if (!isSingleText && isAcrossBlocks && endRef.current && startRef.current) {\n Transforms.mergeNodes(editor, {\n at: endRef.current,\n hanging: true,\n voids,\n })\n }\n\n // For certain scripts, deleting N character(s) backward should delete\n // N code point(s) instead of an entire grapheme cluster.\n // Therefore, the remaining code points should be inserted back.\n // Bengali: \\u0980-\\u09FF\n // Thai: \\u0E00-\\u0E7F\n // Burmese (Myanmar): \\u1000-\\u109F\n // Hindi (Devanagari): \\u0900-\\u097F\n // Khmer: \\u1780-\\u17FF\n // Malayalam: \\u0D00-\\u0D7F\n // Oriya: \\u0B00-\\u0B7F\n // Punjabi (Gurmukhi): \\u0A00-\\u0A7F\n // Tamil: \\u0B80-\\u0BFF\n // Telugu: \\u0C00-\\u0C7F\n if (\n isCollapsed &&\n reverse &&\n unit === 'character' &&\n removedText.length > 1 &&\n removedText.match(\n /[\\u0980-\\u09FF\\u0E00-\\u0E7F\\u1000-\\u109F\\u0900-\\u097F\\u1780-\\u17FF\\u0D00-\\u0D7F\\u0B00-\\u0B7F\\u0A00-\\u0A7F\\u0B80-\\u0BFF\\u0C00-\\u0C7F]+/\n )\n ) {\n Transforms.insertText(\n editor,\n removedText.slice(0, removedText.length - distance)\n )\n }\n\n const startUnref = startRef.unref()\n const endUnref = endRef.unref()\n const point = reverse ? startUnref || endUnref : endUnref || startUnref\n\n if (options.at == null && point) {\n Transforms.select(editor, point)\n }\n })\n}\n","import { Transforms } from '../interfaces/transforms'\nimport { Editor } from '../interfaces/editor'\nimport { Range } from '../interfaces/range'\nimport { Path } from '../interfaces/path'\nimport { Element } from '../interfaces/element'\nimport { Descendant, Node, NodeEntry } from '../interfaces/node'\nimport { Text } from '../interfaces/text'\nimport { TextTransforms } from '../interfaces/transforms/text'\nimport { getDefaultInsertLocation } from '../utils'\n\nexport const insertFragment: TextTransforms['insertFragment'] = (\n editor,\n fragment,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const { hanging = false, voids = false } = options\n let { at = getDefaultInsertLocation(editor), batchDirty = true } = options\n\n if (!fragment.length) {\n return\n }\n\n if (Range.isRange(at)) {\n if (!hanging) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const [, end] = Range.edges(at)\n\n if (!voids && Editor.void(editor, { at: end })) {\n return\n }\n\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at })\n at = pointRef.unref()!\n }\n } else if (Path.isPath(at)) {\n at = Editor.start(editor, at)\n }\n\n if (!voids && Editor.void(editor, { at })) {\n return\n }\n\n // If the insert point is at the edge of an inline node, move it outside\n // instead since it will need to be split otherwise.\n const inlineElementMatch = Editor.above(editor, {\n at,\n match: n => Element.isElement(n) && Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n })\n\n if (inlineElementMatch) {\n const [, inlinePath] = inlineElementMatch\n\n if (Editor.isEnd(editor, at, inlinePath)) {\n const after = Editor.after(editor, inlinePath)!\n at = after\n } else if (Editor.isStart(editor, at, inlinePath)) {\n const before = Editor.before(editor, inlinePath)!\n at = before\n }\n }\n\n const blockMatch = Editor.above(editor, {\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n at,\n voids,\n })!\n const [, blockPath] = blockMatch\n const isBlockStart = Editor.isStart(editor, at, blockPath)\n const isBlockEnd = Editor.isEnd(editor, at, blockPath)\n const isBlockEmpty = isBlockStart && isBlockEnd\n const [, firstLeafPath] = Node.first({ children: fragment }, [])\n const [, lastLeafPath] = Node.last({ children: fragment }, [])\n\n // For each node in the fragment, determine what level of wrapping should\n // be kept. At minimum, all text nodes will be inserted, but if\n // `shouldInsert` returns true for some ancestor of a particular text node,\n // then the entire ancestor will be inserted rather than inserting the text\n // nodes individually.\n const shouldInsert = ([n, p]: NodeEntry) => {\n const isRoot = p.length === 0\n if (isRoot) {\n return false\n }\n\n // If the destination block is empty, insert all top-level blocks of the\n // fragment.\n if (isBlockEmpty) {\n return true\n }\n\n // Unless we're at the start of the destination block, unwrap any\n // non-void blocks that contain the first leaf node in the fragment.\n if (\n !isBlockStart &&\n Path.isAncestor(p, firstLeafPath) &&\n Element.isElement(n) &&\n !editor.isVoid(n) &&\n !editor.isInline(n)\n ) {\n return false\n }\n\n // Unless we're at the end of the destination block, unwrap any non-void\n // blocks that contain the last leaf node in the fragment.\n if (\n !isBlockEnd &&\n Path.isAncestor(p, lastLeafPath) &&\n Element.isElement(n) &&\n !editor.isVoid(n) &&\n !editor.isInline(n)\n ) {\n return false\n }\n\n // Always insert void nodes, inline elements and text nodes.\n return true\n }\n\n // Whether the current node is in the first block of the fragment.\n let starting = true\n\n // Inline nodes in the first block of the fragment, to be merged with the\n // destination block.\n const starts: Descendant[] = []\n\n // Blocks in the middle of the fragment.\n const middles: Element[] = []\n\n // Inline nodes in the last block of the fragment, to be merged with the\n // destination block. If the fragment contains only one block, this will be\n // empty.\n const ends: Descendant[] = []\n\n for (const entry of Node.nodes(\n { children: fragment },\n { pass: shouldInsert }\n )) {\n const [node, path] = entry\n\n // If we encounter a block that does not contain the first leaf, we're no\n // longer in the first block of the fragment.\n if (\n starting &&\n Element.isElement(node) &&\n !editor.isInline(node) &&\n !Path.isAncestor(path, firstLeafPath)\n ) {\n starting = false\n }\n\n if (shouldInsert(entry)) {\n if (Element.isElement(node) && !editor.isInline(node)) {\n starting = false\n middles.push(node)\n } else if (starting) {\n starts.push(node)\n } else {\n ends.push(node)\n }\n }\n }\n\n const [inlineMatch] = Editor.nodes(editor, {\n at,\n match: n => Text.isText(n) || Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n })!\n\n const [, inlinePath] = inlineMatch\n const isInlineStart = Editor.isStart(editor, at, inlinePath)\n const isInlineEnd = Editor.isEnd(editor, at, inlinePath)\n\n const middleRef = Editor.pathRef(\n editor,\n isBlockEnd && !ends.length ? Path.next(blockPath) : blockPath\n )\n\n const endRef = Editor.pathRef(\n editor,\n isInlineEnd ? Path.next(inlinePath) : inlinePath\n )\n\n // If the fragment contains inlines in multiple distinct blocks, split the\n // destination block.\n const splitBlock = ends.length > 0\n\n Transforms.splitNodes(editor, {\n at,\n match: n =>\n splitBlock\n ? Element.isElement(n) && Editor.isBlock(editor, n)\n : Text.isText(n) || Editor.isInline(editor, n),\n mode: splitBlock ? 'lowest' : 'highest',\n always:\n splitBlock &&\n (!isBlockStart || starts.length > 0) &&\n (!isBlockEnd || ends.length > 0),\n voids,\n })\n\n const startRef = Editor.pathRef(\n editor,\n !isInlineStart || (isInlineStart && isInlineEnd)\n ? Path.next(inlinePath)\n : inlinePath\n )\n\n Transforms.insertNodes(editor, starts, {\n at: startRef.current!,\n match: n => Text.isText(n) || Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n batchDirty,\n })\n\n if (isBlockEmpty && !starts.length && middles.length && !ends.length) {\n Transforms.delete(editor, { at: blockPath, voids })\n }\n\n Transforms.insertNodes(editor, middles, {\n at: middleRef.current!,\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n mode: 'lowest',\n voids,\n batchDirty,\n })\n\n Transforms.insertNodes(editor, ends, {\n at: endRef.current!,\n match: n => Text.isText(n) || Editor.isInline(editor, n),\n mode: 'highest',\n voids,\n batchDirty,\n })\n\n if (!options.at) {\n let path\n\n if (ends.length > 0 && endRef.current) {\n path = Path.previous(endRef.current)\n } else if (middles.length > 0 && middleRef.current) {\n path = Path.previous(middleRef.current)\n } else if (startRef.current) {\n path = Path.previous(startRef.current)\n }\n\n if (path) {\n const end = Editor.end(editor, path)\n Transforms.select(editor, end)\n }\n }\n\n startRef.unref()\n middleRef.unref()\n endRef.unref()\n })\n}\n","import { SelectionTransforms } from '../interfaces/transforms/selection'\nimport { Transforms } from '../interfaces/transforms'\nimport { Range } from '../interfaces/range'\n\nexport const collapse: SelectionTransforms['collapse'] = (\n editor,\n options = {}\n) => {\n const { edge = 'anchor' } = options\n const { selection } = editor\n\n if (!selection) {\n return\n } else if (edge === 'anchor') {\n Transforms.select(editor, selection.anchor)\n } else if (edge === 'focus') {\n Transforms.select(editor, selection.focus)\n } else if (edge === 'start') {\n const [start] = Range.edges(selection)\n Transforms.select(editor, start)\n } else if (edge === 'end') {\n const [, end] = Range.edges(selection)\n Transforms.select(editor, end)\n }\n}\n","import { SelectionTransforms } from '../interfaces/transforms/selection'\n\nexport const deselect: SelectionTransforms['deselect'] = editor => {\n const { selection } = editor\n\n if (selection) {\n editor.apply({\n type: 'set_selection',\n properties: selection,\n newProperties: null,\n })\n }\n}\n","import { SelectionTransforms } from '../interfaces/transforms/selection'\nimport { Range } from '../interfaces/range'\nimport { Editor } from '../interfaces/editor'\nimport { Transforms } from '../interfaces/transforms'\n\nexport const move: SelectionTransforms['move'] = (editor, options = {}) => {\n const { selection } = editor\n const { distance = 1, unit = 'character', reverse = false } = options\n let { edge = null } = options\n\n if (!selection) {\n return\n }\n\n if (edge === 'start') {\n edge = Range.isBackward(selection) ? 'focus' : 'anchor'\n }\n\n if (edge === 'end') {\n edge = Range.isBackward(selection) ? 'anchor' : 'focus'\n }\n\n const { anchor, focus } = selection\n const opts = { distance, unit }\n const props: Partial<Range> = {}\n\n if (edge == null || edge === 'anchor') {\n const point = reverse\n ? Editor.before(editor, anchor, opts)\n : Editor.after(editor, anchor, opts)\n\n if (point) {\n props.anchor = point\n }\n }\n\n if (edge == null || edge === 'focus') {\n const point = reverse\n ? Editor.before(editor, focus, opts)\n : Editor.after(editor, focus, opts)\n\n if (point) {\n props.focus = point\n }\n }\n\n Transforms.setSelection(editor, props)\n}\n","import { SelectionTransforms } from '../interfaces/transforms/selection'\nimport { Editor } from '../interfaces/editor'\nimport { Transforms } from '../interfaces/transforms'\nimport { Range } from '../interfaces/range'\nimport { Scrubber } from '../interfaces/scrubber'\n\nexport const select: SelectionTransforms['select'] = (editor, target) => {\n const { selection } = editor\n target = Editor.range(editor, target)\n\n if (selection) {\n Transforms.setSelection(editor, target)\n return\n }\n\n if (!Range.isRange(target)) {\n throw new Error(\n `When setting the selection and the current selection is \\`null\\` you must provide at least an \\`anchor\\` and \\`focus\\`, but you passed: ${Scrubber.stringify(\n target\n )}`\n )\n }\n\n editor.apply({\n type: 'set_selection',\n properties: selection,\n newProperties: target,\n })\n}\n","import { SelectionTransforms } from '../interfaces/transforms/selection'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\n\nexport const setPoint: SelectionTransforms['setPoint'] = (\n editor,\n props,\n options = {}\n) => {\n const { selection } = editor\n let { edge = 'both' } = options\n\n if (!selection) {\n return\n }\n\n if (edge === 'start') {\n edge = Range.isBackward(selection) ? 'focus' : 'anchor'\n }\n\n if (edge === 'end') {\n edge = Range.isBackward(selection) ? 'anchor' : 'focus'\n }\n\n const { anchor, focus } = selection\n const point = edge === 'anchor' ? anchor : focus\n\n Transforms.setSelection(editor, {\n [edge === 'anchor' ? 'anchor' : 'focus']: { ...point, ...props },\n })\n}\n","import { SelectionTransforms } from '../interfaces/transforms/selection'\nimport { Range } from '../interfaces/range'\nimport { Point } from '../interfaces/point'\n\nexport const setSelection: SelectionTransforms['setSelection'] = (\n editor,\n props\n) => {\n const { selection } = editor\n const oldProps: Partial<Range> | null = {}\n const newProps: Partial<Range> = {}\n\n if (!selection) {\n return\n }\n\n for (const k in props) {\n if (\n (k === 'anchor' &&\n props.anchor != null &&\n !Point.equals(props.anchor, selection.anchor)) ||\n (k === 'focus' &&\n props.focus != null &&\n !Point.equals(props.focus, selection.focus)) ||\n (k !== 'anchor' &&\n k !== 'focus' &&\n props[<keyof Range>k] !== selection[<keyof Range>k])\n ) {\n oldProps[<keyof Range>k] = selection[<keyof Range>k]\n newProps[<keyof Range>k] = props[<keyof Range>k]\n }\n }\n\n if (Object.keys(oldProps).length > 0) {\n editor.apply({\n type: 'set_selection',\n properties: oldProps,\n newProperties: newProps,\n })\n }\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Node } from '../interfaces/node'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { Point } from '../interfaces/point'\nimport { Text } from '../interfaces/text'\nimport { Element } from '../interfaces/element'\nimport { Path } from '../interfaces/path'\nimport { getDefaultInsertLocation } from '../utils'\nimport { batchDirtyPaths } from '../core/batch-dirty-paths'\nimport { BaseInsertNodeOperation } from '../interfaces'\nimport { updateDirtyPaths } from '../core/update-dirty-paths'\n\nexport const insertNodes: NodeTransforms['insertNodes'] = (\n editor,\n nodes,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const {\n hanging = false,\n voids = false,\n mode = 'lowest',\n batchDirty = true,\n } = options\n let { at, match, select } = options\n\n if (Node.isNode(nodes)) {\n nodes = [nodes]\n }\n\n if (nodes.length === 0) {\n return\n }\n\n const [node] = nodes\n\n if (!at) {\n at = getDefaultInsertLocation(editor)\n if (select !== false) {\n select = true\n }\n }\n\n if (select == null) {\n select = false\n }\n\n if (Range.isRange(at)) {\n if (!hanging) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const [, end] = Range.edges(at)\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at })\n at = pointRef.unref()!\n }\n }\n\n if (Point.isPoint(at)) {\n if (match == null) {\n if (Text.isText(node)) {\n match = n => Text.isText(n)\n } else if (editor.isInline(node)) {\n match = n => Text.isText(n) || Editor.isInline(editor, n)\n } else {\n match = n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n }\n\n const [entry] = Editor.nodes(editor, {\n at: at.path,\n match,\n mode,\n voids,\n })\n\n if (entry) {\n const [, matchPath] = entry\n const pathRef = Editor.pathRef(editor, matchPath)\n const isAtEnd = Editor.isEnd(editor, at, matchPath)\n Transforms.splitNodes(editor, { at, match, mode, voids })\n const path = pathRef.unref()!\n at = isAtEnd ? Path.next(path) : path\n } else {\n return\n }\n }\n\n const parentPath = Path.parent(at)\n let index = at[at.length - 1]\n\n if (!voids && Editor.void(editor, { at: parentPath })) {\n return\n }\n\n if (batchDirty) {\n // PERF: batch update dirty paths\n // batched ops used to transform existing dirty paths\n const batchedOps: BaseInsertNodeOperation[] = []\n const newDirtyPaths: Path[] = Path.levels(parentPath)\n batchDirtyPaths(\n editor,\n () => {\n for (const node of nodes as Node[]) {\n const path = parentPath.concat(index)\n index++\n\n const op: BaseInsertNodeOperation = {\n type: 'insert_node',\n path,\n node,\n }\n editor.apply(op)\n at = Path.next(at as Path)\n\n batchedOps.push(op)\n if (Text.isText(node)) {\n newDirtyPaths.push(path)\n } else {\n newDirtyPaths.push(\n ...Array.from(Node.nodes(node), ([, p]) => path.concat(p))\n )\n }\n }\n },\n () => {\n updateDirtyPaths(editor, newDirtyPaths, p => {\n let newPath: Path | null = p\n for (const op of batchedOps) {\n if (Path.operationCanTransformPath(op)) {\n newPath = Path.transform(newPath, op)\n if (!newPath) {\n return null\n }\n }\n }\n return newPath\n })\n }\n )\n } else {\n for (const node of nodes as Node[]) {\n const path = parentPath.concat(index)\n index++\n\n editor.apply({ type: 'insert_node', path, node })\n at = Path.next(at as Path)\n }\n }\n\n at = Path.previous(at)\n\n if (select) {\n const point = Editor.end(editor, at)\n\n if (point) {\n Transforms.select(editor, point)\n }\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { matchPath } from '../utils/match-path'\nimport { Element } from '../interfaces/element'\nimport { Ancestor, NodeEntry } from '../interfaces/node'\nimport { Transforms } from '../interfaces/transforms'\n\nexport const liftNodes: NodeTransforms['liftNodes'] = (\n editor,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const { at = editor.selection, mode = 'lowest', voids = false } = options\n let { match } = options\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n\n if (!at) {\n return\n }\n\n const matches = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(matches, ([, p]) => Editor.pathRef(editor, p))\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n\n if (path.length < 2) {\n throw new Error(\n `Cannot lift node at a path [${path}] because it has a depth of less than \\`2\\`.`\n )\n }\n\n const parentNodeEntry = Editor.node(editor, Path.parent(path))\n const [parent, parentPath] = parentNodeEntry as NodeEntry<Ancestor>\n const index = path[path.length - 1]\n const { length } = parent.children\n\n if (length === 1) {\n const toPath = Path.next(parentPath)\n Transforms.moveNodes(editor, { at: path, to: toPath, voids })\n Transforms.removeNodes(editor, { at: parentPath, voids })\n } else if (index === 0) {\n Transforms.moveNodes(editor, { at: path, to: parentPath, voids })\n } else if (index === length - 1) {\n const toPath = Path.next(parentPath)\n Transforms.moveNodes(editor, { at: path, to: toPath, voids })\n } else {\n const splitPath = Path.next(path)\n const toPath = Path.next(parentPath)\n Transforms.splitNodes(editor, { at: splitPath, voids })\n Transforms.moveNodes(editor, { at: path, to: toPath, voids })\n }\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { Element } from '../interfaces/element'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { Text } from '../interfaces/text'\nimport { Scrubber } from '../interfaces/scrubber'\nimport { Node } from '../interfaces/node'\n\nconst hasSingleChildNest = (editor: Editor, node: Node): boolean => {\n if (Element.isElement(node)) {\n const element = node as Element\n if (Editor.isVoid(editor, node)) {\n return true\n } else if (element.children.length === 1) {\n return hasSingleChildNest(editor, element.children[0])\n } else {\n return false\n }\n } else if (Editor.isEditor(node)) {\n return false\n } else {\n return true\n }\n}\n\nexport const mergeNodes: NodeTransforms['mergeNodes'] = (\n editor,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n let { match, at = editor.selection } = options\n const { hanging = false, voids = false, mode = 'lowest' } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n const [parent] = Editor.parent(editor, at)\n match = n => parent.children.includes(n)\n } else {\n match = n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n }\n\n if (!hanging && Range.isRange(at)) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n\n if (Range.isRange(at)) {\n if (Range.isCollapsed(at)) {\n at = at.anchor\n } else {\n const [, end] = Range.edges(at)\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at })\n at = pointRef.unref()!\n\n if (options.at == null) {\n Transforms.select(editor, at)\n }\n }\n }\n\n const [current] = Editor.nodes(editor, { at, match, voids, mode })\n const prev = Editor.previous(editor, { at, match, voids, mode })\n\n if (!current || !prev) {\n return\n }\n\n const [node, path] = current\n const [prevNode, prevPath] = prev\n\n if (path.length === 0 || prevPath.length === 0) {\n return\n }\n\n const newPath = Path.next(prevPath)\n const commonPath = Path.common(path, prevPath)\n const isPreviousSibling = Path.isSibling(path, prevPath)\n const levels = Array.from(Editor.levels(editor, { at: path }), ([n]) => n)\n .slice(commonPath.length)\n .slice(0, -1)\n\n // Determine if the merge will leave an ancestor of the path empty as a\n // result, in which case we'll want to remove it after merging.\n const emptyAncestor = Editor.above(editor, {\n at: path,\n mode: 'highest',\n match: n => levels.includes(n) && hasSingleChildNest(editor, n),\n })\n\n const emptyRef = emptyAncestor && Editor.pathRef(editor, emptyAncestor[1])\n let properties\n let position\n\n // Ensure that the nodes are equivalent, and figure out what the position\n // and extra properties of the merge will be.\n if (Text.isText(node) && Text.isText(prevNode)) {\n const { text, ...rest } = node\n position = prevNode.text.length\n properties = rest as Partial<Text>\n } else if (Element.isElement(node) && Element.isElement(prevNode)) {\n const { children, ...rest } = node\n position = prevNode.children.length\n properties = rest as Partial<Element>\n } else {\n throw new Error(\n `Cannot merge the node at path [${path}] with the previous sibling because it is not the same kind: ${Scrubber.stringify(\n node\n )} ${Scrubber.stringify(prevNode)}`\n )\n }\n\n // If the node isn't already the next sibling of the previous node, move\n // it so that it is before merging.\n if (!isPreviousSibling) {\n Transforms.moveNodes(editor, { at: path, to: newPath, voids })\n }\n\n // If there was going to be an empty ancestor of the node that was merged,\n // we remove it from the tree.\n if (emptyRef) {\n Transforms.removeNodes(editor, { at: emptyRef.current!, voids })\n }\n\n if (Editor.shouldMergeNodesRemovePrevNode(editor, prev, current)) {\n Transforms.removeNodes(editor, { at: prevPath, voids })\n } else {\n editor.apply({\n type: 'merge_node',\n path: newPath,\n position,\n properties,\n })\n }\n\n if (emptyRef) {\n emptyRef.unref()\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { matchPath } from '../utils/match-path'\nimport { Element } from '../interfaces/element'\n\nexport const moveNodes: NodeTransforms['moveNodes'] = (editor, options) => {\n Editor.withoutNormalizing(editor, () => {\n const {\n to,\n at = editor.selection,\n mode = 'lowest',\n voids = false,\n } = options\n let { match } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n\n const toRef = Editor.pathRef(editor, to)\n const targets = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(targets, ([, p]) => Editor.pathRef(editor, p))\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n const newPath = toRef.current!\n\n if (path.length !== 0) {\n editor.apply({ type: 'move_node', path, newPath })\n }\n\n if (\n toRef.current &&\n Path.isSibling(newPath, path) &&\n Path.isAfter(newPath, path)\n ) {\n // When performing a sibling move to a later index, the path at the destination is shifted\n // to before the insertion point instead of after. To ensure our group of nodes are inserted\n // in the correct order we increment toRef to account for that\n toRef.current = Path.next(toRef.current)\n }\n }\n\n toRef.unref()\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { matchPath } from '../utils/match-path'\nimport { Element } from '../interfaces/element'\nimport { Range } from '../interfaces/range'\n\nexport const removeNodes: NodeTransforms['removeNodes'] = (\n editor,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const { hanging = false, voids = false, mode = 'lowest' } = options\n let { at = editor.selection, match } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n\n if (!hanging && Range.isRange(at)) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n\n const depths = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(depths, ([, p]) => Editor.pathRef(editor, p))\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n\n if (path) {\n const [node] = Editor.node(editor, path)\n editor.apply({ type: 'remove_node', path, node })\n }\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { matchPath } from '../utils/match-path'\nimport { Element } from '../interfaces/element'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { Node } from '../interfaces/node'\n\nexport const setNodes: NodeTransforms['setNodes'] = (\n editor,\n props: Partial<Node>,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n let { match, at = editor.selection, compare, merge } = options\n const {\n hanging = false,\n mode = 'lowest',\n split = false,\n voids = false,\n } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n\n if (!hanging && Range.isRange(at)) {\n at = Editor.unhangRange(editor, at, { voids })\n }\n\n if (split && Range.isRange(at)) {\n if (\n Range.isCollapsed(at) &&\n Editor.leaf(editor, at.anchor)[0].text.length > 0\n ) {\n // If the range is collapsed in a non-empty node and 'split' is true, there's nothing to\n // set that won't get normalized away\n return\n }\n const rangeRef = Editor.rangeRef(editor, at, { affinity: 'inward' })\n const [start, end] = Range.edges(at)\n const splitMode = mode === 'lowest' ? 'lowest' : 'highest'\n const endAtEndOfNode = Editor.isEnd(editor, end, end.path)\n Transforms.splitNodes(editor, {\n at: end,\n match,\n mode: splitMode,\n voids,\n always: !endAtEndOfNode,\n })\n const startAtStartOfNode = Editor.isStart(editor, start, start.path)\n Transforms.splitNodes(editor, {\n at: start,\n match,\n mode: splitMode,\n voids,\n always: !startAtStartOfNode,\n })\n at = rangeRef.unref()!\n\n if (options.at == null) {\n Transforms.select(editor, at)\n }\n }\n\n if (!compare) {\n compare = (prop, nodeProp) => prop !== nodeProp\n }\n\n for (const [node, path] of Editor.nodes(editor, {\n at,\n match,\n mode,\n voids,\n })) {\n const properties: Partial<Node> = {}\n // FIXME: is this correct?\n const newProperties: Partial<Node> & { [key: string]: unknown } = {}\n\n // You can't set properties on the editor node.\n if (path.length === 0) {\n continue\n }\n\n let hasChanges = false\n\n for (const k in props) {\n if (k === 'children' || k === 'text') {\n continue\n }\n\n if (compare(props[<keyof Node>k], node[<keyof Node>k])) {\n hasChanges = true\n // Omit new properties from the old properties list\n if (node.hasOwnProperty(k))\n properties[<keyof Node>k] = node[<keyof Node>k]\n // Omit properties that have been removed from the new properties list\n if (merge) {\n if (props[<keyof Node>k] != null)\n newProperties[<keyof Node>k] = merge(\n node[<keyof Node>k],\n props[<keyof Node>k]\n )\n } else {\n if (props[<keyof Node>k] != null)\n newProperties[<keyof Node>k] = props[<keyof Node>k]\n }\n }\n }\n\n if (hasChanges) {\n editor.apply({\n type: 'set_node',\n path,\n properties,\n newProperties,\n })\n }\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Element } from '../interfaces/element'\nimport { Range } from '../interfaces/range'\nimport { Path } from '../interfaces/path'\nimport { PointRef } from '../interfaces/point-ref'\nimport { Transforms } from '../interfaces/transforms'\nimport { Node } from '../interfaces/node'\nimport { Point } from '../interfaces/point'\n\n/**\n * Convert a range into a point by deleting it's content.\n */\nconst deleteRange = (editor: Editor, range: Range): Point | null => {\n if (Range.isCollapsed(range)) {\n return range.anchor\n } else {\n const [, end] = Range.edges(range)\n const pointRef = Editor.pointRef(editor, end)\n Transforms.delete(editor, { at: range })\n return pointRef.unref()\n }\n}\n\nexport const splitNodes: NodeTransforms['splitNodes'] = (\n editor,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const { mode = 'lowest', voids = false } = options\n let { match, at = editor.selection, height = 0, always = false } = options\n\n if (match == null) {\n match = n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n\n if (Range.isRange(at)) {\n at = deleteRange(editor, at)\n }\n\n // If the target is a path, the default height-skipping and position\n // counters need to account for us potentially splitting at a non-leaf.\n if (Path.isPath(at)) {\n const path = at\n const point = Editor.point(editor, path)\n const [parent] = Editor.parent(editor, path)\n match = n => n === parent\n height = point.path.length - path.length + 1\n at = point\n always = true\n }\n\n if (!at) {\n return\n }\n\n const beforeRef = Editor.pointRef(editor, at, {\n affinity: 'backward',\n })\n let afterRef: PointRef | undefined\n try {\n const [highest] = Editor.nodes(editor, { at, match, mode, voids })\n\n if (!highest) {\n return\n }\n\n const voidMatch = Editor.void(editor, { at, mode: 'highest' })\n const nudge = 0\n\n if (!voids && voidMatch) {\n const [voidNode, voidPath] = voidMatch\n\n if (Element.isElement(voidNode) && editor.isInline(voidNode)) {\n let after = Editor.after(editor, voidPath)\n\n if (!after) {\n const text = { text: '' }\n const afterPath = Path.next(voidPath)\n Transforms.insertNodes(editor, text, { at: afterPath, voids })\n after = Editor.point(editor, afterPath)!\n }\n\n at = after\n always = true\n }\n\n const siblingHeight = at.path.length - voidPath.length\n height = siblingHeight + 1\n always = true\n }\n\n afterRef = Editor.pointRef(editor, at)\n const depth = at.path.length - height\n const [, highestPath] = highest\n const lowestPath = at.path.slice(0, depth)\n let position = height === 0 ? at.offset : at.path[depth] + nudge\n\n for (const [node, path] of Editor.levels(editor, {\n at: lowestPath,\n reverse: true,\n voids,\n })) {\n let split = false\n\n if (\n path.length < highestPath.length ||\n path.length === 0 ||\n (!voids && Element.isElement(node) && Editor.isVoid(editor, node))\n ) {\n break\n }\n\n const point = beforeRef.current!\n const isEnd = Editor.isEnd(editor, point, path)\n\n if (always || !beforeRef || !Editor.isEdge(editor, point, path)) {\n split = true\n const properties = Node.extractProps(node)\n editor.apply({\n type: 'split_node',\n path,\n position,\n properties,\n })\n }\n\n position = path[path.length - 1] + (split || isEnd ? 1 : 0)\n }\n\n if (options.at == null) {\n const point = afterRef.current || Editor.end(editor, [])\n Transforms.select(editor, point)\n }\n } finally {\n beforeRef.unref()\n afterRef?.unref()\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Transforms } from '../interfaces/transforms'\n\nexport const unsetNodes: NodeTransforms['unsetNodes'] = (\n editor,\n props,\n options = {}\n) => {\n if (!Array.isArray(props)) {\n props = [props]\n }\n\n const obj: any = {}\n\n for (const key of props) {\n obj[key] = null\n }\n\n Transforms.setNodes(editor, obj, options)\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { matchPath } from '../utils/match-path'\nimport { Element } from '../interfaces/element'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\n\nexport const unwrapNodes: NodeTransforms['unwrapNodes'] = (\n editor,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const { mode = 'lowest', split = false, voids = false } = options\n let { at = editor.selection, match } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n match = Path.isPath(at)\n ? matchPath(editor, at)\n : n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n\n if (Path.isPath(at)) {\n at = Editor.range(editor, at)\n }\n\n const rangeRef = Range.isRange(at) ? Editor.rangeRef(editor, at) : null\n const matches = Editor.nodes(editor, { at, match, mode, voids })\n const pathRefs = Array.from(\n matches,\n ([, p]) => Editor.pathRef(editor, p)\n // unwrapNode will call liftNode which does not support splitting the node when nested.\n // If we do not reverse the order and call it from top to the bottom, it will remove all blocks\n // that wrap target node. So we reverse the order.\n ).reverse()\n\n for (const pathRef of pathRefs) {\n const path = pathRef.unref()!\n const [node] = Editor.node(editor, path)\n let range = Editor.range(editor, path)\n\n if (split && rangeRef) {\n range = Range.intersection(rangeRef.current!, range)!\n }\n\n Transforms.liftNodes(editor, {\n at: range,\n match: n => Element.isAncestor(node) && node.children.includes(n),\n voids,\n })\n }\n\n if (rangeRef) {\n rangeRef.unref()\n }\n })\n}\n","import { NodeTransforms } from '../interfaces/transforms/node'\nimport { Editor } from '../interfaces/editor'\nimport { Path } from '../interfaces/path'\nimport { matchPath } from '../utils/match-path'\nimport { Element } from '../interfaces/element'\nimport { Text } from '../interfaces/text'\nimport { Range } from '../interfaces/range'\nimport { Transforms } from '../interfaces/transforms'\nimport { Point } from '../interfaces'\n\nexport const wrapNodes: NodeTransforms['wrapNodes'] = (\n editor,\n element,\n options = {}\n) => {\n Editor.withoutNormalizing(editor, () => {\n const { mode = 'lowest', split = false, voids = false } = options\n let { match, at = editor.selection } = options\n\n if (!at) {\n return\n }\n\n if (match == null) {\n if (Path.isPath(at)) {\n match = matchPath(editor, at)\n } else if (editor.isInline(element)) {\n match = n =>\n (Element.isElement(n) && Editor.isInline(editor, n)) || Text.isText(n)\n } else {\n match = n => Element.isElement(n) && Editor.isBlock(editor, n)\n }\n }\n\n if (split && Range.isRange(at)) {\n const [start, end] = Range.edges(at)\n\n const rangeRef = Editor.rangeRef(editor, at, {\n affinity: 'inward',\n })\n\n // Always split if we're in the middle of a block, to ensure that text\n // node boundaries are handled correctly.\n const isAtBlockEdge = (point: Point) => {\n const blockAbove = Editor.above(editor, {\n at: point,\n match: n => Element.isElement(n) && Editor.isBlock(editor, n),\n })\n return blockAbove && Editor.isEdge(editor, point, blockAbove[1])\n }\n\n Transforms.splitNodes(editor, {\n at: end,\n match,\n voids,\n always: !isAtBlockEdge(end),\n })\n\n Transforms.splitNodes(editor, {\n at: start,\n match,\n voids,\n always: !isAtBlockEdge(start),\n })\n\n at = rangeRef.unref()!\n\n if (options.at == null) {\n Transforms.select(editor, at)\n }\n }\n\n const roots = Array.from(\n Editor.nodes(editor, {\n at,\n match: editor.isInline(element)\n ? n => Element.isElement(n) && Editor.isBlock(editor, n)\n : n => Editor.isEditor(n),\n mode: 'lowest',\n voids,\n })\n )\n\n for (const [, rootPath] of roots) {\n const a = Range.isRange(at)\n ? Range.intersection(at, Editor.range(editor, rootPath))\n : at\n\n if (!a) {\n continue\n }\n\n const matches = Array.from(\n Editor.nodes(editor, { at: a, match, mode, voids })\n )\n\n if (matches.length > 0) {\n const [first] = matches\n const last = matches[matches.length - 1]\n const [, firstPath] = first\n const [, lastPath] = last\n\n if (firstPath.length === 0 && lastPath.length === 0) {\n // if there's no matching parent - usually means the node is an editor - don't do anything\n continue\n }\n\n const commonPath = Path.equals(firstPath, lastPath)\n ? Path.parent(firstPath)\n : Path.common(firstPath, lastPath)\n\n const range = Editor.range(editor, firstPath, lastPath)\n const commonNodeEntry = Editor.node(editor, commonPath)\n const [commonNode] = commonNodeEntry\n const depth = commonPath.length + 1\n const wrapperPath = Path.next(lastPath.slice(0, depth))\n const wrapper = { ...element, children: [] }\n Transforms.insertNodes(editor, wrapper, { at: wrapperPath, voids })\n\n Transforms.moveNodes(editor, {\n at: range,\n match: n =>\n Element.isAncestor(commonNode) && commonNode.children.includes(n),\n to: wrapperPath.concat(0),\n voids,\n })\n }\n }\n })\n}\n","import {\n addMark,\n deleteFragment,\n Editor,\n getDirtyPaths,\n getFragment,\n insertBreak,\n insertFragment,\n insertNode,\n insertSoftBreak,\n insertText,\n normalizeNode,\n removeMark,\n shouldNormalize,\n} from './'\nimport { apply } from './core'\nimport {\n above,\n after,\n before,\n deleteBackward,\n deleteForward,\n edges,\n elementReadOnly,\n end,\n first,\n fragment,\n getVoid,\n hasBlocks,\n hasInlines,\n hasPath,\n hasTexts,\n isBlock,\n isEdge,\n isEmpty,\n isEnd,\n isNormalizing,\n isStart,\n last,\n leaf,\n levels,\n marks,\n next,\n node,\n nodes,\n normalize,\n parent,\n path,\n pathRef,\n pathRefs,\n point,\n pointRef,\n pointRefs,\n positions,\n previous,\n range,\n rangeRef,\n rangeRefs,\n setNormalizing,\n shouldMergeNodesRemovePrevNode,\n start,\n string,\n unhangRange,\n withoutNormalizing,\n} from './editor'\nimport { deleteText } from './transforms-text'\nimport {\n collapse,\n deselect,\n move,\n select,\n setPoint,\n setSelection,\n} from './transforms-selection'\nimport {\n insertNodes,\n liftNodes,\n mergeNodes,\n moveNodes,\n removeNodes,\n setNodes,\n splitNodes,\n unsetNodes,\n unwrapNodes,\n wrapNodes,\n} from './transforms-node'\n\n/**\n * Create a new Slate `Editor` object.\n */\nexport const createEditor = (): Editor => {\n const editor: Editor = {\n children: [],\n operations: [],\n selection: null,\n marks: null,\n isElementReadOnly: () => false,\n isInline: () => false,\n isSelectable: () => true,\n isVoid: () => false,\n markableVoid: () => false,\n onChange: () => {},\n\n // Core\n apply: (...args) => apply(editor, ...args),\n\n // Editor\n addMark: (...args) => addMark(editor, ...args),\n deleteBackward: (...args) => deleteBackward(editor, ...args),\n deleteForward: (...args) => deleteForward(editor, ...args),\n deleteFragment: (...args) => deleteFragment(editor, ...args),\n getFragment: (...args) => getFragment(editor, ...args),\n insertBreak: (...args) => insertBreak(editor, ...args),\n insertSoftBreak: (...args) => insertSoftBreak(editor, ...args),\n insertFragment: (...args) => insertFragment(editor, ...args),\n insertNode: (...args) => insertNode(editor, ...args),\n insertText: (...args) => insertText(editor, ...args),\n normalizeNode: (...args) => normalizeNode(editor, ...args),\n removeMark: (...args) => removeMark(editor, ...args),\n getDirtyPaths: (...args) => getDirtyPaths(editor, ...args),\n shouldNormalize: (...args) => shouldNormalize(editor, ...args),\n\n // Editor interface\n above: (...args) => above(editor, ...args),\n after: (...args) => after(editor, ...args),\n before: (...args) => before(editor, ...args),\n collapse: (...args) => collapse(editor, ...args),\n delete: (...args) => deleteText(editor, ...args),\n deselect: (...args) => deselect(editor, ...args),\n edges: (...args) => edges(editor, ...args),\n elementReadOnly: (...args) => elementReadOnly(editor, ...args),\n end: (...args) => end(editor, ...args),\n first: (...args) => first(editor, ...args),\n fragment: (...args) => fragment(editor, ...args),\n getMarks: (...args) => marks(editor, ...args),\n hasBlocks: (...args) => hasBlocks(editor, ...args),\n hasInlines: (...args) => hasInlines(editor, ...args),\n hasPath: (...args) => hasPath(editor, ...args),\n hasTexts: (...args) => hasTexts(editor, ...args),\n insertNodes: (...args) => insertNodes(editor, ...args),\n isBlock: (...args) => isBlock(editor, ...args),\n isEdge: (...args) => isEdge(editor, ...args),\n isEmpty: (...args) => isEmpty(editor, ...args),\n isEnd: (...args) => isEnd(editor, ...args),\n isNormalizing: (...args) => isNormalizing(editor, ...args),\n isStart: (...args) => isStart(editor, ...args),\n last: (...args) => last(editor, ...args),\n leaf: (...args) => leaf(editor, ...args),\n levels: (...args) => levels(editor, ...args),\n liftNodes: (...args) => liftNodes(editor, ...args),\n mergeNodes: (...args) => mergeNodes(editor, ...args),\n move: (...args) => move(editor, ...args),\n moveNodes: (...args) => moveNodes(editor, ...args),\n next: (...args) => next(editor, ...args),\n node: (...args) => node(editor, ...args),\n nodes: (...args) => nodes(editor, ...args),\n normalize: (...args) => normalize(editor, ...args),\n parent: (...args) => parent(editor, ...args),\n path: (...args) => path(editor, ...args),\n pathRef: (...args) => pathRef(editor, ...args),\n pathRefs: (...args) => pathRefs(editor, ...args),\n point: (...args) => point(editor, ...args),\n pointRef: (...args) => pointRef(editor, ...args),\n pointRefs: (...args) => pointRefs(editor, ...args),\n positions: (...args) => positions(editor, ...args),\n previous: (...args) => previous(editor, ...args),\n range: (...args) => range(editor, ...args),\n rangeRef: (...args) => rangeRef(editor, ...args),\n rangeRefs: (...args) => rangeRefs(editor, ...args),\n removeNodes: (...args) => removeNodes(editor, ...args),\n select: (...args) => select(editor, ...args),\n setNodes: (...args) => setNodes(editor, ...args),\n setNormalizing: (...args) => setNormalizing(editor, ...args),\n setPoint: (...args) => setPoint(editor, ...args),\n setSelection: (...args) => setSelection(editor, ...args),\n splitNodes: (...args) => splitNodes(editor, ...args),\n start: (...args) => start(editor, ...args),\n string: (...args) => string(editor, ...args),\n unhangRange: (...args) => unhangRange(editor, ...args),\n unsetNodes: (...args) => unsetNodes(editor, ...args),\n unwrapNodes: (...args) => unwrapNodes(editor, ...args),\n void: (...args) => getVoid(editor, ...args),\n withoutNormalizing: (...args) => withoutNormalizing(editor, ...args),\n wrapNodes: (...args) => wrapNodes(editor, ...args),\n shouldMergeNodesRemovePrevNode: (...args) =>\n shouldMergeNodesRemovePrevNode(editor, ...args),\n }\n\n return editor\n}\n","import type { UseChatHelpers } from '@ai-sdk/react';\nimport type { TriggerComboboxPluginOptions } from '@platejs/combobox';\n\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport {\n type EditorNodesOptions,\n type NodeEntry,\n type OmitFirst,\n type Path,\n type PluginConfig,\n type SlateEditor,\n type TIdElement,\n type TRange,\n bindFirst,\n ElementApi,\n getPluginType,\n KEYS,\n} from 'platejs';\nimport { createTPlatePlugin } from 'platejs/react';\n\nimport type { AIBatch } from '../../lib';\nimport type { AIMode, AIToolName } from '../../lib/types';\nimport type { ChatMessage } from './internal/types';\n\nimport { AIPlugin } from '../ai/AIPlugin';\nimport { removeAnchorAIChat } from './transforms';\nimport { acceptAIChat } from './transforms/acceptAIChat';\nimport { insertBelowAIChat } from './transforms/insertBelowAIChat';\nimport { replaceSelectionAIChat } from './transforms/replaceSelectionAIChat';\nimport { resetAIChat } from './utils/resetAIChat';\nimport { submitAIChat } from './utils/submitAIChat';\nimport { withAIChat } from './withAIChat';\n\nexport type AIChatPluginConfig = PluginConfig<\n 'aiChat',\n {\n _blockChunks: string;\n _blockPath: Path | null;\n /** @private Using For streamInsertChunk */\n _mdxName: string | null;\n _replaceIds: string[];\n /** @private The Editor used to generate the AI response. */\n aiEditor: SlateEditor | null;\n chat: UseChatHelpers<ChatMessage>;\n chatNodes: TIdElement[];\n chatSelection: TRange | null;\n /** @deprecated Use api.aiChat.node({streaming:true}) instead */\n experimental_lastTextId: string | null;\n /**\n * Specifies how the assistant message is handled:\n *\n * - 'insert': Directly inserts content into the editor without preview.\n * - 'chat': Initiates an interactive session to review and refine content\n * before insertion.\n */\n mode: AIMode;\n open: boolean;\n /** Whether the AI response is currently streaming. Cursor mode only. */\n streaming: boolean;\n toolName: AIToolName;\n } & TriggerComboboxPluginOptions,\n {\n aiChat: {\n reset: OmitFirst<typeof resetAIChat>;\n submit: OmitFirst<typeof submitAIChat>;\n hide: (options?: { focus?: boolean; undo?: boolean }) => void;\n node: (\n options?: EditorNodesOptions & { anchor?: boolean; streaming?: boolean }\n ) => NodeEntry | undefined;\n reload: () => void;\n show: () => void;\n stop: () => void;\n };\n },\n {\n aiChat: {\n accept: OmitFirst<typeof acceptAIChat>;\n insertBelow: OmitFirst<typeof insertBelowAIChat>;\n replaceSelection: OmitFirst<typeof replaceSelectionAIChat>;\n removeAnchor: (options?: EditorNodesOptions) => void;\n };\n }\n>;\n\nexport const AIChatPlugin = createTPlatePlugin<AIChatPluginConfig>({\n key: KEYS.aiChat,\n dependencies: ['ai'],\n node: {\n isElement: true,\n },\n options: {\n _blockChunks: '',\n _blockPath: null,\n _mdxName: null,\n _replaceIds: [],\n aiEditor: null,\n chat: { messages: [] } as unknown as UseChatHelpers<ChatMessage>,\n chatNodes: [],\n chatSelection: null,\n experimental_lastTextId: null,\n mode: 'insert',\n open: false,\n streaming: false,\n toolName: null,\n trigger: ' ',\n triggerPreviousCharPattern: /^\\s?$/,\n },\n})\n .overrideEditor(withAIChat)\n .extendApi<\n Pick<\n AIChatPluginConfig['api']['aiChat'],\n 'node' | 'reset' | 'stop' | 'submit'\n >\n >(({ editor, getOption, getOptions, setOption, type }) => {\n return {\n reset: bindFirst(resetAIChat, editor),\n submit: bindFirst(submitAIChat, editor),\n node: (options = {}) => {\n const { anchor = false, streaming = false, ...rest } = options;\n\n if (anchor) {\n return editor.api.node({\n at: [],\n match: (n) => ElementApi.isElement(n) && n.type === type,\n ...rest,\n });\n }\n\n if (streaming) {\n if (!getOption('streaming')) return;\n\n const path = getOption('_blockPath');\n if (!path) return;\n\n return editor.api.node({\n at: path,\n mode: 'lowest',\n reverse: true,\n match: (t) => !!t[getPluginType(editor, KEYS.ai)],\n ...rest,\n });\n }\n\n return editor.api.node({\n match: (n) => n[getPluginType(editor, KEYS.ai)],\n ...rest,\n });\n },\n reload: () => {\n const { chat, chatNodes, chatSelection } = getOptions();\n\n editor.getTransforms(AIPlugin).ai.undo();\n\n if (chatSelection) {\n editor.tf.setSelection(chatSelection);\n } else {\n editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.set(chatNodes.map((node) => node.id as string));\n }\n\n const blocks = editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.getNodes();\n\n const selection =\n blocks.length > 0 ? editor.api.nodesRange(blocks) : editor.selection;\n\n const ctx = {\n children: editor.children,\n selection: selection ?? null,\n toolName: getOption('toolName'),\n };\n\n void chat.regenerate?.({\n body: {\n ctx,\n },\n });\n },\n stop: () => {\n setOption('streaming', false);\n getOptions().chat.stop?.();\n },\n };\n })\n .extendApi(({ api, editor, getOptions, setOption, tf, type }) => ({\n hide: ({\n focus = true,\n undo = true,\n }: { focus?: boolean; undo?: boolean } = {}) => {\n api.aiChat.reset({ undo });\n\n setOption('open', false);\n\n if (focus) {\n if (editor.getOption(BlockSelectionPlugin, 'isSelectingSome')) {\n editor.getApi(BlockSelectionPlugin).blockSelection.focus();\n } else {\n editor.tf.focus();\n }\n }\n\n const lastBatch = editor.history.undos.at(-1) as AIBatch;\n\n if (lastBatch?.ai) {\n delete lastBatch.ai;\n }\n\n tf.aiChat.removeAnchor();\n },\n show: () => {\n api.aiChat.reset();\n\n setOption('toolName', null);\n\n getOptions().chat.setMessages?.([]);\n\n setOption('open', true);\n },\n }))\n .extendTransforms(({ editor }) => ({\n accept: bindFirst(acceptAIChat, editor),\n insertBelow: bindFirst(insertBelowAIChat, editor),\n removeAnchor: bindFirst(removeAnchorAIChat, editor),\n replaceSelection: bindFirst(replaceSelectionAIChat, editor),\n }));\n","import {\n acceptSuggestion,\n getSuggestionKey,\n getTransientSuggestionKey,\n} from '@platejs/suggestion';\nimport { SuggestionPlugin } from '@platejs/suggestion/react';\nimport { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport { withAIBatch } from '../../../lib';\nimport { AIPlugin } from '../../ai/AIPlugin';\nimport { type AIChatPluginConfig, AIChatPlugin } from '../AIChatPlugin';\n\nexport const acceptAIChat = (editor: PlateEditor) => {\n const mode = editor.getOption(AIChatPlugin, 'mode');\n\n if (mode === 'insert') {\n const { tf } = getEditorPlugin(editor, AIPlugin);\n const api = editor.getApi<AIChatPluginConfig>({ key: KEYS.ai });\n\n const lastAINodePath = api.aiChat.node({ at: [], reverse: true })![1];\n\n withAIBatch(editor, () => {\n tf.ai.removeMarks();\n editor.getTransforms(AIChatPlugin).aiChat.removeAnchor();\n });\n\n api.aiChat.hide();\n editor.tf.focus();\n\n const focusPoint = editor.api.end(lastAINodePath)!;\n\n editor.tf.setSelection({\n anchor: focusPoint,\n focus: focusPoint,\n });\n }\n\n if (mode === 'chat') {\n withAIBatch(editor, () => {\n acceptSuggestions(editor);\n });\n\n editor.getApi(AIChatPlugin).aiChat.hide();\n }\n};\n\nexport const acceptSuggestions = (editor: PlateEditor) => {\n const suggestions = editor.getApi(SuggestionPlugin).suggestion.nodes({\n transient: true,\n });\n\n suggestions.forEach(([suggestionNode]) => {\n const suggestionData = editor\n .getApi(SuggestionPlugin)\n .suggestion.suggestionData(suggestionNode);\n\n if (!suggestionData) return;\n\n const description = {\n createdAt: new Date(suggestionData.createdAt),\n keyId: getSuggestionKey(suggestionData.id),\n suggestionId: suggestionData.id,\n type: suggestionData.type,\n userId: suggestionData.userId,\n };\n\n acceptSuggestion(editor, description);\n });\n\n editor.tf.unsetNodes([getTransientSuggestionKey()], {\n at: [],\n mode: 'all',\n match: (n) => !!n[getTransientSuggestionKey()],\n });\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport cloneDeep from 'lodash/cloneDeep.js';\nimport { type SlateEditor, KEYS, PathApi, RangeApi } from 'platejs';\n\nimport { withAIBatch } from '../../../lib';\nimport { AIPlugin } from '../../ai/AIPlugin';\nimport { type AIChatPluginConfig, AIChatPlugin } from '../AIChatPlugin';\nimport { acceptSuggestions } from './acceptAIChat';\nimport { createFormattedBlocks } from './replaceSelectionAIChat';\n\nexport const insertBelowAIChat = (\n editor: PlateEditor,\n sourceEditor: SlateEditor,\n { format = 'single' }: { format?: 'all' | 'none' | 'single' } = {}\n) => {\n const { toolName } = editor.getOptions(AIChatPlugin);\n\n if (toolName === 'generate')\n return insertBelowGenerate(editor, sourceEditor, { format });\n\n const selectedBlocks = editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.getNodes();\n\n const selectedIds = editor.getOptions(BlockSelectionPlugin).selectedIds;\n\n editor.getTransforms(AIPlugin).ai.undo();\n\n const insertBlocksAndSelect =\n editor.getTransforms(BlockSelectionPlugin).blockSelection\n .insertBlocksAndSelect;\n\n if (!selectedIds || selectedIds.size === 0) return;\n\n const lastBlock = selectedBlocks.at(-1);\n\n if (!lastBlock) return;\n\n const nextPath = PathApi.next(lastBlock[1]);\n\n const nodes = selectedBlocks.map((block) => block[0]);\n\n insertBlocksAndSelect(nodes, {\n at: nextPath,\n insertedCallback: () => {\n withAIBatch(editor, () => {\n acceptSuggestions(editor);\n });\n },\n });\n\n editor.getApi(AIChatPlugin).aiChat.hide({ focus: false });\n};\n\nexport const insertBelowGenerate = (\n editor: PlateEditor,\n sourceEditor: SlateEditor,\n { format = 'single' }: { format?: 'all' | 'none' | 'single' } = {}\n) => {\n if (!sourceEditor || sourceEditor.api.isEmpty()) return;\n\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n editor.getApi<AIChatPluginConfig>({ key: KEYS.ai }).aiChat.hide();\n\n const insertBlocksAndSelect =\n editor.getTransforms(BlockSelectionPlugin).blockSelection\n .insertBlocksAndSelect;\n\n if (isBlockSelecting) {\n const selectedBlocks = editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.getNodes();\n\n const selectedIds = editor.getOptions(BlockSelectionPlugin).selectedIds;\n\n if (!selectedIds || selectedIds.size === 0) return;\n\n const lastBlock = selectedBlocks.at(-1);\n\n if (!lastBlock) return;\n\n const nextPath = PathApi.next(lastBlock[1]);\n\n if (format === 'none') {\n insertBlocksAndSelect(cloneDeep(sourceEditor.children), {\n at: nextPath,\n });\n\n return;\n }\n\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: lastBlock,\n });\n\n if (!formattedBlocks) return;\n\n insertBlocksAndSelect(formattedBlocks, {\n at: nextPath,\n });\n } else {\n const [, end] = RangeApi.edges(editor.selection!);\n const endPath = [end.path[0]];\n const currentBlock = editor.api.node({\n at: endPath,\n block: true,\n mode: 'lowest',\n });\n\n if (!currentBlock) return;\n if (format === 'none') {\n insertBlocksAndSelect(cloneDeep(sourceEditor.children), {\n at: PathApi.next(endPath),\n });\n\n return;\n }\n\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: currentBlock,\n });\n\n if (!formattedBlocks) return;\n\n insertBlocksAndSelect(formattedBlocks, {\n at: PathApi.next(endPath),\n });\n }\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport {\n BlockSelectionPlugin,\n removeBlockSelectionNodes,\n} from '@platejs/selection/react';\nimport cloneDeep from 'lodash/cloneDeep.js';\nimport {\n type NodeEntry,\n type SlateEditor,\n type TElement,\n KEYS,\n NodeApi,\n TextApi,\n} from 'platejs';\n\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nexport const createFormattedBlocks = ({\n blocks,\n format,\n sourceBlock,\n}: {\n blocks: TElement[];\n format: 'all' | 'none' | 'single';\n sourceBlock: NodeEntry;\n}) => {\n if (format === 'none') return cloneDeep(blocks);\n\n const [sourceNode] = sourceBlock;\n const firstTextEntry = NodeApi.firstText(sourceNode);\n\n if (!firstTextEntry) return null;\n\n const blockProps = NodeApi.extractProps(sourceNode);\n const textProps = NodeApi.extractProps(firstTextEntry[0]);\n\n const applyTextFormatting = (node: any): any => {\n if (TextApi.isText(node)) {\n return { ...textProps, ...node };\n }\n if (node.children) {\n return {\n ...node,\n children: node.children.map(applyTextFormatting),\n };\n }\n\n return node;\n };\n\n return blocks.map((block, index) => {\n if (format === 'single' && index > 0) {\n return block;\n }\n\n return applyTextFormatting({\n ...block,\n ...blockProps,\n });\n });\n};\n\nexport const replaceSelectionAIChat = (\n editor: PlateEditor,\n sourceEditor: SlateEditor,\n { format = 'single' }: { format?: 'all' | 'none' | 'single' } = {}\n) => {\n if (!sourceEditor || sourceEditor.api.isEmpty()) return;\n\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n editor.getApi<AIChatPluginConfig>({ key: KEYS.ai }).aiChat.hide();\n\n // If no blocks selected, treat it like a normal selection replacement\n if (!isBlockSelecting) {\n const firstBlock = editor.api.node({\n block: true,\n mode: 'lowest',\n });\n\n if (\n firstBlock &&\n editor.api.isSelected(firstBlock[1], { contains: true }) &&\n format !== 'none'\n ) {\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: firstBlock,\n });\n\n if (!formattedBlocks) return;\n\n /** When user selection is cover the whole code block */\n if (\n firstBlock[0].type === KEYS.codeLine &&\n sourceEditor.children[0].type === KEYS.codeBlock &&\n sourceEditor.children.length === 1\n ) {\n editor.tf.insertFragment(formattedBlocks[0].children);\n } else {\n editor.tf.insertFragment(formattedBlocks);\n }\n\n editor.tf.focus();\n\n return;\n }\n\n editor.tf.insertFragment(sourceEditor.children);\n editor.tf.focus();\n\n return;\n }\n\n const blockSelectionApi = editor.getApi(BlockSelectionPlugin).blockSelection;\n const selectedBlocks = blockSelectionApi.getNodes();\n\n if (selectedBlocks.length === 0) return;\n // If format is 'none' or multiple blocks with 'single',\n // just insert the content as is\n if (format === 'none' || (format === 'single' && selectedBlocks.length > 1)) {\n editor.tf.withoutNormalizing(() => {\n removeBlockSelectionNodes(editor);\n\n editor.tf.withNewBatch(() => {\n editor\n .getTransforms(BlockSelectionPlugin)\n .blockSelection.insertBlocksAndSelect(\n cloneDeep(sourceEditor.children),\n {\n at: selectedBlocks[0][1],\n }\n );\n });\n });\n\n editor.getApi(BlockSelectionPlugin).blockSelection.focus();\n\n return;\n }\n\n // Apply formatting from first block when:\n // - formatting is 'all', or\n // - only one block is selected\n const [, firstBlockPath] = selectedBlocks[0];\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: selectedBlocks[0],\n });\n\n if (!formattedBlocks) return;\n\n editor.tf.withoutNormalizing(() => {\n removeBlockSelectionNodes(editor);\n\n editor.tf.withNewBatch(() => {\n editor\n .getTransforms(BlockSelectionPlugin)\n .blockSelection.insertBlocksAndSelect(formattedBlocks, {\n at: firstBlockPath,\n });\n });\n });\n\n editor.getApi(BlockSelectionPlugin).blockSelection.focus();\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport {\n type RemoveNodesOptions,\n ElementApi,\n getPluginType,\n KEYS,\n} from 'platejs';\n\nexport const removeAnchorAIChat = (\n editor: PlateEditor,\n options?: RemoveNodesOptions\n) => {\n editor.tf.withoutSaving(() => {\n editor.tf.removeNodes({\n at: [],\n match: (n) =>\n ElementApi.isElement(n) &&\n n.type === getPluginType(editor, KEYS.aiChat),\n ...options,\n });\n });\n};\n","import { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nimport { AIPlugin } from '../../ai/AIPlugin';\n\nexport const resetAIChat = (\n editor: PlateEditor,\n { undo = true }: { undo?: boolean } = {}\n) => {\n const { api, getOptions, setOptions } = getEditorPlugin<AIChatPluginConfig>(\n editor,\n {\n key: KEYS.aiChat,\n }\n );\n\n api.aiChat.stop();\n\n const chat = getOptions().chat;\n\n if (chat.messages && chat.messages.length > 0) {\n chat.setMessages?.([]);\n }\n\n setOptions({\n _replaceIds: [],\n chatNodes: [],\n mode: 'insert',\n toolName: 'generate',\n });\n\n if (undo) {\n editor.getTransforms(AIPlugin).ai.undo();\n }\n};\n","import type { ChatRequestOptions } from 'ai';\n\nimport { isSelecting } from '@platejs/selection';\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport { type Descendant, type Range, type TIdElement, KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { AIMode, AIToolName } from '../../../lib/types';\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nimport {\n type EditorPrompt,\n getEditorPrompt,\n} from '../../../lib/utils/getEditorPrompt';\nimport { AIPlugin } from '../../ai/AIPlugin';\n\nexport const submitAIChat = (\n editor: PlateEditor,\n input: string,\n {\n mode,\n options,\n prompt,\n toolName,\n }: {\n mode?: AIMode;\n options?: ChatRequestOptions;\n prompt?: EditorPrompt;\n toolName?: AIToolName;\n } = {}\n) => {\n const { getOptions, setOption } = getEditorPlugin<AIChatPluginConfig>(\n editor,\n {\n key: KEYS.aiChat,\n }\n );\n\n const { chat } = getOptions();\n\n if (!prompt && input?.length === 0) {\n return;\n }\n if (!prompt) {\n prompt = input;\n }\n if (!mode) {\n mode = isSelecting(editor) ? 'chat' : 'insert';\n }\n if (mode === 'insert') {\n editor.getTransforms(AIPlugin).ai.undo();\n }\n\n setOption('mode', mode);\n\n setOption('toolName', toolName ?? null);\n\n const blocks = editor.getApi(BlockSelectionPlugin).blockSelection.getNodes();\n const blocksRange = editor.api.nodesRange(blocks);\n\n const promptText = getEditorPrompt(editor, {\n prompt,\n });\n\n const selection = blocks.length > 0 ? blocksRange : editor.selection;\n\n const chatNodes =\n blocks.length > 0\n ? blocks.map((block) => block[0])\n : editor.api.fragment<TIdElement>();\n\n setOption('chatNodes', chatNodes);\n setOption('chatSelection', blocks.length > 0 ? null : editor.selection);\n\n const ctx: {\n children: Descendant[];\n selection: Range | null;\n toolName: string | null;\n } = {\n children: editor.children,\n selection: selection ?? null,\n toolName: toolName ?? null,\n };\n\n void chat.sendMessage?.(\n {\n text: promptText,\n },\n {\n body: {\n ctx,\n },\n ...options,\n }\n );\n};\n","import type { OverrideEditor } from 'platejs/react';\n\nimport { ElementApi, KEYS } from 'platejs';\n\nimport { AIPlugin } from '../ai/AIPlugin';\nimport { type AIChatPluginConfig, AIChatPlugin } from './AIChatPlugin';\n\nexport const withAIChat: OverrideEditor<AIChatPluginConfig> = ({\n api,\n editor,\n getOptions,\n tf: { apply, insertText, normalizeNode },\n type,\n}) => {\n const tf = editor.getTransforms(AIPlugin);\n\n const matchesTrigger = (text: string) => {\n const { trigger } = getOptions();\n\n if (trigger instanceof RegExp) {\n return trigger.test(text);\n }\n if (Array.isArray(trigger)) {\n return trigger.includes(text);\n }\n\n return text === trigger;\n };\n\n return {\n transforms: {\n insertText(text, options) {\n const { triggerPreviousCharPattern, triggerQuery } = getOptions();\n\n const fn = () => {\n if (\n !editor.selection ||\n !matchesTrigger(text) ||\n (triggerQuery && !triggerQuery(editor))\n ) {\n return;\n }\n\n // Make sure an input is created at the beginning of line or after a whitespace\n const previousChar = editor.api.string(\n editor.api.range('before', editor.selection)\n );\n\n const matchesPreviousCharPattern =\n triggerPreviousCharPattern?.test(previousChar);\n\n if (!matchesPreviousCharPattern) return;\n\n const nodeEntry = editor.api.block({ highest: true });\n\n if (!nodeEntry || !editor.api.isEmpty(nodeEntry[0])) return;\n\n api.aiChat.show();\n\n return true;\n };\n\n if (fn()) return;\n\n return insertText(text, options);\n },\n normalizeNode(entry) {\n const [node, path] = entry;\n\n if (node[KEYS.ai] && !getOptions().open) {\n tf.ai.removeMarks({ at: path });\n\n return;\n }\n\n if (\n ElementApi.isElement(node) &&\n node.type === type &&\n !getOptions().open\n ) {\n editor.getTransforms(AIChatPlugin).aiChat.removeAnchor({ at: path });\n\n return;\n }\n\n return normalizeNode(entry);\n },\n },\n };\n};\n","import { useEffect, useMemo } from 'react';\n\nimport type { SlateEditor } from 'platejs';\n\nimport { type DeserializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\nimport { useEditorPlugin } from 'platejs/react';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\n/**\n * Register an editor in the AI chat plugin, and deserializes the content into\n * `editor.children` with block-level memoization.\n */\nexport const useAIChatEditor = (\n editor: SlateEditor,\n content: string,\n { parser }: DeserializeMdOptions = {}\n) => {\n const { setOption } = useEditorPlugin(AIChatPlugin);\n\n editor.children = useMemo(\n () => {\n return editor.getApi(MarkdownPlugin).markdown.deserialize(content, {\n memoize: true,\n parser,\n });\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [content]\n );\n\n useEffect(() => {\n setOption('aiEditor', editor);\n }, [editor, setOption]);\n};\n","import { useEffect, useRef } from 'react';\n\nimport type { TText } from 'platejs';\n\nimport { KEYS } from 'platejs';\nimport { usePluginOption } from 'platejs/react';\n\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nimport { useLastAssistantMessage } from '../utils/getLastAssistantMessage';\n\nexport const useChatChunk = ({\n onChunk,\n onFinish,\n}: {\n onChunk: (chunk: {\n chunk: string;\n isFirst: boolean;\n nodes: TText[];\n text: string;\n }) => void;\n onFinish?: ({ content }: { content: string }) => void;\n}) => {\n const { status } = usePluginOption(\n { key: KEYS.aiChat } as AIChatPluginConfig,\n 'chat'\n );\n const isLoading = status === 'streaming' || status === 'submitted';\n\n const content = useLastAssistantMessage()?.parts.find(\n (part) => part.type === 'text'\n )?.text;\n\n const insertedTextRef = useRef<string>('');\n const prevIsLoadingRef = useRef(isLoading);\n\n useEffect(() => {\n if (!isLoading) {\n insertedTextRef.current = '';\n }\n if (prevIsLoadingRef.current && !isLoading) {\n onFinish?.({ content: content ?? '' });\n }\n\n prevIsLoadingRef.current = isLoading;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoading]);\n\n useEffect(() => {\n if (!content) {\n return;\n }\n\n const chunk = content.slice(insertedTextRef.current.length);\n\n const nodes: TText[] = [];\n\n if (chunk) {\n const isFirst = insertedTextRef.current === '';\n\n nodes.push({ text: chunk });\n onChunk({\n chunk,\n isFirst,\n nodes,\n text: content,\n });\n }\n\n insertedTextRef.current = content;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content]);\n};\n","import { type PlateEditor, usePluginOption } from 'platejs/react';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\nexport function getLastAssistantMessage(editor: PlateEditor) {\n const messages = editor.getOptions(AIChatPlugin).chat.messages;\n\n return messages?.findLast((message) => message.role === 'assistant');\n}\n\nexport function useLastAssistantMessage() {\n const toolName = usePluginOption(AIChatPlugin, 'toolName');\n const chat = usePluginOption(AIChatPlugin, 'chat');\n\n if (toolName === 'comment') return;\n\n return chat.messages?.findLast((message) => message.role === 'assistant');\n}\n","'use client';\n\nimport { useEffect } from 'react';\n\nimport type { UseChatHelpers } from '@ai-sdk/react';\nimport type { NodeEntry } from 'platejs';\n\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport { useEditorPlugin, usePluginOption } from 'platejs/react';\n\nimport type { ChatMessage } from '../internal/types';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\nexport type UseEditorChatOptions = {\n chat: UseChatHelpers<ChatMessage>;\n onOpenBlockSelection?: (blocks: NodeEntry[]) => void;\n onOpenChange?: (open: boolean) => void;\n onOpenCursor?: () => void;\n onOpenSelection?: () => void;\n};\n\nexport const useEditorChat = ({\n chat,\n onOpenBlockSelection,\n onOpenChange,\n onOpenCursor,\n onOpenSelection,\n}: UseEditorChatOptions) => {\n const { editor } = useEditorPlugin(AIChatPlugin);\n const open = usePluginOption(AIChatPlugin, 'open');\n\n useEffect(() => {\n onOpenChange?.(open);\n\n if (open) {\n if (onOpenBlockSelection) {\n const blockSelectionApi =\n editor.getApi(BlockSelectionPlugin).blockSelection;\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n if (isBlockSelecting) {\n onOpenBlockSelection(blockSelectionApi.getNodes());\n\n return;\n }\n }\n if (onOpenCursor && editor.api.isCollapsed()) {\n onOpenCursor();\n\n return;\n }\n if (onOpenSelection && editor.api.isExpanded()) {\n onOpenSelection();\n\n return;\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open]);\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type DeserializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\n\nexport const streamDeserializeInlineMd = (\n editor: PlateEditor,\n text: string,\n options?: DeserializeMdOptions\n) => {\n return editor\n .getApi(MarkdownPlugin)\n .markdown.deserializeInline(text, options);\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type DeserializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\nimport { type TElement, getPluginType, KEYS, TextApi } from 'platejs';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\nimport { getChunkTrimmed } from './utils';\nimport { escapeInput } from './utils/escapeInput';\n\nconst statMdxTagRegex = /<([A-Za-z][A-Za-z0-9._:-]*)(?:\\s[^>]*?)?(?<!\\/)>/;\n\nexport const streamDeserializeMd = (\n editor: PlateEditor,\n data: string,\n options?: DeserializeMdOptions\n) => {\n const input = escapeInput(data);\n\n const value = withoutDeserializeInMdx(editor, input);\n\n if (Array.isArray(value)) return value;\n\n let blocks = [];\n\n blocks = editor.getApi(MarkdownPlugin).markdown.deserialize(input, {\n ...options,\n preserveEmptyParagraphs: false,\n });\n\n const trimmedData = getChunkTrimmed(data);\n\n const lastBlock = blocks.at(-1) as TElement | undefined;\n\n const addNewLine = trimmedData === '\\n\\n';\n const unshiftNewLine =\n getChunkTrimmed(data, { direction: 'left' }) === '\\n\\n';\n\n const isCodeBlockOrTable =\n lastBlock?.type === 'code_block' || lastBlock?.type === 'table';\n\n let result = blocks;\n\n /**\n * Deserialize the sting like `123\\n\\n` will be `123` base on markdown spec\n * but we want to keep the `\\n\\n`\n */\n\n if (\n lastBlock &&\n !isCodeBlockOrTable &&\n trimmedData.length > 0 &&\n !addNewLine\n ) {\n const textNode = [\n {\n text: trimmedData,\n },\n ];\n\n const lastChild = lastBlock.children.at(-1);\n\n /** It’s like normalizing and merging the text nodes. */\n if (\n lastChild &&\n TextApi.isText(lastChild) &&\n Object.keys(lastChild).length === 1\n ) {\n lastBlock.children.pop();\n\n const textNode = [\n {\n text: lastChild.text + trimmedData,\n },\n ];\n\n lastBlock.children.push(...textNode);\n } else {\n lastBlock.children.push(...textNode);\n }\n\n result = [...blocks.slice(0, -1), lastBlock];\n }\n\n if (addNewLine && !isCodeBlockOrTable) {\n result.push({\n children: [{ text: '' }],\n type: KEYS.p,\n });\n }\n\n if (unshiftNewLine && !isCodeBlockOrTable) {\n result.unshift({\n children: [{ text: '' }],\n type: KEYS.p,\n });\n }\n\n return result;\n};\n\nconst withoutDeserializeInMdx = (editor: PlateEditor, input: string) => {\n const mdxName = editor.getOption(AIChatPlugin, '_mdxName');\n\n if (mdxName) {\n const isMdxEnd = input.includes(`</${mdxName}>`);\n\n if (isMdxEnd) {\n editor.setOption(AIChatPlugin, '_mdxName', null);\n return false;\n } else {\n return [\n {\n children: [\n {\n text: input,\n },\n ],\n type: getPluginType(editor, KEYS.p),\n },\n ];\n }\n } else {\n const newMdxName = statMdxTagRegex.exec(input)?.[1];\n\n // Avoid incorrect detection in the code block\n if (input.startsWith(`<${newMdxName}`)) {\n editor.setOption(AIChatPlugin, '_mdxName', newMdxName ?? null);\n }\n }\n};\n","export const getChunkTrimmed = (\n chunk: string,\n {\n direction = 'right',\n }: {\n direction?: 'left' | 'right';\n } = {}\n) => {\n const str = direction === 'right' ? chunk.trimEnd() : chunk.trimStart();\n\n if (direction === 'right') {\n return chunk.slice(str.length);\n } else {\n return chunk.slice(0, chunk.length - str.length);\n }\n};\n\nexport function isCompleteCodeBlock(str: string) {\n const trimmed = str.trim();\n\n const startsWithCodeBlock = trimmed.startsWith('```');\n const endsWithCodeBlock = trimmed.endsWith('```');\n\n return startsWithCodeBlock && endsWithCodeBlock;\n}\n\nexport function isCompleteMath(str: string) {\n const trimmed = str.trim();\n\n const startsWithMath = trimmed.startsWith('$$');\n const endsWithMath = trimmed.endsWith('$$');\n\n return startsWithMath && endsWithMath;\n}\n","import { isCompleteMath } from './utils';\n\nexport const escapeInput = (data: string) => {\n let res = data;\n\n // test case: should correctly handle inline math\n if (\n data.startsWith('$$') &&\n !data.startsWith('$$\\n') &&\n !isCompleteMath(data)\n ) {\n res = data.replace('$$', String.raw`\\$\\$`);\n }\n\n return res;\n};\n","import type { TElement } from 'platejs';\nimport type { PlateEditor } from 'platejs/react';\n\nexport const getListNode = (editor: PlateEditor, node: TElement): TElement => {\n if (node.listStyleType && node.listStart) {\n const previousNode = editor.api.previous({\n at: editor.selection?.focus,\n })?.[0];\n\n // if previous node is also an indent list, don't need to do additional work\n if (previousNode?.listStyleType && previousNode?.listStart) {\n return node;\n } else {\n if (node.listStart === 1) return node;\n\n return {\n ...node,\n listRestartPolite: node.listStart,\n };\n }\n }\n\n return node;\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type TElement, type TText, isDefined, KEYS } from 'platejs';\n\nconst LIST_STYLE_TYPE = 'listStyleType';\n\nexport const isSameNode = (\n editor: PlateEditor,\n node1: TElement | TText,\n node2: TElement | TText\n) => {\n if (\n node1.type !== editor.getType(KEYS.p) ||\n node2.type !== editor.getType(KEYS.p)\n )\n return node1.type === node2.type;\n\n if (isDefined(node1[LIST_STYLE_TYPE]) || isDefined(node2[LIST_STYLE_TYPE])) {\n return node1[LIST_STYLE_TYPE] === node2[LIST_STYLE_TYPE];\n }\n\n return node1.type === node2.type;\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type Descendant, ElementApi } from 'platejs';\n\nimport type { SteamInsertChunkOptions } from '../streamInsertChunk';\n\nimport { getListNode } from './getListNode';\n\nexport const nodesWithProps = (\n editor: PlateEditor,\n nodes: Descendant[],\n options: SteamInsertChunkOptions\n): Descendant[] => {\n return nodes.map((node): Descendant => {\n if (ElementApi.isElement(node)) {\n return {\n ...getListNode(editor, node),\n ...options.elementProps,\n children: nodesWithProps(editor, node.children, options),\n };\n } else {\n return {\n ...options.textProps,\n ...node,\n text: node.text,\n };\n }\n });\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport {\n type Path,\n type SlateEditor,\n getPluginType,\n KEYS,\n NodeApi,\n PathApi,\n} from 'platejs';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\nimport { streamDeserializeInlineMd } from './streamDeserializeInlineMd';\nimport { streamDeserializeMd } from './streamDeserializeMd';\nimport { streamSerializeMd } from './streamSerializeMd';\nimport { isSameNode } from './utils/isSameNode';\nimport { nodesWithProps } from './utils/nodesWithProps';\n\nexport interface SteamInsertChunkOptions {\n elementProps?: any;\n textProps?: any;\n}\n\nconst getNextPath = (path: Path, length: number) => {\n let result = path;\n\n for (let i = 0; i < length; i++) {\n result = PathApi.next(result);\n }\n return result;\n};\n\n/** @experimental */\nexport function streamInsertChunk(\n editor: PlateEditor,\n chunk: string,\n options: SteamInsertChunkOptions = {}\n) {\n const { _blockChunks, _blockPath } = editor.getOptions(AIChatPlugin);\n\n if (_blockPath === null) {\n const blocks = streamDeserializeMd(editor, chunk);\n const path = getCurrentBlockPath(editor);\n const startBlock = editor.api.node(path)![0];\n\n const startInEmptyParagraph =\n NodeApi.string(startBlock).length === 0 &&\n startBlock.type === getPluginType(editor, KEYS.p);\n\n // if start in empty paragraph, remove it\n if (startInEmptyParagraph) {\n editor.tf.removeNodes({ at: path });\n }\n\n if (blocks.length > 0) {\n editor.tf.insertNodes(nodesWithProps(editor, [blocks[0]], options), {\n at: path,\n nextBlock: !startInEmptyParagraph,\n select: true,\n });\n\n editor.setOption(AIChatPlugin, '_blockPath', getCurrentBlockPath(editor));\n editor.setOption(AIChatPlugin, '_blockChunks', chunk);\n\n if (blocks.length > 1) {\n const nextBlocks = blocks.slice(1);\n\n const nextPath = getCurrentBlockPath(editor);\n\n editor.tf.insertNodes(nodesWithProps(editor, nextBlocks, options), {\n at: nextPath,\n nextBlock: true,\n select: true,\n });\n\n const lastBlock = editor.api.node(\n getNextPath(nextPath, nextBlocks.length)\n )!;\n\n editor.setOption(AIChatPlugin, '_blockPath', lastBlock[1]);\n\n const lastBlockChunks = streamSerializeMd(\n editor,\n {\n value: [lastBlock[0]],\n },\n chunk\n );\n\n editor.setOption(AIChatPlugin, '_blockChunks', lastBlockChunks);\n }\n }\n } else {\n const tempBlockChunks = _blockChunks + chunk;\n const tempBlocks = streamDeserializeMd(editor, tempBlockChunks);\n\n // console.log(\n // JSON.stringify(chunk),\n // 'chunk',\n // '-------------------------------------------------------------------------------------------'\n // );\n // console.log(\n // '🚀 ~ Streaming ~ tempBlockChunks:',\n // JSON.stringify(tempBlockChunks)\n // );\n\n // console.log('🚀 ~ Streaming ~ tempBlocks:', JSON.stringify(tempBlocks));\n\n if (tempBlocks.length === 0) {\n return console.warn(\n `unsupport md nodes: ${JSON.stringify(tempBlockChunks)}`\n );\n }\n\n if (tempBlocks.length === 1) {\n const currentBlock = editor.api.node(_blockPath)![0];\n\n // If the types are the same\n if (isSameNode(editor, currentBlock, tempBlocks[0])) {\n const chunkNodes = streamDeserializeInlineMd(editor as any, chunk);\n\n // Deserialize the chunk and add it to the end of the current block\n editor.tf.insertNodes(nodesWithProps(editor, chunkNodes, options), {\n at: editor.api.end(_blockPath),\n select: true,\n });\n\n const updatedBlock = editor.api.node(_blockPath)!;\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [updatedBlock[0]],\n },\n tempBlockChunks\n );\n\n const blockText = NodeApi.string(tempBlocks[0]);\n\n // Verify if the editor content matches the chunk\n if (\n serializedBlock === tempBlockChunks &&\n blockText === serializedBlock\n ) {\n editor.setOption(AIChatPlugin, '_blockChunks', tempBlockChunks);\n } else {\n editor.tf.replaceNodes(\n nodesWithProps(editor, [tempBlocks[0]], options),\n {\n at: _blockPath,\n select: true,\n }\n );\n\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [tempBlocks[0]],\n },\n tempBlockChunks\n );\n\n editor.setOption(\n AIChatPlugin,\n '_blockChunks',\n // one block includes multiple children\n tempBlocks[0].type === getPluginType(editor, KEYS.codeBlock) ||\n tempBlocks[0].type === getPluginType(editor, KEYS.table) ||\n tempBlocks[0].type === getPluginType(editor, KEYS.equation)\n ? tempBlockChunks\n : serializedBlock\n );\n }\n } else {\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [tempBlocks[0]],\n },\n tempBlockChunks\n );\n\n editor.tf.replaceNodes(\n nodesWithProps(editor, [tempBlocks[0]], options),\n {\n at: _blockPath,\n select: true,\n }\n );\n\n editor.setOption(AIChatPlugin, '_blockChunks', serializedBlock);\n }\n } else {\n editor.tf.replaceNodes(nodesWithProps(editor, [tempBlocks[0]], options), {\n at: _blockPath,\n select: true,\n });\n\n if (tempBlocks.length > 1) {\n const newEndBlockPath = getNextPath(_blockPath, tempBlocks.length - 1);\n\n editor.tf.insertNodes(\n nodesWithProps(editor, tempBlocks.slice(1), options),\n {\n at: PathApi.next(_blockPath),\n select: true,\n }\n );\n\n editor.setOption(AIChatPlugin, '_blockPath', newEndBlockPath);\n\n const endBlock = editor.api.node(newEndBlockPath)![0];\n\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [endBlock],\n },\n tempBlockChunks\n );\n\n editor.setOption(AIChatPlugin, '_blockChunks', serializedBlock);\n }\n }\n }\n}\n\nexport const getCurrentBlockPath = (editor: SlateEditor) => {\n const getAnchorPreviousPath = (editor: SlateEditor): Path | undefined => {\n const anchorNode = editor\n .getApi(AIChatPlugin)\n .aiChat.node({ anchor: true });\n\n if (anchorNode) {\n return PathApi.previous(anchorNode[1])!;\n }\n };\n\n const getFocusPath = (editor: SlateEditor): Path | undefined => {\n return editor.selection?.focus.path.slice(0, 1);\n };\n\n const path = getAnchorPreviousPath(editor) ?? getFocusPath(editor) ?? [0];\n\n const entry = editor.api.node(path);\n\n // streaming in table or columns shouldn't remove them\n if (\n entry &&\n (entry[0].type === getPluginType(editor, KEYS.columnGroup) ||\n entry[0].type === getPluginType(editor, KEYS.table))\n ) {\n return editor.api.above()?.[1] ?? path;\n }\n\n return path;\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type SerializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\nimport {\n type Descendant,\n ElementApi,\n getPluginKey,\n KEYS,\n TextApi,\n} from 'platejs';\n\nimport {\n getChunkTrimmed,\n isCompleteCodeBlock,\n isCompleteMath,\n} from './utils/utils';\n\n// fixes test: should serialize heading with tailing line break\n// fixes test: incomplete line breaks\nconst trimEndHeading = (\n editor: PlateEditor,\n value: Descendant[]\n): { trimmedText: string; value: Descendant[] } => {\n const headingKeys = new Set([\n KEYS.h1,\n KEYS.h2,\n KEYS.h3,\n KEYS.h4,\n KEYS.h5,\n KEYS.h6,\n ]);\n const lastBlock = value.at(-1);\n\n if (\n lastBlock &&\n headingKeys.has(\n (getPluginKey(editor, lastBlock.type as string) ?? lastBlock.type) as any\n ) &&\n ElementApi.isElement(lastBlock)\n ) {\n const lastTextNode = lastBlock.children.at(-1);\n\n if (TextApi.isText(lastTextNode)) {\n const trimmedText = getChunkTrimmed(lastTextNode?.text as string);\n\n // Create a new lastBlock with immutable operations\n const newChildren = [\n ...lastBlock.children.slice(0, -1),\n { text: lastTextNode.text.trimEnd() },\n ];\n\n const newLastBlock = {\n ...lastBlock,\n children: newChildren,\n };\n\n return {\n trimmedText: trimmedText,\n value: [...value.slice(0, -1), newLastBlock],\n };\n }\n }\n\n return { trimmedText: '', value };\n};\n\nexport const streamSerializeMd = (\n editor: PlateEditor,\n options: SerializeMdOptions,\n chunk: string\n) => {\n const { value: optionsValue, ...restOptions } = options;\n const { value } = trimEndHeading(editor, optionsValue ?? editor.children);\n\n let result = '';\n\n result = editor.getApi(MarkdownPlugin).markdown.serialize({\n value: value,\n ...restOptions,\n });\n\n const trimmedChunk = getChunkTrimmed(chunk);\n\n if (isCompleteCodeBlock(result) && !chunk.endsWith('```')) {\n result = result.trimEnd().slice(0, -3) + trimmedChunk;\n }\n\n if (isCompleteMath(result) && !chunk.endsWith('$$')) {\n result = result.trimEnd().slice(0, -3) + trimmedChunk;\n }\n\n // clean HTML spaces and zero-width characters\n result = result.replace(/ /g, ' ');\n result = result.replace(/​/g, ' ');\n result = result.replace(/\\u200B/g, '');\n\n // remove extra \\n but not include \\n itself\n // FIXME maybe failed when chunk is more than two'\\n'\n if (trimmedChunk !== '\\n\\n') {\n result = result.trimEnd() + trimmedChunk;\n }\n\n // Handle empty paragraph case for streaming\n if (chunk.endsWith('\\n\\n')) {\n if (result === '\\n') {\n // Single empty paragraph case\n result = '';\n } else if (result.endsWith('\\n\\n')) {\n // Multiple paragraphs ending with empty paragraph\n result = result.slice(0, -1);\n }\n }\n\n // replace   to real space\n\n // remove Markdown escape characters (including those potentially added in the chunk)\n result = result.replace(/\\\\([\\\\`*_{}\\\\[\\]()#+\\-\\\\.!~<>|$])/g, '$1');\n\n return result;\n};\n","import { deserializeMd } from '@platejs/markdown';\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport {\n diffToSuggestions,\n getTransientSuggestionKey,\n SkipSuggestionDeletes,\n} from '@platejs/suggestion';\nimport {\n type Descendant,\n type SlateEditor,\n type TElement,\n type TIdElement,\n type TSuggestionData,\n type TSuggestionElement,\n ElementApi,\n KEYS,\n nanoid,\n TextApi,\n} from 'platejs';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\nexport const applyAISuggestions = (editor: SlateEditor, content: string) => {\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n const { chatNodes } = editor.getOptions(AIChatPlugin);\n\n if (isBlockSelecting) {\n const setReplaceIds = (ids: string[]) => {\n editor.setOption(AIChatPlugin, '_replaceIds', ids);\n };\n\n if (editor.getOption(AIChatPlugin, '_replaceIds').length === 0) {\n setReplaceIds(chatNodes.map((node) => node.id as string));\n }\n\n const diffNodes = getDiffNodes(editor, content);\n\n const replaceNodes = Array.from(\n editor.api.nodes<TIdElement>({\n at: [],\n match: (n: TIdElement) =>\n ElementApi.isElement(n) &&\n editor.getOption(AIChatPlugin, '_replaceIds').includes(n.id),\n })\n );\n\n replaceNodes.forEach(([node, path], index) => {\n const replaceNode = node as unknown as TSuggestionElement;\n const diffNode = diffNodes[index] as unknown as TSuggestionElement;\n\n const isSameString =\n SkipSuggestionDeletes(editor, replaceNode) ===\n SkipSuggestionDeletes(editor, diffNode);\n\n const isSameSuggestion =\n (replaceNode.suggestion as TSuggestionData | undefined)?.type ===\n (diffNode.suggestion as TSuggestionData | undefined)?.type;\n\n if (isSameString && isSameSuggestion && node.id == diffNode.id) {\n return;\n }\n\n if (\n index === replaceNodes.length - 1 &&\n diffNodes.length > replaceNodes.length\n ) {\n editor.tf.replaceNodes(diffNodes.slice(index), {\n at: path,\n });\n } else {\n editor.tf.replaceNodes(diffNode, {\n at: path,\n });\n }\n });\n\n editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.set(diffNodes.map((node) => node.id as string));\n setReplaceIds(diffNodes.map((node) => node.id as string));\n } else {\n const diffNodes = getDiffNodes(editor, content);\n\n editor.tf.insertFragment(diffNodes);\n\n const nodes = editor.api.nodes({\n at: [],\n mode: 'lowest',\n match: (n) => TextApi.isText(n) && !!n[getTransientSuggestionKey()],\n });\n\n const range = editor.api.nodesRange(Array.from(nodes));\n\n editor.tf.setSelection(range!);\n\n return;\n }\n};\n\nconst withProps = (\n diffNodes: Descendant[],\n chatNodes: Descendant[]\n): Descendant[] => {\n return diffNodes.map((node, index) => {\n if (!ElementApi.isElement(node)) return node;\n\n const originalNode = chatNodes?.[index] as TElement | undefined;\n\n return {\n ...node,\n ...(originalNode ?? { id: nanoid() }),\n children: node.children,\n };\n });\n};\n\nconst withTransient = (diffNodes: Descendant[]): Descendant[] => {\n return diffNodes.map((node) => {\n if (TextApi.isText(node)) {\n return {\n ...node,\n [getTransientSuggestionKey()]: true,\n };\n } else {\n return {\n ...node,\n children: withTransient(node.children),\n [getTransientSuggestionKey()]: true,\n };\n }\n });\n};\n\nconst withoutSuggestionAndComments = (nodes: Descendant[]): Descendant[] => {\n return nodes.map((node) => {\n if (TextApi.isText(node)) {\n if (node[KEYS.suggestion] || node[KEYS.comment]) {\n return {\n text: node.text,\n };\n }\n\n return node;\n }\n\n if (ElementApi.isElement(node)) {\n if (node[KEYS.suggestion]) {\n const nodeWithoutSuggestion: any = {};\n\n Object.keys(node).forEach((key) => {\n if (key !== KEYS.suggestion && !key.startsWith(KEYS.suggestion)) {\n nodeWithoutSuggestion[key] = node[key];\n }\n });\n\n return {\n ...nodeWithoutSuggestion,\n children: withoutSuggestionAndComments(node.children),\n };\n }\n\n return {\n ...node,\n children: withoutSuggestionAndComments(node.children),\n };\n }\n\n return node;\n });\n};\nconst getDiffNodes = (editor: SlateEditor, aiContent: string) => {\n /** Original document nodes */\n const chatNodes = withoutSuggestionAndComments(\n editor.getOption(AIChatPlugin, 'chatNodes')\n );\n\n const aiNodes = withProps(deserializeMd(editor, aiContent), chatNodes);\n\n const diffNodes = withTransient(\n diffToSuggestions(editor, chatNodes, aiNodes, { ignoreProps: ['id'] })\n );\n\n return diffNodes;\n};\n","'use client';\n\nimport type React from 'react';\n\nimport type { DebouncedFunc } from 'lodash';\n\nimport { serializeMd } from '@platejs/markdown';\nimport debounce from 'lodash/debounce.js';\nimport {\n type OmitFirst,\n type PluginConfig,\n type TElement,\n bindFirst,\n KEYS,\n NodeApi,\n} from 'platejs';\nimport { type PlateEditor, createTPlatePlugin } from 'platejs/react';\n\nimport type { CompleteOptions } from './utils/callCompletionApi';\n\nimport { renderCopilotBelowNodes } from './renderCopilotBelowNodes';\nimport { acceptCopilot } from './transforms/acceptCopilot';\nimport { acceptCopilotNextWord } from './transforms/acceptCopilotNextWord';\nimport { type GetNextWord, getNextWord } from './utils/getNextWord';\nimport { triggerCopilotSuggestion } from './utils/triggerCopilotSuggestion';\nimport { withCopilot } from './withCopilot';\n\nexport type CopilotPluginConfig = PluginConfig<\n 'copilot',\n CompletionState & {\n /**\n * AI completion options. See:\n * {@link https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion#parameters | AI SDK UI useCompletion Parameters}\n */\n completeOptions?: Partial<CompleteOptions>;\n /**\n * Debounce delay for auto triggering AI completion.\n *\n * @default 0\n */\n debounceDelay?: number;\n /** Get the next word to be inserted. */\n getNextWord?: GetNextWord;\n /** Render the ghost text. */\n renderGhostText?: (() => React.ReactNode) | null;\n shouldAbort?: boolean;\n /** The node id where the suggestion is located. */\n suggestionNodeId?: string | null;\n /** The text of the suggestion. */\n suggestionText?: string | null;\n /**\n * Conditions to auto trigger copilot, used in addition to triggerQuery.\n * Disabling defaults to:\n *\n * - Block above is empty\n * - Block above ends with a space\n * - There is already a suggestion\n */\n autoTriggerQuery?: (options: { editor: PlateEditor }) => boolean;\n /**\n * Get the prompt for AI completion.\n *\n * @default serializeMdNodes(editor.api.block({ highest: true }))\n */\n getPrompt?: (options: { editor: PlateEditor }) => string;\n /**\n * Conditions to trigger copilot. Disabling defaults to:\n *\n * - Selection is expanded\n * - Selection is not at the end of block\n */\n triggerQuery?: (options: { editor: PlateEditor }) => boolean;\n // query?: QueryEditorOptions;\n },\n {\n copilot: {\n triggerSuggestion: OmitFirst<typeof triggerCopilotSuggestion>;\n // Function to abort the current API request and reject the completion state.\n reject: () => false | undefined;\n setBlockSuggestion: (options: { text: string; id?: string }) => void;\n // Function to abort the current API request.\n stop: () => void;\n };\n },\n {\n copilot: {\n accept: OmitFirst<typeof acceptCopilot>;\n acceptNextWord: OmitFirst<typeof acceptCopilotNextWord>;\n };\n },\n {\n isSuggested?: (id: string) => boolean;\n }\n>;\n\ntype CompletionState = {\n abortController?: AbortController | null;\n // The current text completion.\n completion?: string | null;\n // The error thrown during the completion process, if any.\n error?: Error | null;\n // Boolean flag indicating whether a fetch operation is currently in progress.\n isLoading?: boolean;\n};\n\nexport const CopilotPlugin = createTPlatePlugin<CopilotPluginConfig>({\n key: KEYS.copilot,\n handlers: {\n onBlur: ({ api }) => {\n api.copilot.reject();\n },\n onMouseDown: ({ api }) => {\n api.copilot.reject();\n },\n },\n options: {\n abortController: null,\n completeOptions: {},\n completion: '',\n debounceDelay: 0,\n error: null,\n getNextWord: getNextWord,\n isLoading: false,\n renderGhostText: null,\n shouldAbort: true,\n suggestionNodeId: null,\n suggestionText: null,\n autoTriggerQuery: ({ editor }) => {\n if (\n editor.getOptions<CopilotPluginConfig>({ key: KEYS.copilot })\n .suggestionText\n ) {\n return false;\n }\n\n const isEmpty = editor.api.isEmpty(editor.selection, { block: true });\n\n if (isEmpty) return false;\n\n const blockAbove = editor.api.block();\n\n if (!blockAbove) return false;\n\n const blockString = NodeApi.string(blockAbove[0]);\n\n return blockString.at(-1) === ' ';\n },\n getPrompt: ({ editor }) => {\n const contextEntry = editor.api.block({ highest: true });\n\n if (!contextEntry) return '';\n\n return serializeMd(editor, {\n value: [contextEntry[0] as TElement],\n });\n },\n triggerQuery: ({ editor }) => {\n if (editor.api.isExpanded()) return false;\n\n const isEnd = editor.api.isAt({ end: true });\n\n if (!isEnd) return false;\n\n return true;\n },\n },\n})\n .overrideEditor(withCopilot)\n .extendSelectors<CopilotPluginConfig['selectors']>(({ getOptions }) => ({\n isSuggested: (id) => getOptions().suggestionNodeId === id,\n }))\n .extendTransforms(({ editor }) => ({\n accept: bindFirst(acceptCopilot, editor),\n acceptNextWord: bindFirst(acceptCopilotNextWord, editor),\n }))\n .extendApi<Omit<CopilotPluginConfig['api']['copilot'], 'reject'>>(\n ({ api, editor, getOptions, setOption, setOptions }) => {\n const debounceDelay = getOptions().debounceDelay;\n\n let triggerSuggestion = bindFirst(triggerCopilotSuggestion, editor);\n\n if (debounceDelay) {\n triggerSuggestion = debounce(\n bindFirst(triggerCopilotSuggestion, editor),\n debounceDelay\n ) as any;\n }\n\n return {\n triggerSuggestion,\n setBlockSuggestion: ({ id = getOptions().suggestionNodeId, text }) => {\n if (!id) {\n id = editor.api.block()![0].id as string;\n }\n\n setOptions({\n suggestionNodeId: id,\n suggestionText: text,\n });\n },\n stop: () => {\n const { abortController } = getOptions();\n\n (api.copilot.triggerSuggestion as DebouncedFunc<any>)?.cancel();\n\n if (abortController) {\n abortController.abort();\n setOption('abortController', null);\n }\n },\n };\n }\n )\n .extendApi(({ api, getOptions, setOptions }) => ({\n reject: () => {\n if (!getOptions().suggestionText?.length) return false;\n\n api.copilot.stop();\n\n setOptions({\n completion: null,\n suggestionNodeId: null,\n suggestionText: null,\n });\n },\n }))\n .extend({\n render: {\n belowNodes: renderCopilotBelowNodes,\n },\n shortcuts: {\n accept: {\n keys: 'tab',\n },\n reject: {\n keys: 'escape',\n },\n },\n });\n","'use client';\n\nimport React from 'react';\n\nimport { KEYS } from 'platejs';\nimport { type RenderNodeWrapperProps, getEditorPlugin } from 'platejs/react';\n\nimport type { CopilotPluginConfig } from './CopilotPlugin';\n\nexport const renderCopilotBelowNodes = ({\n editor,\n}: RenderNodeWrapperProps<CopilotPluginConfig>) => {\n const copilot = getEditorPlugin<CopilotPluginConfig>(editor, {\n key: KEYS.copilot,\n });\n\n const { renderGhostText: GhostText } = copilot.getOptions();\n\n if (!GhostText) return;\n\n return ({ children }: { children: React.ReactNode }) => {\n return (\n <React.Fragment>\n {children}\n\n <GhostText />\n </React.Fragment>\n );\n };\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { deserializeInlineMd } from '@platejs/markdown';\nimport { KEYS } from 'platejs';\n\nimport type { CopilotPluginConfig } from '../CopilotPlugin';\n\nexport const acceptCopilot = (editor: PlateEditor) => {\n const { suggestionText } = editor.getOptions<CopilotPluginConfig>({\n key: KEYS.copilot,\n });\n\n if (!suggestionText?.length) return false;\n\n editor.tf.insertFragment(deserializeInlineMd(editor, suggestionText));\n};\n","import { deserializeInlineMd } from '@platejs/markdown';\nimport { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { CopilotPluginConfig } from '../CopilotPlugin';\n\nimport { withoutAbort } from '../utils';\n\nexport const acceptCopilotNextWord = (editor: PlateEditor) => {\n const { api, getOptions } = getEditorPlugin<CopilotPluginConfig>(editor, {\n key: KEYS.copilot,\n });\n\n const { getNextWord, suggestionText } = getOptions();\n\n if (!suggestionText?.length) {\n return false;\n }\n\n const { firstWord, remainingText } = getNextWord!({ text: suggestionText });\n\n api.copilot.setBlockSuggestion({\n text: remainingText,\n });\n\n withoutAbort(editor, () => {\n editor.tf.insertFragment(deserializeInlineMd(editor, firstWord));\n });\n};\n","// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type CallCompletionApiOptions = {\n prompt: string;\n api?: string;\n body?: Record<string, any>;\n credentials?: RequestCredentials | undefined;\n fetch?: ReturnType<typeof getOriginalFetch> | undefined;\n headers?: HeadersInit | undefined;\n setAbortController?: (abortController: AbortController | null) => void;\n setCompletion?: (completion: string) => void;\n setError?: (error: Error | null) => void;\n setLoading?: (loading: boolean) => void;\n onError?: ((error: Error) => void) | undefined;\n onFinish?: ((prompt: string, completion: string) => void) | undefined;\n onResponse?: ((response: Response) => Promise<void> | void) | undefined;\n};\n\nexport type CompleteOptions = Omit<\n CallCompletionApiOptions,\n 'setAbortController' | 'setCompletion' | 'setError' | 'setLoading'\n>;\n\n// https://github.com/vercel/ai/blob/main/packages/ui-utils/src/call-completion-api.ts\n// https://github.com/vercel/ai/blob/642ba22ee33723f3aae9669c7e075322cffca2f3/packages/react/src/use-completion.ts\nexport async function callCompletionApi({\n api = '/api/completion',\n body,\n credentials,\n fetch = getOriginalFetch(),\n headers,\n prompt,\n setAbortController = () => {},\n setCompletion = () => {},\n setError = () => {},\n setLoading = () => {},\n onError,\n onFinish,\n onResponse,\n}: CallCompletionApiOptions) {\n try {\n setLoading(true);\n setError(null);\n\n const abortController = new AbortController();\n setAbortController(abortController);\n\n // Empty the completion immediately.\n setCompletion('');\n\n const res = await fetch(api, {\n body: JSON.stringify({\n prompt,\n ...body,\n }),\n credentials,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: 'POST',\n signal: abortController.signal,\n }).catch((error) => {\n throw error;\n });\n\n if (onResponse) {\n await onResponse(res);\n }\n if (!res.ok) {\n throw new Error(\n (await res.text()) || 'Failed to fetch the chat response.'\n );\n }\n if (!res.body) {\n throw new Error('The response body is empty.');\n }\n\n const { text } = await res.json();\n\n if (!text) {\n throw new Error('The response does not contain a text field.');\n }\n\n setCompletion(text);\n\n if (onFinish) {\n onFinish(prompt, text);\n }\n\n setAbortController(null);\n\n return text as string;\n } catch (error) {\n // Ignore abort errors as they are expected.\n if ((error as any).name === 'AbortError') {\n setAbortController(null);\n\n return null;\n }\n if (error instanceof Error && onError) {\n onError(error);\n }\n\n setError(error as Error);\n } finally {\n setLoading(false);\n }\n}\n","export type GetNextWord = (options: { text: string }) => {\n firstWord: string;\n remainingText: string;\n};\n\nexport const getNextWord: GetNextWord = ({ text }) => {\n if (!text) return { firstWord: '', remainingText: '' };\n\n // Check if the first non-space character is a CJK character\n const nonSpaceMatch = /^\\s*(\\S)/.exec(text);\n\n if (!nonSpaceMatch) return { firstWord: '', remainingText: '' };\n\n const firstNonSpaceChar = nonSpaceMatch[1];\n\n // Regular expression for matching CJK characters\n // 1. [\\u4E00-\\u9FA5] - Chinese Characters\n // 2. [\\u3040-\\u309F] - Japanese Hiragana\n // 3. [\\u30A0-\\u30FF] - Japanese Katakana\n // 4. [\\u3400-\\u4DBF] - CJK Extension A\n // 5. [\\u4E00-\\u9FFF] - CJK Unified Ideographs\n // 6. [\\uF900-\\uFAFF] - CJK Compatibility Ideographs\n // 7. [\\uAC00-\\uD7AF] - Korean Syllables\n // 8. [\\u1100-\\u11FF] - Korean Jamo\n const isCJKChar =\n /[\\u1100-\\u11FF\\u3040-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF]/.test(\n firstNonSpaceChar\n );\n\n let firstWord, remainingText;\n\n if (isCJKChar) {\n // CJK characters: match leading spaces + first character + optional punctuation\n const match =\n /^(\\s*)([\\u1100-\\u11FF\\u3040-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF])([\\u3000-\\u303F\\uFF00-\\uFFEF])?/.exec(\n text\n );\n\n if (match) {\n const [fullMatch, spaces = '', char = '', punctuation = ''] = match;\n firstWord = spaces + char + punctuation;\n remainingText = text.slice(firstWord.length);\n } else {\n firstWord = '';\n remainingText = text;\n }\n } else {\n // For non-CJK text (including mixed content), match until space or CJK char\n const match =\n /^(\\s*\\S+?)(?=[\\s\\u1100-\\u11FF\\u3040-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF]|$)/.exec(\n text\n );\n\n if (match) {\n firstWord = match[0];\n remainingText = text.slice(firstWord.length);\n } else {\n firstWord = text;\n remainingText = '';\n }\n }\n\n return { firstWord, remainingText };\n};\n","import { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { CopilotPluginConfig } from '../CopilotPlugin';\n\nimport { callCompletionApi } from './callCompletionApi';\n\nexport const triggerCopilotSuggestion = async (editor: PlateEditor) => {\n const { api, getOptions, setOption } = getEditorPlugin<CopilotPluginConfig>(\n editor,\n {\n key: KEYS.copilot,\n }\n );\n\n const { completeOptions, getPrompt, isLoading, triggerQuery } = getOptions();\n\n if (isLoading || editor.getOptions({ key: KEYS.aiChat }).chat?.isLoading) {\n return false;\n }\n if (!triggerQuery!({ editor })) return false;\n\n // if (query && !queryEditor(editor, query)) return;\n\n const prompt = getPrompt!({ editor });\n\n if (prompt.length === 0) return false;\n\n api.copilot.stop();\n\n await callCompletionApi({\n prompt,\n onFinish: (_, completion) => {\n api.copilot.setBlockSuggestion({ text: completion });\n },\n ...completeOptions,\n setAbortController: (controller) =>\n setOption('abortController', controller),\n setCompletion: (completion) => setOption('completion', completion),\n setError: (error) => setOption('error', error),\n setLoading: (loading) => setOption('isLoading', loading),\n onError: (error) => {\n setOption('error', error);\n completeOptions?.onError?.(error);\n },\n });\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { CopilotPlugin } from '..';\n\nexport const withoutAbort = (editor: PlateEditor, fn: () => void) => {\n editor.setOption(CopilotPlugin, 'shouldAbort', false);\n fn();\n editor.setOption(CopilotPlugin, 'shouldAbort', true);\n};\n","import type { OverrideEditor, PlateEditor } from 'platejs/react';\n\nimport { serializeInlineMd } from '@platejs/markdown';\nimport {\n type Operation,\n type SlateEditor,\n type TRange,\n RangeApi,\n} from 'platejs';\n\nimport type { CopilotPluginConfig } from './CopilotPlugin';\n\nimport { withoutAbort } from './utils/withoutAbort';\n\ntype CopilotBatch = PlateEditor['history']['undos'][number] & {\n shouldAbort: boolean;\n};\n\nconst getPatchString = (editor: SlateEditor, operations: Operation[]) => {\n let string = '';\n\n for (const operation of operations) {\n if (operation.type === 'insert_node') {\n const node = operation.node;\n const text = serializeInlineMd(editor, { value: [node] });\n string += text;\n } else if (operation.type === 'insert_text') {\n string += operation.text;\n }\n }\n\n return string;\n};\n\nexport const withCopilot: OverrideEditor<CopilotPluginConfig> = ({\n api,\n editor,\n getOptions,\n setOption,\n tf: { apply, insertText, redo, setSelection, undo, writeHistory },\n}) => {\n let prevSelection: TRange | null = null;\n\n return {\n transforms: {\n apply(operation) {\n const { shouldAbort } = getOptions();\n\n if (shouldAbort) {\n api.copilot.reject();\n }\n\n apply(operation);\n },\n insertText(text, options) {\n const suggestionText = getOptions().suggestionText;\n\n // When using IME input, it's possible to enter two characters at once.\n if (suggestionText?.startsWith(text)) {\n withoutAbort(editor, () => {\n editor.tf.withoutMerging(() => {\n const newText = suggestionText?.slice(text.length);\n setOption('suggestionText', newText);\n insertText(text);\n });\n });\n\n return;\n }\n\n insertText(text, options);\n },\n\n redo() {\n if (!getOptions().suggestionText) return redo();\n\n const topRedo = editor.history.redos.at(-1) as CopilotBatch;\n const prevSuggestion = getOptions().suggestionText;\n\n if (topRedo && topRedo.shouldAbort === false && prevSuggestion) {\n withoutAbort(editor, () => {\n const shouldRemoveText = getPatchString(editor, topRedo.operations);\n\n const newText = prevSuggestion.slice(shouldRemoveText.length);\n setOption('suggestionText', newText);\n\n redo();\n });\n\n return;\n }\n\n return redo();\n },\n\n setSelection(props) {\n setSelection(props);\n\n if (\n editor.selection &&\n (!prevSelection ||\n !RangeApi.equals(prevSelection, editor.selection)) &&\n getOptions().autoTriggerQuery!({ editor }) &&\n editor.api.isFocused()\n ) {\n void api.copilot.triggerSuggestion();\n }\n\n prevSelection = editor.selection;\n },\n\n undo() {\n if (!getOptions().suggestionText) return undo();\n\n const lastUndos = editor.history.undos.at(-1) as CopilotBatch;\n const oldText = getOptions().suggestionText;\n\n if (lastUndos && lastUndos.shouldAbort === false && oldText) {\n withoutAbort(editor, () => {\n const shouldInsertText = getPatchString(\n editor,\n lastUndos.operations\n );\n\n const newText = shouldInsertText + oldText;\n setOption('suggestionText', newText);\n\n undo();\n });\n\n return;\n }\n\n return undo();\n },\n\n writeHistory(stacks, batch) {\n if (!getOptions().isLoading) {\n batch.shouldAbort = getOptions().shouldAbort;\n }\n\n return writeHistory(stacks, batch);\n },\n },\n };\n};\n"],"mappings":";AAEA,SAAS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M;AAAA,QAC1C;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,MACA,oBAAoB,CAAC,EAAE,KAAK,WAAW,EAAE,kBAAkB,KAAK,MAAM;AACpE,YAAI,CAAC,IAAI;AACP,eAAK,OAAO,IAAI,MAAM,EAAG,CAAC,EAAE;AAAA,QAC9B;AAEA,mBAAW;AAAA,UACT,kBAAkB;AAAA,UAClB,gBAAgB;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,MACA,MAAM,MAAM;AACV,cAAM,EAAE,gBAAgB,IAAI,WAAW;AAEvC,QAAC,IAAI,QAAQ,mBAA0C,OAAO;AAE9D,YAAI,iBAAiB;AACnB,0BAAgB,MAAM;AACtB,oBAAU,mBAAmB,IAAI;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,EACC,UAAU,CAAC,EAAE,KAAK,YAAY,WAAW,OAAO;AAAA,EAC/C,QAAQ,MAAM;AACZ,QAAI,CAAC,WAAW,EAAE,gBAAgB,OAAQ,QAAO;AAEjD,QAAI,QAAQ,KAAK;AAEjB,eAAW;AAAA,MACT,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,gBAAgB;AAAA,IAClB,CAAC;AAAA,EACH;AACF,EAAE,EACD,OAAO;AAAA,EACN,QAAQ;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,MACN,MAAM;AAAA,IACR;AAAA,IACA,QAAQ;AAAA,MACN,MAAM;AAAA,IACR;AAAA,EACF;AACF,CAAC;","names":["KEYS","KEYS","KEYS","isSelecting","immer","isSet","current","Immer","base","Immer","Path","ancestors","path","options","arguments","length","undefined","reverse","paths","levels","slice","common","another","i","av","bv","push","compare","min","Math","endsAfter","as","bs","equals","endsAt","endsBefore","every","n","hasPrevious","isAfter","isAncestor","isBefore","isChild","isCommon","isDescendant","isParent","isPath","value","Array","isArray","isSibling","al","bl","list","next","Error","concat","last","operationCanTransformPath","operation","type","parent","previous","relative","ancestor","transform","p","affinity","op","position","newPath","onp","copy","o","toPrimitive","toPropertyKey","insertChildren","xs","index","_len","newValues","_key","replaceChildren","removeCount","_len2","_key2","removeChildren","modifyDescendant","editor","f","node","Node","get","slicedPath","modifiedNode","pop","ancestorNode","_objectSpread","children","modifyChildren","Text","isText","Scrubber","stringify","modifyLeaf","GeneralTransforms","transformSelection","offset","text","before","after","prevPath","prevIndex","prev","newNode","truePath","newIndex","selection","point","key","Range","points","result","Point","texts","preferNext","properties","newProperties","hasOwnProperty","isRange","nextNode","NodeTransforms","insertNodes","nodes","liftNodes","mergeNodes","moveNodes","removeNodes","setNodes","props","splitNodes","unsetNodes","unwrapNodes","wrapNodes","element","SelectionTransforms","collapse","deselect","move","select","target","setPoint","setSelection","isObject","isDeepEqual","a","b","objectWithoutPropertiesLoose","edges","range","anchor","focus","isBackward","end","surrounds","intersectionRange","intersection","includes","rs","re","ts","te","start","isAfterStart","isBeforeEnd","isPoint","rest","_objectWithoutProperties","_excluded","s1","e1","s2","e2","isCollapsed","isExpanded","isForward","affinityAnchor","affinityFocus","isElement","deep","isEditor","apply","isChildrenValid","isNodeList","Element","isElementList","val","isElementProps","isElementType","elementVal","elementKey","matches","root","entry","child","c","childPath","descendant","Editor","descendants","elements","extractProps","_excluded2","first","fragment","newRoot","produce","r","nodeEntries","pass","_ref","splice","leaf","getIf","has","isNode","isTextProps","from","to","visited","Set","add","nextIndex","parentPath","string","map","join","Operation","isNodeOperation","isOperation","endsWith","isOperationList","isSelectionOperation","isTextOperation","inverse","inversePath","inverseNewPath","addMark","deleteFragment","insertBreak","insertSoftBreak","insertFragment","insertNode","insertText","isElementReadOnly","isInline","isSelectable","isVoid","normalizeNode","onChange","removeMark","getDirtyPaths","marks","operations","above","at","deleteBackward","unit","deleteForward","elementReadOnly","hasBlocks","hasInlines","hasPath","hasTexts","isBlock","isEdge","isEmpty","isEnd","isNormalizing","isStart","getMarks","normalize","pathRef","pathRefs","pointRef","pointRefs","positions","rangeRef","rangeRefs","setNormalizing","unhangRange","void","withoutNormalizing","fn","shouldMergeNodesRemovePrevNode","prevNode","curNode","Point","compare","point","another","result","Path","path","offset","isAfter","isBefore","equals","isPoint","value","isObject","isPath","transform","op","options","affinity","type","text","length","position","Math","min","isAncestor","_objectSpread","_scrubber","undefined","Scrubber","setScrubber","scrubber","stringify","JSON","Text","loose","omitText","obj","rest","_objectWithoutProperties","_excluded","isDeepEqual","isText","isTextList","Array","isArray","every","val","isTextProps","props","matches","key","hasOwnProperty","decorations","node","leaves","leaf","dec","anchor","focus","merge","mergeDecoration","_excluded2","start","end","Range","edges","next","leafEnd","decorationStart","decorationEnd","Object","assign","leafStart","push","middle","before","after","off","slice","currentOffset","index","item","entries","isFirst","isLast","getDefaultInsertLocation","editor","selection","children","Editor","CodepointType","NonBoundaryPairs","CodepointType","L","V","LV","LVT","T","Any","Extend","ZWJ","SpacingMark","Prepend","ExtPict","RI","TextTransforms","delete","editor","options","insertFragment","fragment","insertText","text","Editor","withoutNormalizing","voids","at","getDefaultInsertLocation","Path","isPath","range","Range","isRange","isCollapsed","anchor","end","void","start","startRef","pointRef","endRef","Transforms","startPoint","unref","endPoint","setSelection","focus","elementReadOnly","path","offset","length","apply","type","_objectSpread","GeneralTransforms","NodeTransforms","SelectionTransforms","BlockSelectionPlugin","bindFirst","ElementApi","getPluginType","KEYS","getTransientSuggestionKey","KEYS","KEYS","getTransientSuggestionKey","BlockSelectionPlugin","cloneDeep","KEYS","KEYS","NodeApi","TextApi","formattedBlocks","BlockSelectionPlugin","KEYS","cloneDeep","getPluginType","KEYS","KEYS","getEditorPlugin","getEditorPlugin","KEYS","isSelecting","BlockSelectionPlugin","KEYS","getEditorPlugin","getEditorPlugin","KEYS","isSelecting","BlockSelectionPlugin","ElementApi","KEYS","KEYS","ElementApi","KEYS","bindFirst","ElementApi","getPluginType","BlockSelectionPlugin","useEffect","KEYS","usePluginOption","usePluginOption","KEYS","useEffect","useEffect","BlockSelectionPlugin","useEditorPlugin","usePluginOption","useEditorPlugin","usePluginOption","useEffect","BlockSelectionPlugin","MarkdownPlugin","MarkdownPlugin","getPluginType","KEYS","TextApi","KEYS","ElementApi","ElementApi","MarkdownPlugin","TextApi","textNode","KEYS","getPluginType","getPluginType","KEYS","NodeApi","PathApi","MarkdownPlugin","ElementApi","KEYS","TextApi","KEYS","ElementApi","TextApi","MarkdownPlugin","PathApi","NodeApi","getPluginType","KEYS","serializedBlock","editor","deserializeMd","BlockSelectionPlugin","getTransientSuggestionKey","ElementApi","KEYS","TextApi","BlockSelectionPlugin","ElementApi","TextApi","getTransientSuggestionKey","KEYS","deserializeMd","bindFirst","KEYS","NodeApi","createTPlatePlugin","KEYS","getEditorPlugin","KEYS","deserializeInlineMd","KEYS","getEditorPlugin","fetch","KEYS","getEditorPlugin","getEditorPlugin","KEYS","getEditorPlugin","KEYS","getNextWord","deserializeInlineMd","RangeApi","RangeApi","createTPlatePlugin","KEYS","NodeApi","bindFirst"]}
|
|
1
|
+
{"version":3,"sources":["../../src/react/ai/AIPlugin.ts","../../src/lib/BaseAIPlugin.ts","../../src/lib/transforms/insertAINodes.ts","../../src/lib/transforms/removeAIMarks.ts","../../src/lib/transforms/removeAINodes.ts","../../src/lib/transforms/undoAI.ts","../../src/lib/transforms/withAIBatch.ts","../../src/lib/utils/getEditorPrompt.ts","../../src/react/ai/utils/aiCommentToRange.ts","../../src/react/ai/utils/findTextRangeInBlock.tsx","../../src/react/ai-chat/AIChatPlugin.ts","../../src/react/ai-chat/transforms/acceptAIChat.ts","../../src/react/ai-chat/transforms/insertBelowAIChat.ts","../../src/react/ai-chat/transforms/replaceSelectionAIChat.ts","../../src/react/ai-chat/transforms/removeAnchorAIChat.ts","../../src/react/ai-chat/utils/resetAIChat.ts","../../src/react/ai-chat/utils/submitAIChat.ts","../../src/react/ai-chat/withAIChat.ts","../../src/react/ai-chat/hooks/useAIChatEditor.ts","../../src/react/ai-chat/hooks/useChatChunk.ts","../../src/react/ai-chat/utils/getLastAssistantMessage.ts","../../src/react/ai-chat/hooks/useEditorChat.ts","../../src/react/ai-chat/streaming/streamDeserializeInlineMd.ts","../../src/react/ai-chat/streaming/streamDeserializeMd.ts","../../src/react/ai-chat/streaming/utils/utils.ts","../../src/react/ai-chat/streaming/utils/escapeInput.ts","../../src/react/ai-chat/streaming/utils/getListNode.ts","../../src/react/ai-chat/streaming/utils/isSameNode.ts","../../src/react/ai-chat/streaming/utils/nodesWithProps.ts","../../src/react/ai-chat/streaming/streamInsertChunk.ts","../../src/react/ai-chat/streaming/streamSerializeMd.ts","../../src/react/ai-chat/utils/applyAISuggestions.ts","../../src/react/copilot/CopilotPlugin.tsx","../../src/react/copilot/renderCopilotBelowNodes.tsx","../../src/react/copilot/transforms/acceptCopilot.ts","../../src/react/copilot/transforms/acceptCopilotNextWord.ts","../../src/react/copilot/utils/callCompletionApi.ts","../../src/react/copilot/utils/getNextWord.ts","../../src/react/copilot/utils/triggerCopilotSuggestion.ts","../../src/react/copilot/utils/withoutAbort.ts","../../src/react/copilot/withCopilot.ts"],"sourcesContent":["import type { ExtendConfig } from 'platejs';\n\nimport { toPlatePlugin } from 'platejs/react';\n\nimport { type BaseAIPluginConfig, BaseAIPlugin } from '../../lib';\n\nexport type AIPluginConfig = ExtendConfig<BaseAIPluginConfig>;\n\nexport const AIPlugin = toPlatePlugin(BaseAIPlugin);\n","import {\n type OmitFirst,\n type PluginConfig,\n bindFirst,\n createTSlatePlugin,\n KEYS,\n} from 'platejs';\n\nimport { removeAIMarks, undoAI } from './transforms';\nimport { insertAINodes } from './transforms/insertAINodes';\nimport { removeAINodes } from './transforms/removeAINodes';\n\nexport type BaseAIPluginConfig = PluginConfig<\n 'ai',\n {},\n {},\n {\n ai: {\n insertNodes: OmitFirst<typeof insertAINodes>;\n removeMarks: OmitFirst<typeof removeAIMarks>;\n removeNodes: OmitFirst<typeof removeAINodes>;\n };\n }\n>;\n\nexport const BaseAIPlugin = createTSlatePlugin({\n key: KEYS.ai,\n node: { isDecoration: false, isLeaf: true },\n}).extendTransforms(({ editor }) => ({\n insertNodes: bindFirst(insertAINodes, editor),\n removeMarks: bindFirst(removeAIMarks, editor),\n removeNodes: bindFirst(removeAINodes, editor),\n undo: bindFirst(undoAI, editor),\n}));\n","import type { Descendant, Path, SlateEditor } from 'platejs';\n\nexport const insertAINodes = (\n editor: SlateEditor,\n nodes: Descendant[],\n {\n target,\n }: {\n target?: Path;\n } = {}\n) => {\n if (!target && !editor.selection?.focus.path) return;\n\n const aiNodes = nodes.map((node) => ({\n ...node,\n ai: true,\n }));\n\n editor.tf.withoutNormalizing(() => {\n editor.tf.insertNodes(aiNodes, {\n at: editor.api.end(target || editor.selection!.focus.path),\n select: true,\n });\n editor.tf.collapse({ edge: 'end' });\n });\n};\n","import { type SlateEditor, type TLocation, getPluginType, KEYS } from 'platejs';\n\nexport const removeAIMarks = (\n editor: SlateEditor,\n { at = [] }: { at?: TLocation } = {}\n) => {\n const nodeType = getPluginType(editor, KEYS.ai);\n\n editor.tf.unsetNodes(nodeType, {\n at,\n match: (n) => (n as any)[nodeType],\n });\n};\n","import { type Path, type SlateEditor, TextApi } from 'platejs';\n\nexport const removeAINodes = (\n editor: SlateEditor,\n { at = [] }: { at?: Path } = {}\n) => {\n editor.tf.removeNodes({\n at,\n match: (n) => TextApi.isText(n) && !!(n as any).ai,\n });\n};\n","import type { SlateEditor } from 'platejs';\n\nimport { getTransientSuggestionKey } from '@platejs/suggestion';\n\nexport const undoAI = (editor: SlateEditor) => {\n const hasAINodeOrAISuggestion =\n editor.api.some({\n at: [],\n match: (n) => !!(n as any).ai,\n }) ||\n editor.api.some({\n at: [],\n match: (n) => !!n[getTransientSuggestionKey()],\n });\n\n if ((editor.history.undos.at(-1) as any)?.ai && hasAINodeOrAISuggestion) {\n editor.undo();\n editor.history.redos.pop();\n }\n};\n","import type { History, SlateEditor } from 'platejs';\n\nexport type AIBatch = History['undos'][number] & { ai?: boolean };\n\nexport const withAIBatch = (\n editor: SlateEditor,\n fn: () => void,\n {\n split,\n }: {\n split?: boolean;\n } = {}\n) => {\n if (split) {\n editor.tf.withNewBatch(fn);\n } else {\n editor.tf.withMerging(fn);\n }\n\n const lastBatch = editor.history.undos?.at(-1) as AIBatch | undefined;\n\n if (lastBatch) {\n lastBatch.ai = true;\n }\n};\n","import { isSelecting } from '@platejs/selection';\nimport { type SlateEditor, KEYS } from 'platejs';\n\nexport type EditorPrompt =\n | ((params: EditorPromptParams) => string)\n | PromptConfig\n | string;\n\nexport interface EditorPromptParams {\n editor: SlateEditor;\n isBlockSelecting: boolean;\n isSelecting: boolean;\n}\n\nexport interface PromptConfig {\n default: string;\n blockSelecting?: string;\n selecting?: string;\n}\n\nconst createPromptFromConfig = (\n config: PromptConfig,\n params: EditorPromptParams\n): string => {\n const { isBlockSelecting, isSelecting } = params;\n\n if (isBlockSelecting && config.blockSelecting) {\n return config.blockSelecting ?? config.default;\n } else if (isSelecting && config.selecting) {\n return config.selecting ?? config.default;\n } else {\n return config.default;\n }\n};\n\nexport const getEditorPrompt = (\n editor: SlateEditor,\n {\n prompt = '',\n }: {\n prompt?: EditorPrompt;\n }\n): string => {\n const params: EditorPromptParams = {\n editor,\n isBlockSelecting: editor.getOption(\n { key: KEYS.blockSelection },\n 'isSelectingSome'\n ),\n isSelecting: isSelecting(editor),\n };\n\n let promptText = '';\n\n if (typeof prompt === 'function') {\n promptText = prompt(params);\n } else if (typeof prompt === 'object') {\n promptText = createPromptFromConfig(prompt, params);\n } else {\n promptText = prompt;\n }\n\n return promptText;\n};\n","import { deserializeMd } from '@platejs/markdown';\nimport {\n type NodeEntry,\n type Range,\n type SlateEditor,\n type TElement,\n NodeApi,\n} from 'platejs';\n\nimport type { TComment } from '../../ai-chat/internal/types';\n\nimport { findTextRangeInBlock } from './findTextRangeInBlock';\n\nexport const aiCommentToRange = (\n editor: SlateEditor,\n aiComment: TComment\n): Range | undefined => {\n const { blockId, content } = aiComment;\n\n const contentNodes = deserializeMd(editor, content);\n\n let firstBlock: NodeEntry<TElement> | undefined;\n\n const ranges: Range[] = [];\n contentNodes.forEach((node, index) => {\n let currentBlock: NodeEntry<TElement> | undefined;\n\n if (index === 0) {\n firstBlock = editor.api.node<TElement>({ id: blockId, at: [] });\n currentBlock = firstBlock;\n } else {\n if (!firstBlock) return;\n\n const [_, firstBlockPath] = firstBlock;\n\n const blockPath = [firstBlockPath[0] + index];\n currentBlock = editor.api.node(blockPath);\n }\n\n if (!currentBlock) return;\n\n const range = findTextRangeInBlock({\n block: currentBlock,\n findText: NodeApi.string(node),\n });\n\n if (!range) return;\n\n ranges.push(range);\n });\n\n if (ranges.length === 0) return;\n\n if (ranges.length > 1) {\n const startRange = ranges[0];\n const endRange = ranges.at(-1)!;\n\n return {\n anchor: startRange.anchor,\n focus: endRange.focus,\n };\n }\n\n if (ranges.length === 1) {\n return ranges[0];\n }\n};\n","import { distance } from 'fastest-levenshtein';\nimport { type NodeEntry, type Path, type Range, NodeApi } from 'platejs';\n\nfunction maxAllowedDistance(len: number): number {\n if (len <= 2) return 0;\n if (len <= 5) return 1;\n if (len <= 10) return 2;\n if (len <= 20) return 3;\n // Maximum allowed distance is 5, regardless of text length\n return 5;\n}\n\n/** Find text within a block, supporting fuzzy matching. */\nexport function findTextRangeInBlock({\n block,\n findText,\n}: {\n block: NodeEntry;\n findText: string;\n}): Range | null {\n const [blockNode, blockPath] = block;\n\n // Collect all text content and map positions\n const textSegments: { offset: number; path: Path; text: string }[] = [];\n let fullText = '';\n\n // Iterate through all text nodes in the block\n for (const [textNode, textPath] of NodeApi.texts(blockNode)) {\n const startOffset = fullText.length;\n // textPath is relative to blockNode, not absolute\n const absolutePath = [...blockPath, ...textPath];\n textSegments.push({\n offset: startOffset,\n path: absolutePath,\n text: textNode.text,\n });\n fullText += textNode.text;\n }\n\n if (!fullText) return null;\n\n // Try exact match first\n let matchStart = fullText.indexOf(findText);\n let matchEnd = matchStart >= 0 ? matchStart + findText.length : -1;\n\n // If no exact match, try fuzzy matching\n if (matchStart === -1) {\n const maxDist = maxAllowedDistance(findText.length);\n let bestMatch = { distance: Infinity, end: -1, start: -1 };\n\n // Sliding window to find best fuzzy match\n for (let i = 0; i <= fullText.length - findText.length; i++) {\n // Try different lengths around the target length\n for (let lenOffset = -maxDist; lenOffset <= maxDist; lenOffset++) {\n const len = findText.length + lenOffset;\n if (len <= 0 || i + len > fullText.length) continue;\n\n const candidate = fullText.slice(i, i + len);\n const dist = distance(candidate, findText);\n\n if (dist <= maxDist && dist < bestMatch.distance) {\n bestMatch = { distance: dist, end: i + len, start: i };\n }\n }\n }\n\n if (bestMatch.start !== -1) {\n matchStart = bestMatch.start;\n matchEnd = bestMatch.end;\n }\n }\n\n // If still no match, try prefix matching as fallback\n if (matchStart === -1) {\n // Find longest prefix match\n for (let prefixLen = findText.length - 1; prefixLen > 0; prefixLen--) {\n const prefix = findText.slice(0, Math.max(0, prefixLen));\n const idx = fullText.indexOf(prefix);\n if (idx !== -1) {\n matchStart = idx;\n matchEnd = idx + prefixLen;\n break;\n }\n }\n }\n\n if (matchStart === -1) return null;\n\n // Convert character offsets to Slate paths and offsets\n const findPoint = (\n charOffset: number,\n isEnd = false\n ): { offset: number; path: Path } => {\n const accumulated = 0;\n\n // For start positions, if offset lands exactly at the beginning of a segment, use that segment\n if (!isEnd) {\n for (const segment of textSegments) {\n if (charOffset === segment.offset) {\n return {\n offset: 0,\n path: segment.path,\n };\n }\n }\n }\n\n // Normal search through segments\n for (const segment of textSegments) {\n const segmentEnd = segment.offset + segment.text.length;\n\n if (charOffset >= segment.offset && charOffset <= segmentEnd) {\n const localOffset = charOffset - segment.offset;\n return {\n offset: localOffset,\n path: segment.path,\n };\n }\n }\n\n // Fallback to last position\n const lastSegment = textSegments.at(-1);\n if (!lastSegment) {\n return { offset: 0, path: blockPath };\n }\n return {\n offset: lastSegment.text.length,\n path: lastSegment.path,\n };\n };\n\n const anchor = findPoint(matchStart, false);\n const focus = findPoint(matchEnd, true);\n\n return {\n anchor,\n focus,\n };\n}\n","import type { UseChatHelpers } from '@ai-sdk/react';\nimport type { TriggerComboboxPluginOptions } from '@platejs/combobox';\n\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport {\n type EditorNodesOptions,\n type NodeEntry,\n type OmitFirst,\n type Path,\n type PluginConfig,\n type SlateEditor,\n type TIdElement,\n type TRange,\n bindFirst,\n ElementApi,\n getPluginType,\n KEYS,\n} from 'platejs';\nimport { createTPlatePlugin } from 'platejs/react';\n\nimport type { AIBatch } from '../../lib';\nimport type { AIMode, AIToolName } from '../../lib/types';\nimport type { ChatMessage } from './internal/types';\n\nimport { AIPlugin } from '../ai/AIPlugin';\nimport { removeAnchorAIChat } from './transforms';\nimport { acceptAIChat } from './transforms/acceptAIChat';\nimport { insertBelowAIChat } from './transforms/insertBelowAIChat';\nimport { replaceSelectionAIChat } from './transforms/replaceSelectionAIChat';\nimport { resetAIChat } from './utils/resetAIChat';\nimport { submitAIChat } from './utils/submitAIChat';\nimport { withAIChat } from './withAIChat';\n\nexport type AIChatPluginConfig = PluginConfig<\n 'aiChat',\n {\n _blockChunks: string;\n _blockPath: Path | null;\n /** @private Using For streamInsertChunk */\n _mdxName: string | null;\n _replaceIds: string[];\n /** @private The Editor used to generate the AI response. */\n aiEditor: SlateEditor | null;\n chat: UseChatHelpers<ChatMessage>;\n chatNodes: TIdElement[];\n chatSelection: TRange | null;\n /** @deprecated Use api.aiChat.node({streaming:true}) instead */\n experimental_lastTextId: string | null;\n /**\n * Specifies how the assistant message is handled:\n *\n * - 'insert': Directly inserts content into the editor without preview.\n * - 'chat': Initiates an interactive session to review and refine content\n * before insertion.\n */\n mode: AIMode;\n open: boolean;\n /** Whether the AI response is currently streaming. Cursor mode only. */\n streaming: boolean;\n toolName: AIToolName;\n } & TriggerComboboxPluginOptions,\n {\n aiChat: {\n reset: OmitFirst<typeof resetAIChat>;\n submit: OmitFirst<typeof submitAIChat>;\n hide: (options?: { focus?: boolean; undo?: boolean }) => void;\n node: (\n options?: EditorNodesOptions & { anchor?: boolean; streaming?: boolean }\n ) => NodeEntry | undefined;\n reload: () => void;\n show: () => void;\n stop: () => void;\n };\n },\n {\n aiChat: {\n accept: OmitFirst<typeof acceptAIChat>;\n insertBelow: OmitFirst<typeof insertBelowAIChat>;\n replaceSelection: OmitFirst<typeof replaceSelectionAIChat>;\n removeAnchor: (options?: EditorNodesOptions) => void;\n };\n }\n>;\n\nexport const AIChatPlugin = createTPlatePlugin<AIChatPluginConfig>({\n key: KEYS.aiChat,\n dependencies: ['ai'],\n node: {\n isElement: true,\n },\n options: {\n _blockChunks: '',\n _blockPath: null,\n _mdxName: null,\n _replaceIds: [],\n aiEditor: null,\n chat: { messages: [] } as unknown as UseChatHelpers<ChatMessage>,\n chatNodes: [],\n chatSelection: null,\n experimental_lastTextId: null,\n mode: 'insert',\n open: false,\n streaming: false,\n toolName: null,\n trigger: ' ',\n triggerPreviousCharPattern: /^\\s?$/,\n },\n})\n .overrideEditor(withAIChat)\n .extendApi<\n Pick<\n AIChatPluginConfig['api']['aiChat'],\n 'node' | 'reset' | 'stop' | 'submit'\n >\n >(({ editor, getOption, getOptions, setOption, type }) => {\n return {\n reset: bindFirst(resetAIChat, editor),\n submit: bindFirst(submitAIChat, editor),\n node: (options = {}) => {\n const { anchor = false, streaming = false, ...rest } = options;\n\n if (anchor) {\n return editor.api.node({\n at: [],\n match: (n) => ElementApi.isElement(n) && n.type === type,\n ...rest,\n });\n }\n\n if (streaming) {\n if (!getOption('streaming')) return;\n\n const path = getOption('_blockPath');\n if (!path) return;\n\n return editor.api.node({\n at: path,\n mode: 'lowest',\n reverse: true,\n match: (t) => !!t[getPluginType(editor, KEYS.ai)],\n ...rest,\n });\n }\n\n return editor.api.node({\n match: (n) => n[getPluginType(editor, KEYS.ai)],\n ...rest,\n });\n },\n reload: () => {\n const { chat, chatNodes, chatSelection } = getOptions();\n\n editor.getTransforms(AIPlugin).ai.undo();\n\n if (chatSelection) {\n editor.tf.setSelection(chatSelection);\n } else {\n editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.set(chatNodes.map((node) => node.id as string));\n }\n\n const blocks = editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.getNodes();\n\n const selection =\n blocks.length > 0 ? editor.api.nodesRange(blocks) : editor.selection;\n\n const ctx = {\n children: editor.children,\n selection: selection ?? null,\n toolName: getOption('toolName'),\n };\n\n void chat.regenerate?.({\n body: {\n ctx,\n },\n });\n },\n stop: () => {\n setOption('streaming', false);\n getOptions().chat.stop?.();\n },\n };\n })\n .extendApi(({ api, editor, getOptions, setOption, tf, type }) => ({\n hide: ({\n focus = true,\n undo = true,\n }: { focus?: boolean; undo?: boolean } = {}) => {\n api.aiChat.reset({ undo });\n\n setOption('open', false);\n\n if (focus) {\n if (editor.getOption(BlockSelectionPlugin, 'isSelectingSome')) {\n editor.getApi(BlockSelectionPlugin).blockSelection.focus();\n } else {\n editor.tf.focus();\n }\n }\n\n const lastBatch = editor.history.undos.at(-1) as AIBatch;\n\n if (lastBatch?.ai) {\n delete lastBatch.ai;\n }\n\n tf.aiChat.removeAnchor();\n },\n show: () => {\n api.aiChat.reset();\n\n setOption('toolName', null);\n\n getOptions().chat.setMessages?.([]);\n\n setOption('open', true);\n },\n }))\n .extendTransforms(({ editor }) => ({\n accept: bindFirst(acceptAIChat, editor),\n insertBelow: bindFirst(insertBelowAIChat, editor),\n removeAnchor: bindFirst(removeAnchorAIChat, editor),\n replaceSelection: bindFirst(replaceSelectionAIChat, editor),\n }));\n","import {\n acceptSuggestion,\n getSuggestionKey,\n getTransientSuggestionKey,\n} from '@platejs/suggestion';\nimport { SuggestionPlugin } from '@platejs/suggestion/react';\nimport { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport { withAIBatch } from '../../../lib';\nimport { AIPlugin } from '../../ai/AIPlugin';\nimport { type AIChatPluginConfig, AIChatPlugin } from '../AIChatPlugin';\n\nexport const acceptAIChat = (editor: PlateEditor) => {\n const mode = editor.getOption(AIChatPlugin, 'mode');\n\n if (mode === 'insert') {\n const { tf } = getEditorPlugin(editor, AIPlugin);\n const api = editor.getApi<AIChatPluginConfig>({ key: KEYS.ai });\n\n const lastAINodePath = api.aiChat.node({ at: [], reverse: true })![1];\n\n withAIBatch(editor, () => {\n tf.ai.removeMarks();\n editor.getTransforms(AIChatPlugin).aiChat.removeAnchor();\n });\n\n api.aiChat.hide();\n editor.tf.focus();\n\n const focusPoint = editor.api.end(lastAINodePath)!;\n\n editor.tf.setSelection({\n anchor: focusPoint,\n focus: focusPoint,\n });\n }\n\n if (mode === 'chat') {\n withAIBatch(editor, () => {\n acceptSuggestions(editor);\n });\n\n editor.getApi(AIChatPlugin).aiChat.hide();\n }\n};\n\nexport const acceptSuggestions = (editor: PlateEditor) => {\n const suggestions = editor.getApi(SuggestionPlugin).suggestion.nodes({\n transient: true,\n });\n\n suggestions.forEach(([suggestionNode]) => {\n const suggestionData = editor\n .getApi(SuggestionPlugin)\n .suggestion.suggestionData(suggestionNode);\n\n if (!suggestionData) return;\n\n const description = {\n createdAt: new Date(suggestionData.createdAt),\n keyId: getSuggestionKey(suggestionData.id),\n suggestionId: suggestionData.id,\n type: suggestionData.type,\n userId: suggestionData.userId,\n };\n\n acceptSuggestion(editor, description);\n });\n\n editor.tf.unsetNodes([getTransientSuggestionKey()], {\n at: [],\n mode: 'all',\n match: (n) => !!n[getTransientSuggestionKey()],\n });\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport cloneDeep from 'lodash/cloneDeep.js';\nimport { type SlateEditor, KEYS, PathApi, RangeApi } from 'platejs';\n\nimport { withAIBatch } from '../../../lib';\nimport { AIPlugin } from '../../ai/AIPlugin';\nimport { type AIChatPluginConfig, AIChatPlugin } from '../AIChatPlugin';\nimport { acceptSuggestions } from './acceptAIChat';\nimport { createFormattedBlocks } from './replaceSelectionAIChat';\n\nexport const insertBelowAIChat = (\n editor: PlateEditor,\n sourceEditor: SlateEditor,\n { format = 'single' }: { format?: 'all' | 'none' | 'single' } = {}\n) => {\n const { toolName } = editor.getOptions(AIChatPlugin);\n\n if (toolName === 'generate')\n return insertBelowGenerate(editor, sourceEditor, { format });\n\n const selectedBlocks = editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.getNodes();\n\n const selectedIds = editor.getOptions(BlockSelectionPlugin).selectedIds;\n\n editor.getTransforms(AIPlugin).ai.undo();\n\n const insertBlocksAndSelect =\n editor.getTransforms(BlockSelectionPlugin).blockSelection\n .insertBlocksAndSelect;\n\n if (!selectedIds || selectedIds.size === 0) return;\n\n const lastBlock = selectedBlocks.at(-1);\n\n if (!lastBlock) return;\n\n const nextPath = PathApi.next(lastBlock[1]);\n\n const nodes = selectedBlocks.map((block) => block[0]);\n\n insertBlocksAndSelect(nodes, {\n at: nextPath,\n insertedCallback: () => {\n withAIBatch(editor, () => {\n acceptSuggestions(editor);\n });\n },\n });\n\n editor.getApi(AIChatPlugin).aiChat.hide({ focus: false });\n};\n\nexport const insertBelowGenerate = (\n editor: PlateEditor,\n sourceEditor: SlateEditor,\n { format = 'single' }: { format?: 'all' | 'none' | 'single' } = {}\n) => {\n if (!sourceEditor || sourceEditor.api.isEmpty()) return;\n\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n editor.getApi<AIChatPluginConfig>({ key: KEYS.ai }).aiChat.hide();\n\n const insertBlocksAndSelect =\n editor.getTransforms(BlockSelectionPlugin).blockSelection\n .insertBlocksAndSelect;\n\n if (isBlockSelecting) {\n const selectedBlocks = editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.getNodes();\n\n const selectedIds = editor.getOptions(BlockSelectionPlugin).selectedIds;\n\n if (!selectedIds || selectedIds.size === 0) return;\n\n const lastBlock = selectedBlocks.at(-1);\n\n if (!lastBlock) return;\n\n const nextPath = PathApi.next(lastBlock[1]);\n\n if (format === 'none') {\n insertBlocksAndSelect(cloneDeep(sourceEditor.children), {\n at: nextPath,\n });\n\n return;\n }\n\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: lastBlock,\n });\n\n if (!formattedBlocks) return;\n\n insertBlocksAndSelect(formattedBlocks, {\n at: nextPath,\n });\n } else {\n const [, end] = RangeApi.edges(editor.selection!);\n const endPath = [end.path[0]];\n const currentBlock = editor.api.node({\n at: endPath,\n block: true,\n mode: 'lowest',\n });\n\n if (!currentBlock) return;\n if (format === 'none') {\n insertBlocksAndSelect(cloneDeep(sourceEditor.children), {\n at: PathApi.next(endPath),\n });\n\n return;\n }\n\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: currentBlock,\n });\n\n if (!formattedBlocks) return;\n\n insertBlocksAndSelect(formattedBlocks, {\n at: PathApi.next(endPath),\n });\n }\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport {\n BlockSelectionPlugin,\n removeBlockSelectionNodes,\n} from '@platejs/selection/react';\nimport cloneDeep from 'lodash/cloneDeep.js';\nimport {\n type NodeEntry,\n type SlateEditor,\n type TElement,\n KEYS,\n NodeApi,\n TextApi,\n} from 'platejs';\n\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nexport const createFormattedBlocks = ({\n blocks,\n format,\n sourceBlock,\n}: {\n blocks: TElement[];\n format: 'all' | 'none' | 'single';\n sourceBlock: NodeEntry;\n}) => {\n if (format === 'none') return cloneDeep(blocks);\n\n const [sourceNode] = sourceBlock;\n const firstTextEntry = NodeApi.firstText(sourceNode);\n\n if (!firstTextEntry) return null;\n\n const blockProps = NodeApi.extractProps(sourceNode);\n const textProps = NodeApi.extractProps(firstTextEntry[0]);\n\n const applyTextFormatting = (node: any): any => {\n if (TextApi.isText(node)) {\n return { ...textProps, ...node };\n }\n if (node.children) {\n return {\n ...node,\n children: node.children.map(applyTextFormatting),\n };\n }\n\n return node;\n };\n\n return blocks.map((block, index) => {\n if (format === 'single' && index > 0) {\n return block;\n }\n\n return applyTextFormatting({\n ...block,\n ...blockProps,\n });\n });\n};\n\nexport const replaceSelectionAIChat = (\n editor: PlateEditor,\n sourceEditor: SlateEditor,\n { format = 'single' }: { format?: 'all' | 'none' | 'single' } = {}\n) => {\n if (!sourceEditor || sourceEditor.api.isEmpty()) return;\n\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n editor.getApi<AIChatPluginConfig>({ key: KEYS.ai }).aiChat.hide();\n\n // If no blocks selected, treat it like a normal selection replacement\n if (!isBlockSelecting) {\n const firstBlock = editor.api.node({\n block: true,\n mode: 'lowest',\n });\n\n if (\n firstBlock &&\n editor.api.isSelected(firstBlock[1], { contains: true }) &&\n format !== 'none'\n ) {\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: firstBlock,\n });\n\n if (!formattedBlocks) return;\n\n /** When user selection is cover the whole code block */\n if (\n firstBlock[0].type === KEYS.codeLine &&\n sourceEditor.children[0].type === KEYS.codeBlock &&\n sourceEditor.children.length === 1\n ) {\n editor.tf.insertFragment(formattedBlocks[0].children);\n } else {\n editor.tf.insertFragment(formattedBlocks);\n }\n\n editor.tf.focus();\n\n return;\n }\n\n editor.tf.insertFragment(sourceEditor.children);\n editor.tf.focus();\n\n return;\n }\n\n const blockSelectionApi = editor.getApi(BlockSelectionPlugin).blockSelection;\n const selectedBlocks = blockSelectionApi.getNodes();\n\n if (selectedBlocks.length === 0) return;\n // If format is 'none' or multiple blocks with 'single',\n // just insert the content as is\n if (format === 'none' || (format === 'single' && selectedBlocks.length > 1)) {\n editor.tf.withoutNormalizing(() => {\n removeBlockSelectionNodes(editor);\n\n editor.tf.withNewBatch(() => {\n editor\n .getTransforms(BlockSelectionPlugin)\n .blockSelection.insertBlocksAndSelect(\n cloneDeep(sourceEditor.children),\n {\n at: selectedBlocks[0][1],\n }\n );\n });\n });\n\n editor.getApi(BlockSelectionPlugin).blockSelection.focus();\n\n return;\n }\n\n // Apply formatting from first block when:\n // - formatting is 'all', or\n // - only one block is selected\n const [, firstBlockPath] = selectedBlocks[0];\n const formattedBlocks = createFormattedBlocks({\n blocks: cloneDeep(sourceEditor.children),\n format,\n sourceBlock: selectedBlocks[0],\n });\n\n if (!formattedBlocks) return;\n\n editor.tf.withoutNormalizing(() => {\n removeBlockSelectionNodes(editor);\n\n editor.tf.withNewBatch(() => {\n editor\n .getTransforms(BlockSelectionPlugin)\n .blockSelection.insertBlocksAndSelect(formattedBlocks, {\n at: firstBlockPath,\n });\n });\n });\n\n editor.getApi(BlockSelectionPlugin).blockSelection.focus();\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport {\n type RemoveNodesOptions,\n ElementApi,\n getPluginType,\n KEYS,\n} from 'platejs';\n\nexport const removeAnchorAIChat = (\n editor: PlateEditor,\n options?: RemoveNodesOptions\n) => {\n editor.tf.withoutSaving(() => {\n editor.tf.removeNodes({\n at: [],\n match: (n) =>\n ElementApi.isElement(n) &&\n n.type === getPluginType(editor, KEYS.aiChat),\n ...options,\n });\n });\n};\n","import { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nimport { AIPlugin } from '../../ai/AIPlugin';\n\nexport const resetAIChat = (\n editor: PlateEditor,\n { undo = true }: { undo?: boolean } = {}\n) => {\n const { api, getOptions, setOptions } = getEditorPlugin<AIChatPluginConfig>(\n editor,\n {\n key: KEYS.aiChat,\n }\n );\n\n api.aiChat.stop();\n\n const chat = getOptions().chat;\n\n if (chat.messages && chat.messages.length > 0) {\n chat.setMessages?.([]);\n }\n\n setOptions({\n _replaceIds: [],\n chatNodes: [],\n mode: 'insert',\n toolName: 'generate',\n });\n\n if (undo) {\n editor.getTransforms(AIPlugin).ai.undo();\n }\n};\n","import type { ChatRequestOptions } from 'ai';\n\nimport { isSelecting } from '@platejs/selection';\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport { type Descendant, type Range, type TIdElement, KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { AIMode, AIToolName } from '../../../lib/types';\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nimport {\n type EditorPrompt,\n getEditorPrompt,\n} from '../../../lib/utils/getEditorPrompt';\nimport { AIPlugin } from '../../ai/AIPlugin';\n\nexport const submitAIChat = (\n editor: PlateEditor,\n input: string,\n {\n mode,\n options,\n prompt,\n toolName,\n }: {\n mode?: AIMode;\n options?: ChatRequestOptions;\n prompt?: EditorPrompt;\n toolName?: AIToolName;\n } = {}\n) => {\n const { getOptions, setOption } = getEditorPlugin<AIChatPluginConfig>(\n editor,\n {\n key: KEYS.aiChat,\n }\n );\n\n const { chat } = getOptions();\n\n if (!prompt && input?.length === 0) {\n return;\n }\n if (!prompt) {\n prompt = input;\n }\n if (!mode) {\n mode = isSelecting(editor) ? 'chat' : 'insert';\n }\n if (mode === 'insert') {\n editor.getTransforms(AIPlugin).ai.undo();\n }\n\n setOption('mode', mode);\n\n setOption('toolName', toolName ?? null);\n\n const blocks = editor.getApi(BlockSelectionPlugin).blockSelection.getNodes();\n const blocksRange = editor.api.nodesRange(blocks);\n\n const promptText = getEditorPrompt(editor, {\n prompt,\n });\n\n const selection = blocks.length > 0 ? blocksRange : editor.selection;\n\n const chatNodes =\n blocks.length > 0\n ? blocks.map((block) => block[0])\n : editor.api.fragment<TIdElement>();\n\n setOption('chatNodes', chatNodes);\n setOption('chatSelection', blocks.length > 0 ? null : editor.selection);\n\n const ctx: {\n children: Descendant[];\n selection: Range | null;\n toolName: string | null;\n } = {\n children: editor.children,\n selection: selection ?? null,\n toolName: toolName ?? null,\n };\n\n void chat.sendMessage?.(\n {\n text: promptText,\n },\n {\n body: {\n ctx,\n },\n ...options,\n }\n );\n};\n","import type { OverrideEditor } from 'platejs/react';\n\nimport { ElementApi, KEYS } from 'platejs';\n\nimport { AIPlugin } from '../ai/AIPlugin';\nimport { type AIChatPluginConfig, AIChatPlugin } from './AIChatPlugin';\n\nexport const withAIChat: OverrideEditor<AIChatPluginConfig> = ({\n api,\n editor,\n getOptions,\n tf: { apply, insertText, normalizeNode },\n type,\n}) => {\n const tf = editor.getTransforms(AIPlugin);\n\n const matchesTrigger = (text: string) => {\n const { trigger } = getOptions();\n\n if (trigger instanceof RegExp) {\n return trigger.test(text);\n }\n if (Array.isArray(trigger)) {\n return trigger.includes(text);\n }\n\n return text === trigger;\n };\n\n return {\n transforms: {\n insertText(text, options) {\n const { triggerPreviousCharPattern, triggerQuery } = getOptions();\n\n const fn = () => {\n if (\n !editor.selection ||\n !matchesTrigger(text) ||\n (triggerQuery && !triggerQuery(editor))\n ) {\n return;\n }\n\n // Make sure an input is created at the beginning of line or after a whitespace\n const previousChar = editor.api.string(\n editor.api.range('before', editor.selection)\n );\n\n const matchesPreviousCharPattern =\n triggerPreviousCharPattern?.test(previousChar);\n\n if (!matchesPreviousCharPattern) return;\n\n const nodeEntry = editor.api.block({ highest: true });\n\n if (!nodeEntry || !editor.api.isEmpty(nodeEntry[0])) return;\n\n api.aiChat.show();\n\n return true;\n };\n\n if (fn()) return;\n\n return insertText(text, options);\n },\n normalizeNode(entry) {\n const [node, path] = entry;\n\n if (node[KEYS.ai] && !getOptions().open) {\n tf.ai.removeMarks({ at: path });\n\n return;\n }\n\n if (\n ElementApi.isElement(node) &&\n node.type === type &&\n !getOptions().open\n ) {\n editor.getTransforms(AIChatPlugin).aiChat.removeAnchor({ at: path });\n\n return;\n }\n\n return normalizeNode(entry);\n },\n },\n };\n};\n","import { useEffect, useMemo } from 'react';\n\nimport type { SlateEditor } from 'platejs';\n\nimport { type DeserializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\nimport { useEditorPlugin } from 'platejs/react';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\n/**\n * Register an editor in the AI chat plugin, and deserializes the content into\n * `editor.children` with block-level memoization.\n */\nexport const useAIChatEditor = (\n editor: SlateEditor,\n content: string,\n { parser }: DeserializeMdOptions = {}\n) => {\n const { setOption } = useEditorPlugin(AIChatPlugin);\n\n editor.children = useMemo(\n () => {\n return editor.getApi(MarkdownPlugin).markdown.deserialize(content, {\n memoize: true,\n parser,\n });\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [content]\n );\n\n useEffect(() => {\n setOption('aiEditor', editor);\n }, [editor, setOption]);\n};\n","import { useEffect, useRef } from 'react';\n\nimport type { TText } from 'platejs';\n\nimport { KEYS } from 'platejs';\nimport { usePluginOption } from 'platejs/react';\n\nimport type { AIChatPluginConfig } from '../AIChatPlugin';\n\nimport { useLastAssistantMessage } from '../utils/getLastAssistantMessage';\n\nexport const useChatChunk = ({\n onChunk,\n onFinish,\n}: {\n onChunk: (chunk: {\n chunk: string;\n isFirst: boolean;\n nodes: TText[];\n text: string;\n }) => void;\n onFinish?: ({ content }: { content: string }) => void;\n}) => {\n const { status } = usePluginOption(\n { key: KEYS.aiChat } as AIChatPluginConfig,\n 'chat'\n );\n const isLoading = status === 'streaming' || status === 'submitted';\n\n const content = useLastAssistantMessage()?.parts.find(\n (part) => part.type === 'text'\n )?.text;\n\n const insertedTextRef = useRef<string>('');\n const prevIsLoadingRef = useRef(isLoading);\n\n useEffect(() => {\n if (!isLoading) {\n insertedTextRef.current = '';\n }\n if (prevIsLoadingRef.current && !isLoading) {\n onFinish?.({ content: content ?? '' });\n }\n\n prevIsLoadingRef.current = isLoading;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoading]);\n\n useEffect(() => {\n if (!content) {\n return;\n }\n\n const chunk = content.slice(insertedTextRef.current.length);\n\n const nodes: TText[] = [];\n\n if (chunk) {\n const isFirst = insertedTextRef.current === '';\n\n nodes.push({ text: chunk });\n onChunk({\n chunk,\n isFirst,\n nodes,\n text: content,\n });\n }\n\n insertedTextRef.current = content;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content]);\n};\n","import { type PlateEditor, usePluginOption } from 'platejs/react';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\nexport function getLastAssistantMessage(editor: PlateEditor) {\n const messages = editor.getOptions(AIChatPlugin).chat.messages;\n\n return messages?.findLast((message) => message.role === 'assistant');\n}\n\nexport function useLastAssistantMessage() {\n const toolName = usePluginOption(AIChatPlugin, 'toolName');\n const chat = usePluginOption(AIChatPlugin, 'chat');\n\n if (toolName === 'comment') return;\n\n return chat.messages?.findLast((message) => message.role === 'assistant');\n}\n","'use client';\n\nimport { useEffect } from 'react';\n\nimport type { UseChatHelpers } from '@ai-sdk/react';\nimport type { NodeEntry } from 'platejs';\n\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport { useEditorPlugin, usePluginOption } from 'platejs/react';\n\nimport type { ChatMessage } from '../internal/types';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\nexport type UseEditorChatOptions = {\n chat: UseChatHelpers<ChatMessage>;\n onOpenBlockSelection?: (blocks: NodeEntry[]) => void;\n onOpenChange?: (open: boolean) => void;\n onOpenCursor?: () => void;\n onOpenSelection?: () => void;\n};\n\nexport const useEditorChat = ({\n chat,\n onOpenBlockSelection,\n onOpenChange,\n onOpenCursor,\n onOpenSelection,\n}: UseEditorChatOptions) => {\n const { editor } = useEditorPlugin(AIChatPlugin);\n const open = usePluginOption(AIChatPlugin, 'open');\n\n useEffect(() => {\n onOpenChange?.(open);\n\n if (open) {\n if (onOpenBlockSelection) {\n const blockSelectionApi =\n editor.getApi(BlockSelectionPlugin).blockSelection;\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n if (isBlockSelecting) {\n onOpenBlockSelection(blockSelectionApi.getNodes());\n\n return;\n }\n }\n if (onOpenCursor && editor.api.isCollapsed()) {\n onOpenCursor();\n\n return;\n }\n if (onOpenSelection && editor.api.isExpanded()) {\n onOpenSelection();\n\n return;\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open]);\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type DeserializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\n\nexport const streamDeserializeInlineMd = (\n editor: PlateEditor,\n text: string,\n options?: DeserializeMdOptions\n) => {\n return editor\n .getApi(MarkdownPlugin)\n .markdown.deserializeInline(text, options);\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type DeserializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\nimport { type TElement, getPluginType, KEYS, TextApi } from 'platejs';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\nimport { getChunkTrimmed } from './utils';\nimport { escapeInput } from './utils/escapeInput';\n\nconst statMdxTagRegex = /<([A-Za-z][A-Za-z0-9._:-]*)(?:\\s[^>]*?)?(?<!\\/)>/;\n\nexport const streamDeserializeMd = (\n editor: PlateEditor,\n data: string,\n options?: DeserializeMdOptions\n) => {\n const input = escapeInput(data);\n\n const value = withoutDeserializeInMdx(editor, input);\n\n if (Array.isArray(value)) return value;\n\n let blocks = [];\n\n blocks = editor.getApi(MarkdownPlugin).markdown.deserialize(input, {\n ...options,\n preserveEmptyParagraphs: false,\n });\n\n const trimmedData = getChunkTrimmed(data);\n\n const lastBlock = blocks.at(-1) as TElement | undefined;\n\n const addNewLine = trimmedData === '\\n\\n';\n const unshiftNewLine =\n getChunkTrimmed(data, { direction: 'left' }) === '\\n\\n';\n\n const isCodeBlockOrTable =\n lastBlock?.type === 'code_block' || lastBlock?.type === 'table';\n\n let result = blocks;\n\n /**\n * Deserialize the sting like `123\\n\\n` will be `123` base on markdown spec\n * but we want to keep the `\\n\\n`\n */\n\n if (\n lastBlock &&\n !isCodeBlockOrTable &&\n trimmedData.length > 0 &&\n !addNewLine\n ) {\n const textNode = [\n {\n text: trimmedData,\n },\n ];\n\n const lastChild = lastBlock.children.at(-1);\n\n /** It’s like normalizing and merging the text nodes. */\n if (\n lastChild &&\n TextApi.isText(lastChild) &&\n Object.keys(lastChild).length === 1\n ) {\n lastBlock.children.pop();\n\n const textNode = [\n {\n text: lastChild.text + trimmedData,\n },\n ];\n\n lastBlock.children.push(...textNode);\n } else {\n lastBlock.children.push(...textNode);\n }\n\n result = [...blocks.slice(0, -1), lastBlock];\n }\n\n if (addNewLine && !isCodeBlockOrTable) {\n result.push({\n children: [{ text: '' }],\n type: KEYS.p,\n });\n }\n\n if (unshiftNewLine && !isCodeBlockOrTable) {\n result.unshift({\n children: [{ text: '' }],\n type: KEYS.p,\n });\n }\n\n return result;\n};\n\nconst withoutDeserializeInMdx = (editor: PlateEditor, input: string) => {\n const mdxName = editor.getOption(AIChatPlugin, '_mdxName');\n\n if (mdxName) {\n const isMdxEnd = input.includes(`</${mdxName}>`);\n\n if (isMdxEnd) {\n editor.setOption(AIChatPlugin, '_mdxName', null);\n return false;\n } else {\n return [\n {\n children: [\n {\n text: input,\n },\n ],\n type: getPluginType(editor, KEYS.p),\n },\n ];\n }\n } else {\n const newMdxName = statMdxTagRegex.exec(input)?.[1];\n\n // Avoid incorrect detection in the code block\n if (input.startsWith(`<${newMdxName}`)) {\n editor.setOption(AIChatPlugin, '_mdxName', newMdxName ?? null);\n }\n }\n};\n","export const getChunkTrimmed = (\n chunk: string,\n {\n direction = 'right',\n }: {\n direction?: 'left' | 'right';\n } = {}\n) => {\n const str = direction === 'right' ? chunk.trimEnd() : chunk.trimStart();\n\n if (direction === 'right') {\n return chunk.slice(str.length);\n } else {\n return chunk.slice(0, chunk.length - str.length);\n }\n};\n\nexport function isCompleteCodeBlock(str: string) {\n const trimmed = str.trim();\n\n const startsWithCodeBlock = trimmed.startsWith('```');\n const endsWithCodeBlock = trimmed.endsWith('```');\n\n return startsWithCodeBlock && endsWithCodeBlock;\n}\n\nexport function isCompleteMath(str: string) {\n const trimmed = str.trim();\n\n const startsWithMath = trimmed.startsWith('$$');\n const endsWithMath = trimmed.endsWith('$$');\n\n return startsWithMath && endsWithMath;\n}\n","import { isCompleteMath } from './utils';\n\nexport const escapeInput = (data: string) => {\n let res = data;\n\n // test case: should correctly handle inline math\n if (\n data.startsWith('$$') &&\n !data.startsWith('$$\\n') &&\n !isCompleteMath(data)\n ) {\n res = data.replace('$$', String.raw`\\$\\$`);\n }\n\n return res;\n};\n","import type { TElement } from 'platejs';\nimport type { PlateEditor } from 'platejs/react';\n\nexport const getListNode = (editor: PlateEditor, node: TElement): TElement => {\n if (node.listStyleType && node.listStart) {\n const previousNode = editor.api.previous({\n at: editor.selection?.focus,\n })?.[0];\n\n // if previous node is also an indent list, don't need to do additional work\n if (previousNode?.listStyleType && previousNode?.listStart) {\n return node;\n } else {\n if (node.listStart === 1) return node;\n\n return {\n ...node,\n listRestartPolite: node.listStart,\n };\n }\n }\n\n return node;\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type TElement, type TText, isDefined, KEYS } from 'platejs';\n\nconst LIST_STYLE_TYPE = 'listStyleType';\n\nexport const isSameNode = (\n editor: PlateEditor,\n node1: TElement | TText,\n node2: TElement | TText\n) => {\n if (\n node1.type !== editor.getType(KEYS.p) ||\n node2.type !== editor.getType(KEYS.p)\n )\n return node1.type === node2.type;\n\n if (isDefined(node1[LIST_STYLE_TYPE]) || isDefined(node2[LIST_STYLE_TYPE])) {\n return node1[LIST_STYLE_TYPE] === node2[LIST_STYLE_TYPE];\n }\n\n return node1.type === node2.type;\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type Descendant, ElementApi } from 'platejs';\n\nimport type { SteamInsertChunkOptions } from '../streamInsertChunk';\n\nimport { getListNode } from './getListNode';\n\nexport const nodesWithProps = (\n editor: PlateEditor,\n nodes: Descendant[],\n options: SteamInsertChunkOptions\n): Descendant[] => {\n return nodes.map((node): Descendant => {\n if (ElementApi.isElement(node)) {\n return {\n ...getListNode(editor, node),\n ...options.elementProps,\n children: nodesWithProps(editor, node.children, options),\n };\n } else {\n return {\n ...options.textProps,\n ...node,\n text: node.text,\n };\n }\n });\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport {\n type Path,\n type SlateEditor,\n getPluginType,\n KEYS,\n NodeApi,\n PathApi,\n} from 'platejs';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\nimport { streamDeserializeInlineMd } from './streamDeserializeInlineMd';\nimport { streamDeserializeMd } from './streamDeserializeMd';\nimport { streamSerializeMd } from './streamSerializeMd';\nimport { isSameNode } from './utils/isSameNode';\nimport { nodesWithProps } from './utils/nodesWithProps';\n\nexport interface SteamInsertChunkOptions {\n elementProps?: any;\n textProps?: any;\n}\n\nconst getNextPath = (path: Path, length: number) => {\n let result = path;\n\n for (let i = 0; i < length; i++) {\n result = PathApi.next(result);\n }\n return result;\n};\n\n/** @experimental */\nexport function streamInsertChunk(\n editor: PlateEditor,\n chunk: string,\n options: SteamInsertChunkOptions = {}\n) {\n const { _blockChunks, _blockPath } = editor.getOptions(AIChatPlugin);\n\n if (_blockPath === null) {\n const blocks = streamDeserializeMd(editor, chunk);\n const path = getCurrentBlockPath(editor);\n const startBlock = editor.api.node(path)![0];\n\n const startInEmptyParagraph =\n NodeApi.string(startBlock).length === 0 &&\n startBlock.type === getPluginType(editor, KEYS.p);\n\n // if start in empty paragraph, remove it\n if (startInEmptyParagraph) {\n editor.tf.removeNodes({ at: path });\n }\n\n if (blocks.length > 0) {\n editor.tf.insertNodes(nodesWithProps(editor, [blocks[0]], options), {\n at: path,\n nextBlock: !startInEmptyParagraph,\n select: true,\n });\n\n editor.setOption(AIChatPlugin, '_blockPath', getCurrentBlockPath(editor));\n editor.setOption(AIChatPlugin, '_blockChunks', chunk);\n\n if (blocks.length > 1) {\n const nextBlocks = blocks.slice(1);\n\n const nextPath = getCurrentBlockPath(editor);\n\n editor.tf.insertNodes(nodesWithProps(editor, nextBlocks, options), {\n at: nextPath,\n nextBlock: true,\n select: true,\n });\n\n const lastBlock = editor.api.node(\n getNextPath(nextPath, nextBlocks.length)\n )!;\n\n editor.setOption(AIChatPlugin, '_blockPath', lastBlock[1]);\n\n const lastBlockChunks = streamSerializeMd(\n editor,\n {\n value: [lastBlock[0]],\n },\n chunk\n );\n\n editor.setOption(AIChatPlugin, '_blockChunks', lastBlockChunks);\n }\n }\n } else {\n const tempBlockChunks = _blockChunks + chunk;\n const tempBlocks = streamDeserializeMd(editor, tempBlockChunks);\n\n // console.log(\n // JSON.stringify(chunk),\n // 'chunk',\n // '-------------------------------------------------------------------------------------------'\n // );\n // console.log(\n // '🚀 ~ Streaming ~ tempBlockChunks:',\n // JSON.stringify(tempBlockChunks)\n // );\n\n // console.log('🚀 ~ Streaming ~ tempBlocks:', JSON.stringify(tempBlocks));\n\n if (tempBlocks.length === 0) {\n return console.warn(\n `unsupport md nodes: ${JSON.stringify(tempBlockChunks)}`\n );\n }\n\n if (tempBlocks.length === 1) {\n const currentBlock = editor.api.node(_blockPath)![0];\n\n // If the types are the same\n if (isSameNode(editor, currentBlock, tempBlocks[0])) {\n const chunkNodes = streamDeserializeInlineMd(editor as any, chunk);\n\n // Deserialize the chunk and add it to the end of the current block\n editor.tf.insertNodes(nodesWithProps(editor, chunkNodes, options), {\n at: editor.api.end(_blockPath),\n select: true,\n });\n\n const updatedBlock = editor.api.node(_blockPath)!;\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [updatedBlock[0]],\n },\n tempBlockChunks\n );\n\n const blockText = NodeApi.string(tempBlocks[0]);\n\n // Verify if the editor content matches the chunk\n if (\n serializedBlock === tempBlockChunks &&\n blockText === serializedBlock\n ) {\n editor.setOption(AIChatPlugin, '_blockChunks', tempBlockChunks);\n } else {\n editor.tf.replaceNodes(\n nodesWithProps(editor, [tempBlocks[0]], options),\n {\n at: _blockPath,\n select: true,\n }\n );\n\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [tempBlocks[0]],\n },\n tempBlockChunks\n );\n\n editor.setOption(\n AIChatPlugin,\n '_blockChunks',\n // one block includes multiple children\n tempBlocks[0].type === getPluginType(editor, KEYS.codeBlock) ||\n tempBlocks[0].type === getPluginType(editor, KEYS.table) ||\n tempBlocks[0].type === getPluginType(editor, KEYS.equation)\n ? tempBlockChunks\n : serializedBlock\n );\n }\n } else {\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [tempBlocks[0]],\n },\n tempBlockChunks\n );\n\n editor.tf.replaceNodes(\n nodesWithProps(editor, [tempBlocks[0]], options),\n {\n at: _blockPath,\n select: true,\n }\n );\n\n editor.setOption(AIChatPlugin, '_blockChunks', serializedBlock);\n }\n } else {\n editor.tf.replaceNodes(nodesWithProps(editor, [tempBlocks[0]], options), {\n at: _blockPath,\n select: true,\n });\n\n if (tempBlocks.length > 1) {\n const newEndBlockPath = getNextPath(_blockPath, tempBlocks.length - 1);\n\n editor.tf.insertNodes(\n nodesWithProps(editor, tempBlocks.slice(1), options),\n {\n at: PathApi.next(_blockPath),\n select: true,\n }\n );\n\n editor.setOption(AIChatPlugin, '_blockPath', newEndBlockPath);\n\n const endBlock = editor.api.node(newEndBlockPath)![0];\n\n const serializedBlock = streamSerializeMd(\n editor,\n {\n value: [endBlock],\n },\n tempBlockChunks\n );\n\n editor.setOption(AIChatPlugin, '_blockChunks', serializedBlock);\n }\n }\n }\n}\n\nexport const getCurrentBlockPath = (editor: SlateEditor) => {\n const getAnchorPreviousPath = (editor: SlateEditor): Path | undefined => {\n const anchorNode = editor\n .getApi(AIChatPlugin)\n .aiChat.node({ anchor: true });\n\n if (anchorNode) {\n return PathApi.previous(anchorNode[1])!;\n }\n };\n\n const getFocusPath = (editor: SlateEditor): Path | undefined => {\n return editor.selection?.focus.path.slice(0, 1);\n };\n\n const path = getAnchorPreviousPath(editor) ?? getFocusPath(editor) ?? [0];\n\n const entry = editor.api.node(path);\n\n // streaming in table or columns shouldn't remove them\n if (\n entry &&\n (entry[0].type === getPluginType(editor, KEYS.columnGroup) ||\n entry[0].type === getPluginType(editor, KEYS.table))\n ) {\n return editor.api.above()?.[1] ?? path;\n }\n\n return path;\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { type SerializeMdOptions, MarkdownPlugin } from '@platejs/markdown';\nimport {\n type Descendant,\n ElementApi,\n getPluginKey,\n KEYS,\n TextApi,\n} from 'platejs';\n\nimport {\n getChunkTrimmed,\n isCompleteCodeBlock,\n isCompleteMath,\n} from './utils/utils';\n\n// fixes test: should serialize heading with tailing line break\n// fixes test: incomplete line breaks\nconst trimEndHeading = (\n editor: PlateEditor,\n value: Descendant[]\n): { trimmedText: string; value: Descendant[] } => {\n const headingKeys = new Set([\n KEYS.h1,\n KEYS.h2,\n KEYS.h3,\n KEYS.h4,\n KEYS.h5,\n KEYS.h6,\n ]);\n const lastBlock = value.at(-1);\n\n if (\n lastBlock &&\n headingKeys.has(\n (getPluginKey(editor, lastBlock.type as string) ?? lastBlock.type) as any\n ) &&\n ElementApi.isElement(lastBlock)\n ) {\n const lastTextNode = lastBlock.children.at(-1);\n\n if (TextApi.isText(lastTextNode)) {\n const trimmedText = getChunkTrimmed(lastTextNode?.text as string);\n\n // Create a new lastBlock with immutable operations\n const newChildren = [\n ...lastBlock.children.slice(0, -1),\n { text: lastTextNode.text.trimEnd() },\n ];\n\n const newLastBlock = {\n ...lastBlock,\n children: newChildren,\n };\n\n return {\n trimmedText: trimmedText,\n value: [...value.slice(0, -1), newLastBlock],\n };\n }\n }\n\n return { trimmedText: '', value };\n};\n\nexport const streamSerializeMd = (\n editor: PlateEditor,\n options: SerializeMdOptions,\n chunk: string\n) => {\n const { value: optionsValue, ...restOptions } = options;\n const { value } = trimEndHeading(editor, optionsValue ?? editor.children);\n\n let result = '';\n\n result = editor.getApi(MarkdownPlugin).markdown.serialize({\n value: value,\n ...restOptions,\n });\n\n const trimmedChunk = getChunkTrimmed(chunk);\n\n if (isCompleteCodeBlock(result) && !chunk.endsWith('```')) {\n result = result.trimEnd().slice(0, -3) + trimmedChunk;\n }\n\n if (isCompleteMath(result) && !chunk.endsWith('$$')) {\n result = result.trimEnd().slice(0, -3) + trimmedChunk;\n }\n\n // clean HTML spaces and zero-width characters\n result = result.replace(/ /g, ' ');\n result = result.replace(/​/g, ' ');\n result = result.replace(/\\u200B/g, '');\n\n // remove extra \\n but not include \\n itself\n // FIXME maybe failed when chunk is more than two'\\n'\n if (trimmedChunk !== '\\n\\n') {\n result = result.trimEnd() + trimmedChunk;\n }\n\n // Handle empty paragraph case for streaming\n if (chunk.endsWith('\\n\\n')) {\n if (result === '\\n') {\n // Single empty paragraph case\n result = '';\n } else if (result.endsWith('\\n\\n')) {\n // Multiple paragraphs ending with empty paragraph\n result = result.slice(0, -1);\n }\n }\n\n // replace   to real space\n\n // remove Markdown escape characters (including those potentially added in the chunk)\n result = result.replace(/\\\\([\\\\`*_{}\\\\[\\]()#+\\-\\\\.!~<>|$])/g, '$1');\n\n return result;\n};\n","import { deserializeMd } from '@platejs/markdown';\nimport { BlockSelectionPlugin } from '@platejs/selection/react';\nimport {\n diffToSuggestions,\n getTransientSuggestionKey,\n SkipSuggestionDeletes,\n} from '@platejs/suggestion';\nimport {\n type Descendant,\n type SlateEditor,\n type TElement,\n type TIdElement,\n type TSuggestionData,\n type TSuggestionElement,\n ElementApi,\n KEYS,\n nanoid,\n TextApi,\n} from 'platejs';\n\nimport { AIChatPlugin } from '../AIChatPlugin';\n\nexport const applyAISuggestions = (editor: SlateEditor, content: string) => {\n const isBlockSelecting = editor.getOption(\n BlockSelectionPlugin,\n 'isSelectingSome'\n );\n\n const { chatNodes } = editor.getOptions(AIChatPlugin);\n\n if (isBlockSelecting) {\n const setReplaceIds = (ids: string[]) => {\n editor.setOption(AIChatPlugin, '_replaceIds', ids);\n };\n\n if (editor.getOption(AIChatPlugin, '_replaceIds').length === 0) {\n setReplaceIds(chatNodes.map((node) => node.id as string));\n }\n\n const diffNodes = getDiffNodes(editor, content);\n\n const replaceNodes = Array.from(\n editor.api.nodes<TIdElement>({\n at: [],\n match: (n: TIdElement) =>\n ElementApi.isElement(n) &&\n editor.getOption(AIChatPlugin, '_replaceIds').includes(n.id),\n })\n );\n\n replaceNodes.forEach(([node, path], index) => {\n const replaceNode = node as unknown as TSuggestionElement;\n const diffNode = diffNodes[index] as unknown as TSuggestionElement;\n\n const isSameString =\n SkipSuggestionDeletes(editor, replaceNode) ===\n SkipSuggestionDeletes(editor, diffNode);\n\n const isSameSuggestion =\n (replaceNode.suggestion as TSuggestionData | undefined)?.type ===\n (diffNode.suggestion as TSuggestionData | undefined)?.type;\n\n if (\n index === replaceNodes.length - 1 &&\n diffNodes.length > replaceNodes.length\n ) {\n editor.tf.replaceNodes(diffNodes.slice(index), {\n at: path,\n });\n }\n // Performance optimization\n if (isSameString && isSameSuggestion && node.id == diffNode.id) {\n return;\n }\n\n editor.tf.replaceNodes(diffNode, {\n at: path,\n });\n });\n\n editor\n .getApi(BlockSelectionPlugin)\n .blockSelection.set(diffNodes.map((node) => node.id as string));\n setReplaceIds(diffNodes.map((node) => node.id as string));\n } else {\n const diffNodes = getDiffNodes(editor, content);\n\n editor.tf.insertFragment(diffNodes);\n\n const nodes = Array.from(\n editor.api.nodes({\n at: [],\n mode: 'lowest',\n match: (n) => TextApi.isText(n) && !!n[getTransientSuggestionKey()],\n })\n );\n\n const range = editor.api.nodesRange(nodes);\n\n editor.tf.setSelection(range!);\n\n return;\n }\n};\n\nconst withProps = (\n diffNodes: Descendant[],\n chatNodes: Descendant[]\n): Descendant[] => {\n return diffNodes.map((node, index) => {\n if (!ElementApi.isElement(node)) return node;\n\n const originalNode = chatNodes?.[index] as TElement | undefined;\n\n return {\n ...node,\n ...(originalNode ?? { id: nanoid() }),\n children: node.children,\n };\n });\n};\n\nconst withTransient = (diffNodes: Descendant[]): Descendant[] => {\n return diffNodes.map((node) => {\n if (TextApi.isText(node)) {\n return {\n ...node,\n [getTransientSuggestionKey()]: true,\n };\n } else {\n return {\n ...node,\n children: withTransient(node.children),\n [getTransientSuggestionKey()]: true,\n };\n }\n });\n};\n\nconst withoutSuggestionAndComments = (nodes: Descendant[]): Descendant[] => {\n return nodes.map((node) => {\n if (TextApi.isText(node)) {\n if (node[KEYS.suggestion] || node[KEYS.comment]) {\n return {\n text: node.text,\n };\n }\n\n return node;\n }\n if (ElementApi.isElement(node)) {\n if (node[KEYS.suggestion]) {\n const nodeWithoutSuggestion: any = {};\n\n Object.keys(node).forEach((key) => {\n if (key !== KEYS.suggestion && !key.startsWith(KEYS.suggestion)) {\n nodeWithoutSuggestion[key] = node[key];\n }\n });\n\n return {\n ...nodeWithoutSuggestion,\n children: withoutSuggestionAndComments(node.children),\n };\n }\n\n return {\n ...node,\n children: withoutSuggestionAndComments(node.children),\n };\n }\n\n return node;\n });\n};\nconst getDiffNodes = (editor: SlateEditor, aiContent: string) => {\n /** Original document nodes */\n const chatNodes = withoutSuggestionAndComments(\n editor.getOption(AIChatPlugin, 'chatNodes')\n );\n\n const aiNodes = withProps(deserializeMd(editor, aiContent), chatNodes);\n\n const diffNodes = withTransient(\n diffToSuggestions(editor, chatNodes, aiNodes, {\n ignoreProps: ['id', 'listStart'],\n })\n );\n\n return diffNodes;\n};\n","'use client';\n\nimport type React from 'react';\n\nimport type { DebouncedFunc } from 'lodash';\n\nimport { serializeMd } from '@platejs/markdown';\nimport debounce from 'lodash/debounce.js';\nimport {\n type OmitFirst,\n type PluginConfig,\n type TElement,\n bindFirst,\n KEYS,\n NodeApi,\n} from 'platejs';\nimport { type PlateEditor, createTPlatePlugin } from 'platejs/react';\n\nimport type { CompleteOptions } from './utils/callCompletionApi';\n\nimport { renderCopilotBelowNodes } from './renderCopilotBelowNodes';\nimport { acceptCopilot } from './transforms/acceptCopilot';\nimport { acceptCopilotNextWord } from './transforms/acceptCopilotNextWord';\nimport { type GetNextWord, getNextWord } from './utils/getNextWord';\nimport { triggerCopilotSuggestion } from './utils/triggerCopilotSuggestion';\nimport { withCopilot } from './withCopilot';\n\nexport type CopilotPluginConfig = PluginConfig<\n 'copilot',\n CompletionState & {\n /**\n * AI completion options. See:\n * {@link https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion#parameters | AI SDK UI useCompletion Parameters}\n */\n completeOptions?: Partial<CompleteOptions>;\n /**\n * Debounce delay for auto triggering AI completion.\n *\n * @default 0\n */\n debounceDelay?: number;\n /** Get the next word to be inserted. */\n getNextWord?: GetNextWord;\n /** Render the ghost text. */\n renderGhostText?: (() => React.ReactNode) | null;\n shouldAbort?: boolean;\n /** The node id where the suggestion is located. */\n suggestionNodeId?: string | null;\n /** The text of the suggestion. */\n suggestionText?: string | null;\n /**\n * Conditions to auto trigger copilot, used in addition to triggerQuery.\n * Disabling defaults to:\n *\n * - Block above is empty\n * - Block above ends with a space\n * - There is already a suggestion\n */\n autoTriggerQuery?: (options: { editor: PlateEditor }) => boolean;\n /**\n * Get the prompt for AI completion.\n *\n * @default serializeMdNodes(editor.api.block({ highest: true }))\n */\n getPrompt?: (options: { editor: PlateEditor }) => string;\n /**\n * Conditions to trigger copilot. Disabling defaults to:\n *\n * - Selection is expanded\n * - Selection is not at the end of block\n */\n triggerQuery?: (options: { editor: PlateEditor }) => boolean;\n // query?: QueryEditorOptions;\n },\n {\n copilot: {\n triggerSuggestion: OmitFirst<typeof triggerCopilotSuggestion>;\n // Function to abort the current API request and reject the completion state.\n reject: () => false | undefined;\n setBlockSuggestion: (options: { text: string; id?: string }) => void;\n // Function to abort the current API request.\n stop: () => void;\n };\n },\n {\n copilot: {\n accept: OmitFirst<typeof acceptCopilot>;\n acceptNextWord: OmitFirst<typeof acceptCopilotNextWord>;\n };\n },\n {\n isSuggested?: (id: string) => boolean;\n }\n>;\n\ntype CompletionState = {\n abortController?: AbortController | null;\n // The current text completion.\n completion?: string | null;\n // The error thrown during the completion process, if any.\n error?: Error | null;\n // Boolean flag indicating whether a fetch operation is currently in progress.\n isLoading?: boolean;\n};\n\nexport const CopilotPlugin = createTPlatePlugin<CopilotPluginConfig>({\n key: KEYS.copilot,\n handlers: {\n onBlur: ({ api }) => {\n api.copilot.reject();\n },\n onMouseDown: ({ api }) => {\n api.copilot.reject();\n },\n },\n options: {\n abortController: null,\n completeOptions: {},\n completion: '',\n debounceDelay: 0,\n error: null,\n getNextWord: getNextWord,\n isLoading: false,\n renderGhostText: null,\n shouldAbort: true,\n suggestionNodeId: null,\n suggestionText: null,\n autoTriggerQuery: ({ editor }) => {\n if (\n editor.getOptions<CopilotPluginConfig>({ key: KEYS.copilot })\n .suggestionText\n ) {\n return false;\n }\n\n const isEmpty = editor.api.isEmpty(editor.selection, { block: true });\n\n if (isEmpty) return false;\n\n const blockAbove = editor.api.block();\n\n if (!blockAbove) return false;\n\n const blockString = NodeApi.string(blockAbove[0]);\n\n return blockString.at(-1) === ' ';\n },\n getPrompt: ({ editor }) => {\n const contextEntry = editor.api.block({ highest: true });\n\n if (!contextEntry) return '';\n\n return serializeMd(editor, {\n value: [contextEntry[0] as TElement],\n });\n },\n triggerQuery: ({ editor }) => {\n if (editor.api.isExpanded()) return false;\n\n const isEnd = editor.api.isAt({ end: true });\n\n if (!isEnd) return false;\n\n return true;\n },\n },\n})\n .overrideEditor(withCopilot)\n .extendSelectors<CopilotPluginConfig['selectors']>(({ getOptions }) => ({\n isSuggested: (id) => getOptions().suggestionNodeId === id,\n }))\n .extendTransforms(({ editor }) => ({\n accept: bindFirst(acceptCopilot, editor),\n acceptNextWord: bindFirst(acceptCopilotNextWord, editor),\n }))\n .extendApi<Omit<CopilotPluginConfig['api']['copilot'], 'reject'>>(\n ({ api, editor, getOptions, setOption, setOptions }) => {\n const debounceDelay = getOptions().debounceDelay;\n\n let triggerSuggestion = bindFirst(triggerCopilotSuggestion, editor);\n\n if (debounceDelay) {\n triggerSuggestion = debounce(\n bindFirst(triggerCopilotSuggestion, editor),\n debounceDelay\n ) as any;\n }\n\n return {\n triggerSuggestion,\n setBlockSuggestion: ({ id = getOptions().suggestionNodeId, text }) => {\n if (!id) {\n id = editor.api.block()![0].id as string;\n }\n\n setOptions({\n suggestionNodeId: id,\n suggestionText: text,\n });\n },\n stop: () => {\n const { abortController } = getOptions();\n\n (api.copilot.triggerSuggestion as DebouncedFunc<any>)?.cancel();\n\n if (abortController) {\n abortController.abort();\n setOption('abortController', null);\n }\n },\n };\n }\n )\n .extendApi(({ api, getOptions, setOptions }) => ({\n reject: () => {\n if (!getOptions().suggestionText?.length) return false;\n\n api.copilot.stop();\n\n setOptions({\n completion: null,\n suggestionNodeId: null,\n suggestionText: null,\n });\n },\n }))\n .extend({\n render: {\n belowNodes: renderCopilotBelowNodes,\n },\n shortcuts: {\n accept: {\n keys: 'tab',\n },\n reject: {\n keys: 'escape',\n },\n },\n });\n","'use client';\n\nimport React from 'react';\n\nimport { KEYS } from 'platejs';\nimport { type RenderNodeWrapperProps, getEditorPlugin } from 'platejs/react';\n\nimport type { CopilotPluginConfig } from './CopilotPlugin';\n\nexport const renderCopilotBelowNodes = ({\n editor,\n}: RenderNodeWrapperProps<CopilotPluginConfig>) => {\n const copilot = getEditorPlugin<CopilotPluginConfig>(editor, {\n key: KEYS.copilot,\n });\n\n const { renderGhostText: GhostText } = copilot.getOptions();\n\n if (!GhostText) return;\n\n return ({ children }: { children: React.ReactNode }) => {\n return (\n <React.Fragment>\n {children}\n\n <GhostText />\n </React.Fragment>\n );\n };\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { deserializeInlineMd } from '@platejs/markdown';\nimport { KEYS } from 'platejs';\n\nimport type { CopilotPluginConfig } from '../CopilotPlugin';\n\nexport const acceptCopilot = (editor: PlateEditor) => {\n const { suggestionText } = editor.getOptions<CopilotPluginConfig>({\n key: KEYS.copilot,\n });\n\n if (!suggestionText?.length) return false;\n\n editor.tf.insertFragment(deserializeInlineMd(editor, suggestionText));\n};\n","import { deserializeInlineMd } from '@platejs/markdown';\nimport { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { CopilotPluginConfig } from '../CopilotPlugin';\n\nimport { withoutAbort } from '../utils';\n\nexport const acceptCopilotNextWord = (editor: PlateEditor) => {\n const { api, getOptions } = getEditorPlugin<CopilotPluginConfig>(editor, {\n key: KEYS.copilot,\n });\n\n const { getNextWord, suggestionText } = getOptions();\n\n if (!suggestionText?.length) {\n return false;\n }\n\n const { firstWord, remainingText } = getNextWord!({ text: suggestionText });\n\n api.copilot.setBlockSuggestion({\n text: remainingText,\n });\n\n withoutAbort(editor, () => {\n editor.tf.insertFragment(deserializeInlineMd(editor, firstWord));\n });\n};\n","// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type CallCompletionApiOptions = {\n prompt: string;\n api?: string;\n body?: Record<string, any>;\n credentials?: RequestCredentials | undefined;\n fetch?: ReturnType<typeof getOriginalFetch> | undefined;\n headers?: HeadersInit | undefined;\n setAbortController?: (abortController: AbortController | null) => void;\n setCompletion?: (completion: string) => void;\n setError?: (error: Error | null) => void;\n setLoading?: (loading: boolean) => void;\n onError?: ((error: Error) => void) | undefined;\n onFinish?: ((prompt: string, completion: string) => void) | undefined;\n onResponse?: ((response: Response) => Promise<void> | void) | undefined;\n};\n\nexport type CompleteOptions = Omit<\n CallCompletionApiOptions,\n 'setAbortController' | 'setCompletion' | 'setError' | 'setLoading'\n>;\n\n// https://github.com/vercel/ai/blob/main/packages/ui-utils/src/call-completion-api.ts\n// https://github.com/vercel/ai/blob/642ba22ee33723f3aae9669c7e075322cffca2f3/packages/react/src/use-completion.ts\nexport async function callCompletionApi({\n api = '/api/completion',\n body,\n credentials,\n fetch = getOriginalFetch(),\n headers,\n prompt,\n setAbortController = () => {},\n setCompletion = () => {},\n setError = () => {},\n setLoading = () => {},\n onError,\n onFinish,\n onResponse,\n}: CallCompletionApiOptions) {\n try {\n setLoading(true);\n setError(null);\n\n const abortController = new AbortController();\n setAbortController(abortController);\n\n // Empty the completion immediately.\n setCompletion('');\n\n const res = await fetch(api, {\n body: JSON.stringify({\n prompt,\n ...body,\n }),\n credentials,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: 'POST',\n signal: abortController.signal,\n }).catch((error) => {\n throw error;\n });\n\n if (onResponse) {\n await onResponse(res);\n }\n if (!res.ok) {\n throw new Error(\n (await res.text()) || 'Failed to fetch the chat response.'\n );\n }\n if (!res.body) {\n throw new Error('The response body is empty.');\n }\n\n const { text } = await res.json();\n\n if (!text) {\n throw new Error('The response does not contain a text field.');\n }\n\n setCompletion(text);\n\n if (onFinish) {\n onFinish(prompt, text);\n }\n\n setAbortController(null);\n\n return text as string;\n } catch (error) {\n // Ignore abort errors as they are expected.\n if ((error as any).name === 'AbortError') {\n setAbortController(null);\n\n return null;\n }\n if (error instanceof Error && onError) {\n onError(error);\n }\n\n setError(error as Error);\n } finally {\n setLoading(false);\n }\n}\n","export type GetNextWord = (options: { text: string }) => {\n firstWord: string;\n remainingText: string;\n};\n\nexport const getNextWord: GetNextWord = ({ text }) => {\n if (!text) return { firstWord: '', remainingText: '' };\n\n // Check if the first non-space character is a CJK character\n const nonSpaceMatch = /^\\s*(\\S)/.exec(text);\n\n if (!nonSpaceMatch) return { firstWord: '', remainingText: '' };\n\n const firstNonSpaceChar = nonSpaceMatch[1];\n\n // Regular expression for matching CJK characters\n // 1. [\\u4E00-\\u9FA5] - Chinese Characters\n // 2. [\\u3040-\\u309F] - Japanese Hiragana\n // 3. [\\u30A0-\\u30FF] - Japanese Katakana\n // 4. [\\u3400-\\u4DBF] - CJK Extension A\n // 5. [\\u4E00-\\u9FFF] - CJK Unified Ideographs\n // 6. [\\uF900-\\uFAFF] - CJK Compatibility Ideographs\n // 7. [\\uAC00-\\uD7AF] - Korean Syllables\n // 8. [\\u1100-\\u11FF] - Korean Jamo\n const isCJKChar =\n /[\\u1100-\\u11FF\\u3040-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF]/.test(\n firstNonSpaceChar\n );\n\n let firstWord, remainingText;\n\n if (isCJKChar) {\n // CJK characters: match leading spaces + first character + optional punctuation\n const match =\n /^(\\s*)([\\u1100-\\u11FF\\u3040-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF])([\\u3000-\\u303F\\uFF00-\\uFFEF])?/.exec(\n text\n );\n\n if (match) {\n const [fullMatch, spaces = '', char = '', punctuation = ''] = match;\n firstWord = spaces + char + punctuation;\n remainingText = text.slice(firstWord.length);\n } else {\n firstWord = '';\n remainingText = text;\n }\n } else {\n // For non-CJK text (including mixed content), match until space or CJK char\n const match =\n /^(\\s*\\S+?)(?=[\\s\\u1100-\\u11FF\\u3040-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF]|$)/.exec(\n text\n );\n\n if (match) {\n firstWord = match[0];\n remainingText = text.slice(firstWord.length);\n } else {\n firstWord = text;\n remainingText = '';\n }\n }\n\n return { firstWord, remainingText };\n};\n","import { KEYS } from 'platejs';\nimport { type PlateEditor, getEditorPlugin } from 'platejs/react';\n\nimport type { CopilotPluginConfig } from '../CopilotPlugin';\n\nimport { callCompletionApi } from './callCompletionApi';\n\nexport const triggerCopilotSuggestion = async (editor: PlateEditor) => {\n const { api, getOptions, setOption } = getEditorPlugin<CopilotPluginConfig>(\n editor,\n {\n key: KEYS.copilot,\n }\n );\n\n const { completeOptions, getPrompt, isLoading, triggerQuery } = getOptions();\n\n if (isLoading || editor.getOptions({ key: KEYS.aiChat }).chat?.isLoading) {\n return false;\n }\n if (!triggerQuery!({ editor })) return false;\n\n // if (query && !queryEditor(editor, query)) return;\n\n const prompt = getPrompt!({ editor });\n\n if (prompt.length === 0) return false;\n\n api.copilot.stop();\n\n await callCompletionApi({\n prompt,\n onFinish: (_, completion) => {\n api.copilot.setBlockSuggestion({ text: completion });\n },\n ...completeOptions,\n setAbortController: (controller) =>\n setOption('abortController', controller),\n setCompletion: (completion) => setOption('completion', completion),\n setError: (error) => setOption('error', error),\n setLoading: (loading) => setOption('isLoading', loading),\n onError: (error) => {\n setOption('error', error);\n completeOptions?.onError?.(error);\n },\n });\n};\n","import type { PlateEditor } from 'platejs/react';\n\nimport { CopilotPlugin } from '..';\n\nexport const withoutAbort = (editor: PlateEditor, fn: () => void) => {\n editor.setOption(CopilotPlugin, 'shouldAbort', false);\n fn();\n editor.setOption(CopilotPlugin, 'shouldAbort', true);\n};\n","import type { OverrideEditor, PlateEditor } from 'platejs/react';\n\nimport { serializeInlineMd } from '@platejs/markdown';\nimport {\n type Operation,\n type SlateEditor,\n type TRange,\n RangeApi,\n} from 'platejs';\n\nimport type { CopilotPluginConfig } from './CopilotPlugin';\n\nimport { withoutAbort } from './utils/withoutAbort';\n\ntype CopilotBatch = PlateEditor['history']['undos'][number] & {\n shouldAbort: boolean;\n};\n\nconst getPatchString = (editor: SlateEditor, operations: Operation[]) => {\n let string = '';\n\n for (const operation of operations) {\n if (operation.type === 'insert_node') {\n const node = operation.node;\n const text = serializeInlineMd(editor, { value: [node] });\n string += text;\n } else if (operation.type === 'insert_text') {\n string += operation.text;\n }\n }\n\n return string;\n};\n\nexport const withCopilot: OverrideEditor<CopilotPluginConfig> = ({\n api,\n editor,\n getOptions,\n setOption,\n tf: { apply, insertText, redo, setSelection, undo, writeHistory },\n}) => {\n let prevSelection: TRange | null = null;\n\n return {\n transforms: {\n apply(operation) {\n const { shouldAbort } = getOptions();\n\n if (shouldAbort) {\n api.copilot.reject();\n }\n\n apply(operation);\n },\n insertText(text, options) {\n const suggestionText = getOptions().suggestionText;\n\n // When using IME input, it's possible to enter two characters at once.\n if (suggestionText?.startsWith(text)) {\n withoutAbort(editor, () => {\n editor.tf.withoutMerging(() => {\n const newText = suggestionText?.slice(text.length);\n setOption('suggestionText', newText);\n insertText(text);\n });\n });\n\n return;\n }\n\n insertText(text, options);\n },\n\n redo() {\n if (!getOptions().suggestionText) return redo();\n\n const topRedo = editor.history.redos.at(-1) as CopilotBatch;\n const prevSuggestion = getOptions().suggestionText;\n\n if (topRedo && topRedo.shouldAbort === false && prevSuggestion) {\n withoutAbort(editor, () => {\n const shouldRemoveText = getPatchString(editor, topRedo.operations);\n\n const newText = prevSuggestion.slice(shouldRemoveText.length);\n setOption('suggestionText', newText);\n\n redo();\n });\n\n return;\n }\n\n return redo();\n },\n\n setSelection(props) {\n setSelection(props);\n\n if (\n editor.selection &&\n (!prevSelection ||\n !RangeApi.equals(prevSelection, editor.selection)) &&\n getOptions().autoTriggerQuery!({ editor }) &&\n editor.api.isFocused()\n ) {\n void api.copilot.triggerSuggestion();\n }\n\n prevSelection = editor.selection;\n },\n\n undo() {\n if (!getOptions().suggestionText) return undo();\n\n const lastUndos = editor.history.undos.at(-1) as CopilotBatch;\n const oldText = getOptions().suggestionText;\n\n if (lastUndos && lastUndos.shouldAbort === false && oldText) {\n withoutAbort(editor, () => {\n const shouldInsertText = getPatchString(\n editor,\n lastUndos.operations\n );\n\n const newText = shouldInsertText + oldText;\n setOption('suggestionText', newText);\n\n undo();\n });\n\n return;\n }\n\n return undo();\n },\n\n writeHistory(stacks, batch) {\n if (!getOptions().isLoading) {\n batch.shouldAbort = getOptions().shouldAbort;\n }\n\n return writeHistory(stacks, batch);\n },\n },\n };\n};\n"],"mappings":";AAEA,SAAS,qBAAqB;;;ACF9B;AAAA,EAGE;AAAA,EACA;AAAA,EACA,QAAAA;AAAA,OACK;;;ACJA,IAAM,gBAAgB,CAC3B,QACA,OACA;AAAA,EACE;AACF,IAEI,CAAC,MACF;AACH,MAAI,CAAC,UAAU,CAAC,OAAO,WAAW,MAAM,KAAM;AAE9C,QAAM,UAAU,MAAM,IAAI,CAAC,UAAU;AAAA,IACnC,GAAG;AAAA,IACH,IAAI;AAAA,EACN,EAAE;AAEF,SAAO,GAAG,mBAAmB,MAAM;AACjC,WAAO,GAAG,YAAY,SAAS;AAAA,MAC7B,IAAI,OAAO,IAAI,IAAI,UAAU,OAAO,UAAW,MAAM,IAAI;AAAA,MACzD,QAAQ;AAAA,IACV,CAAC;AACD,WAAO,GAAG,SAAS,EAAE,MAAM,MAAM,CAAC;AAAA,EACpC,CAAC;AACH;;;ACzBA,SAA2C,eAAe,YAAY;AAE/D,IAAM,gBAAgB,CAC3B,QACA,EAAE,KAAK,CAAC,EAAE,IAAwB,CAAC,MAChC;AACH,QAAM,WAAW,cAAc,QAAQ,KAAK,EAAE;AAE9C,SAAO,GAAG,WAAW,UAAU;AAAA,IAC7B;AAAA,IACA,OAAO,CAAC,MAA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AAE9D,YAAI,iBAAiB;AACnB,0BAAgB,MAAM;AACtB,oBAAU,mBAAmB,IAAI;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,EACC,UAAU,CAAC,EAAE,KAAK,YAAY,WAAW,OAAO;AAAA,EAC/C,QAAQ,MAAM;AACZ,QAAI,CAAC,WAAW,EAAE,gBAAgB,OAAQ,QAAO;AAEjD,QAAI,QAAQ,KAAK;AAEjB,eAAW;AAAA,MACT,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,gBAAgB;AAAA,IAClB,CAAC;AAAA,EACH;AACF,EAAE,EACD,OAAO;AAAA,EACN,QAAQ;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,MACN,MAAM;AAAA,IACR;AAAA,IACA,QAAQ;AAAA,MACN,MAAM;AAAA,IACR;AAAA,EACF;AACF,CAAC;","names":["KEYS","KEYS","KEYS","isSelecting","NodeApi","NodeApi","BlockSelectionPlugin","bindFirst","ElementApi","getPluginType","KEYS","getTransientSuggestionKey","KEYS","KEYS","getTransientSuggestionKey","BlockSelectionPlugin","cloneDeep","KEYS","KEYS","NodeApi","TextApi","formattedBlocks","BlockSelectionPlugin","KEYS","cloneDeep","getPluginType","KEYS","KEYS","getEditorPlugin","getEditorPlugin","KEYS","isSelecting","BlockSelectionPlugin","KEYS","getEditorPlugin","getEditorPlugin","KEYS","isSelecting","BlockSelectionPlugin","ElementApi","KEYS","KEYS","ElementApi","KEYS","bindFirst","ElementApi","getPluginType","BlockSelectionPlugin","useEffect","KEYS","usePluginOption","usePluginOption","KEYS","useEffect","useEffect","BlockSelectionPlugin","useEditorPlugin","usePluginOption","useEditorPlugin","usePluginOption","useEffect","BlockSelectionPlugin","MarkdownPlugin","MarkdownPlugin","getPluginType","KEYS","TextApi","KEYS","ElementApi","ElementApi","MarkdownPlugin","TextApi","textNode","KEYS","getPluginType","getPluginType","KEYS","NodeApi","PathApi","MarkdownPlugin","ElementApi","KEYS","TextApi","KEYS","ElementApi","TextApi","MarkdownPlugin","PathApi","NodeApi","getPluginType","KEYS","serializedBlock","editor","deserializeMd","BlockSelectionPlugin","getTransientSuggestionKey","ElementApi","KEYS","TextApi","BlockSelectionPlugin","ElementApi","TextApi","getTransientSuggestionKey","KEYS","deserializeMd","bindFirst","KEYS","NodeApi","createTPlatePlugin","KEYS","getEditorPlugin","KEYS","deserializeInlineMd","KEYS","getEditorPlugin","fetch","KEYS","getEditorPlugin","getEditorPlugin","KEYS","getEditorPlugin","KEYS","getNextWord","deserializeInlineMd","RangeApi","RangeApi","createTPlatePlugin","KEYS","NodeApi","bindFirst"]}
|