import type { Anchor } from '../core/anchor'; import { valueRootIndex } from '../core/change/document-change'; import { getEditorSchema } from '../core/editor-runtime'; import { applyBuiltDocumentChange, finalizeTransactionRepresentation, getActiveDocumentChangeBuilder, getActiveUpdateRoot, getCurrentSelection, profileCoreDuration, runEditorTransaction, } from '../core/public-state'; import { mapCanonicalRepresentationPoint } from '../core/representation'; import { node as getNode } from '../editor/node'; import { nodes as getNodes } from '../editor/nodes'; import { type Element, type Location, LocationApi, SelectionApi, } from '../interfaces'; import type { AnyEditor as Editor } from '../interfaces/editor'; import { after as editorAfter, isBlock as editorIsBlock, isEdge as editorIsEdge, isEnd as editorIsEnd, isStart as editorIsStart, isVoid as editorIsVoid, levels as editorLevels, parent as editorParent, point as editorPoint, void as editorVoid, } from '../interfaces/editor'; import { type Ancestor, type Node, NodeApi, type NodeEntry, } from '../interfaces/node'; import { type Path, PathApi } from '../interfaces/path'; import type { Point } from '../interfaces/point'; import { type Range, RangeApi } from '../interfaces/range'; import type { NodeMutationMethods, NodeSplitNodesOptions, } from '../interfaces/transforms/node'; import { getDefined } from '../internal/get-defined'; import { select } from '../transforms-selection/select'; import { readRemovalLanding, removeText } from '../transforms-text/delete-text'; import { isInTextCell, readGridCell, } from '../transforms-text/delete-text-grid'; import { normalizeNodeMatch } from '../utils/node-match'; import { insertNodes } from './insert-nodes'; const isTextCellPath = (editor: Editor, path: Path) => { const cell = readGridCell(editor, path); return !!cell && PathApi.equals(cell, path) && isInTextCell(editor, path); }; /** * A grid cell that holds its text directly never divides. A split at a point * or range lands where its removal lands, a split above the lowest block * divides any grid it lands in, and a split by path divides the path's * parent, or the node itself at a position. */ export const dividesTextCell = ( editor: Editor, at: Location, { mode = 'lowest', position, }: Pick = {} ) => { if (LocationApi.isPath(at)) { return ( at.length > 0 && isTextCellPath(editor, position == null ? PathApi.parent(at) : at) ); } const landed = readRemovalLanding(editor, at, (path) => mode === 'lowest' ? isInTextCell(editor, path) : readGridCell(editor, path) !== null ); return !landed || landed.includes(true); }; const deleteRange = (editor: Editor, range: Range): Point | null => { if (RangeApi.isCollapsed(range)) { return range.anchor; } const [start, end] = RangeApi.edges(range); const [endBlock] = getNodes(editor, { at: end, match: (node) => NodeApi.isElement(node) && editorIsBlock(editor, node), mode: 'highest', }); const preserveEndPoint = Boolean(editorVoid(editor, { at: start, mode: 'highest' })) || Boolean(endBlock && editorIsStart(editor, end, endBlock[1])); const endAnchor = editor.anchor(end, { association: 'forward', deletion: 'nearest', }); const removal = removeText(editor, { at: range, writes: true }); const preservedEnd = endAnchor.release(); if (!removal) return null; if (removal.kind === 'grid') return removal.landing; const selection = getCurrentSelection(editor); return preserveEndPoint ? preservedEnd : SelectionApi.isText(selection) ? selection.anchor : preservedEnd; }; const getTextEndForwardPoint = ( editor: Editor, point: Point, highestPath: Path ): Point | null => { if (highestPath.length >= point.path.length) { return null; } const [node] = getNode(editor, point.path); if ( !NodeApi.isText(node) || node.text !== '' || point.offset !== node.text.length ) { return null; } const nextPath = PathApi.next(point.path); if (!NodeApi.has(editor, nextPath)) { return null; } return editorPoint(editor, nextPath, { edge: 'start' }); }; const isTextStartSplit = (node: Node, point: Point, path: Path) => NodeApi.isText(node) && PathApi.equals(path, point.path) && point.offset === 0; const isInlineStartSplit = ( editor: Editor, node: Node, point: Point, path: Path ) => NodeApi.isElement(node) && getEditorSchema(editor).isInline(node) && editorIsStart(editor, point, path); const getSplitProperties = ( editor: Editor, node: Node, path: Path, root: string, keepType: boolean ) => NodeApi.isText(node) ? { ...getEditorSchema(editor).textPropertiesForSplitAt(node, path, root), } : NodeApi.isElement(node) ? keepType ? getEditorSchema(editor).elementPropertiesForSplitAt(node, path, root) : getElementSplitProperties(editor, node, path, root) : NodeApi.extractProps(node); const getElementSplitProperties = ( editor: Editor, node: Element, path: Path, root: string ) => { const schema = getEditorSchema(editor); const props = schema.elementPropertiesForSplitAt(node, path, root); const placed = schema.placeElementAt( { ...props, children: node.children, type: node.type }, { at: PathApi.next(path), root } ); return placed ? NodeApi.extractProps(placed) : props; }; const ensureStartPointAfterHighestSplit = ( editor: Editor, path: Path ): Point | null => { const [first, ...rest] = path; const top = valueRootIndex( getActiveDocumentChangeBuilder(editor).value, getActiveUpdateRoot(editor) ?? 'main' ).child(getDefined(first)) as Node | undefined; if (!top || !NodeApi.getIf(top, rest)) return null; const [node, innerPath] = NodeApi.first(top, rest); const textPath = [getDefined(first), ...innerPath]; if (NodeApi.isText(node)) { return { path: textPath, offset: 0 }; } if (NodeApi.isElement(node) && node.children.length === 0) { const point = { path: textPath.concat(0), offset: 0 }; applyBuiltDocumentChange(editor, (builder, root) => builder.insertNode(root, point.path, { text: '' }) ); return point; } return null; }; const runSplitNodes = ( editor: Editor, options: NodeSplitNodesOptions, keepType: boolean ) => { runEditorTransaction(editor, (tx) => { profileCoreDuration('split-nodes-transaction', () => { const { mode = 'lowest', voids = false } = options; let { height = 0, always = false } = options; const hasExplicitSelector = options.match != null || options.type != null; let match = normalizeNodeMatch(options.type, options.match); let at = profileCoreDuration('split-nodes-resolve-target', () => tx.resolveTarget({ at: options.at }) ); if (!at) { return; } if (SelectionApi.isNode(at)) return; if ( !hasExplicitSelector && (LocationApi.isPoint(at) || LocationApi.isRange(at)) ) { const point = LocationApi.isRange(at) ? RangeApi.start(at) : at; const [block] = getNodes(editor, { at: point, match: (node) => NodeApi.isElement(node) && editorIsBlock(editor, node), mode: 'lowest', voids: true, }); if (block && getEditorSchema(editor).isObject(block[0])) return; } if (!hasExplicitSelector && dividesTextCell(editor, at, options)) return; if (match == null) { match = (n) => NodeApi.isElement(n) && editorIsBlock(editor, n); } if (LocationApi.isRange(at)) { at = deleteRange(editor, at); if (!at) { return; } } let targetWasPath = false; if (LocationApi.isPath(at)) { targetWasPath = true; if (at.length === 0) { throw new Error('Cannot split the editor root.'); } if (options.position != null) { const path = at; const [node] = getNode(editor, path); if (!hasExplicitSelector || match(node, path)) { applyBuiltDocumentChange(editor, (builder, root) => builder.splitNode( root, path, getDefined(options.position), getSplitProperties(editor, node, path, root, keepType) ) ); return; } always = true; at = NodeApi.isText(node) ? { path, offset: options.position } : NodeApi.isElement(node) ? editorPoint( editor, options.position < node.children.length ? path.concat(options.position) : path, { edge: options.position < node.children.length ? 'start' : 'end', } ) : null; if (!at) return; } if (LocationApi.isPath(at)) { const path = at; const point = profileCoreDuration('split-nodes-path-point', () => editorPoint(editor, path) ); const [parent] = profileCoreDuration('split-nodes-path-parent', () => ( editorParent as ( editor: unknown, at: Location ) => NodeEntry )(editor, path) ); if (!hasExplicitSelector) match = (n) => n === parent; height = point.path.length - path.length + 1; at = point; always = true; } } if (!LocationApi.isPoint(at)) { return; } let splitPoint: Point = at; const beforeAnchor = profileCoreDuration( 'split-nodes-before-anchor', () => editor.anchor(splitPoint, { association: 'backward', deletion: 'nearest', }) ); let afterAnchor: Anchor | undefined; try { const [highest] = profileCoreDuration('split-nodes-find-highest', () => getNodes(editor, { at: splitPoint, match, mode, voids, }) ); if (!highest) { return; } const voidMatch = profileCoreDuration('split-nodes-void-match', () => editorVoid(editor, { at: splitPoint, mode: 'highest', }) ); if (!voids && voidMatch) { const [voidNode, voidPath] = voidMatch; if (getEditorSchema(editor).isInline(voidNode)) { let after = editorAfter(editor, voidPath); if (!after) { const text = { text: '' }; const afterPath = PathApi.next(voidPath); insertNodes(editor, text, { at: afterPath, voids }); after = getDefined(editorPoint(editor, afterPath)); } splitPoint = after; always = true; } const siblingHeight = splitPoint.path.length - voidPath.length; height = siblingHeight + 1; always = true; } const depth = splitPoint.path.length - height; const [, highestPath] = highest; const [splitText] = getNode(editor, splitPoint.path); const preserveLeftPoint = !always && NodeApi.isText(splitText) && splitPoint.offset === splitText.text.length; const textEndForwardPoint = always ? profileCoreDuration('split-nodes-text-end-forward-point', () => getTextEndForwardPoint(editor, splitPoint, highestPath) ) : null; afterAnchor = profileCoreDuration('split-nodes-after-anchor', () => editor.anchor(textEndForwardPoint ?? splitPoint, { association: 'forward', deletion: 'nearest', }) ); const lowestPath = splitPoint.path.slice(0, depth); let rightHighestPath: Path | null = null; let position = height === 0 ? splitPoint.offset : splitPoint.path[depth]; let didSplitDescendant = false; profileCoreDuration('split-nodes-levels-loop', () => { for (const [node, path] of editorLevels(editor, { at: lowestPath, reverse: true, voids, })) { let split = false; if ( path.length < highestPath.length || path.length === 0 || (NodeApi.isElement(node) && (getEditorSchema(editor).isObject(node) || (!voids && editorIsVoid(editor, node)))) ) { break; } const point = getDefined(beforeAnchor.resolve()); const isEnd = editorIsEnd(editor, point, path); if ( (textEndForwardPoint && PathApi.equals(path, splitPoint.path)) || (always && (isTextStartSplit(node, splitPoint, path) || (!targetWasPath && isInlineStartSplit(editor, node, splitPoint, path)))) ) { split = false; } else if ( didSplitDescendant || always || !editorIsEdge(editor, point, path) ) { split = true; const startsParentNewHalf = path.length > highestPath.length; if (keepType && !startsParentNewHalf && NodeApi.isElement(node)) { const placed = getEditorSchema(editor).placeElementAt(node, { at: PathApi.next(path), root: getActiveUpdateRoot(editor) ?? 'main', }); if (placed && placed.type !== node.type) { throw new Error( `Split destination cannot contain "${node.type}" without changing its type.` ); } } applyBuiltDocumentChange(editor, (builder, root) => builder.splitNode( root, path, position, getSplitProperties( editor, node, path, root, keepType || startsParentNewHalf ) ) ); didSplitDescendant = true; rightHighestPath = PathApi.next(path); } position = getDefined(path.at(-1)) + (split || isEnd ? 1 : 0); } }); if (options.at == null) { profileCoreDuration('split-nodes-select-after', () => { const rawResultPoint = preserveLeftPoint ? editorPoint(editor, highestPath, { edge: 'end' }) : rightHighestPath ? ensureStartPointAfterHighestSplit(editor, rightHighestPath) : null; const representationStep = finalizeTransactionRepresentation(editor); const root = getActiveUpdateRoot(editor) ?? 'main'; const representationBefore = representationStep?.indexedBefore.get(root); const representationAfter = representationStep?.indexedAfter.get(root); const mappedResultPoint = rawResultPoint && representationStep && representationBefore && representationAfter ? mapCanonicalRepresentationPoint( editor, representationBefore, representationAfter, representationStep.change, root, rawResultPoint, preserveLeftPoint ? -1 : 1 ) : rawResultPoint; const point = mappedResultPoint || afterAnchor?.resolve() || beforeAnchor.resolve() || editorPoint(editor, [], { edge: 'end' }); select(editor, point); }); } } finally { profileCoreDuration('split-nodes-release-anchors', () => { beforeAnchor.release(); afterAnchor?.release(); }); } }); }); }; export const splitNodes = (( editor: Editor, options: NodeSplitNodesOptions = {} ) => runSplitNodes(editor, options, false)) as NodeMutationMethods['splitNodes']; export const splitNodesKeepingType = ( editor: Editor, options: NodeSplitNodesOptions ) => runSplitNodes(editor, options, true);