import { getEditorSchema } from '../core/editor-runtime'; import { refuseVetoedWrite } from '../core/node-write-veto'; import { applyBuiltDocumentChange, getActiveUpdateRoot, runEditorTransaction, } from '../core/public-state'; import { withoutPlacement } from '../core/view-carets'; import { node as editorNode } from '../editor/node'; import { nodes as getNodes } from '../editor/nodes'; import { type Location, LocationApi } from '../interfaces'; import type { AnyEditor as Editor } from '../interfaces/editor'; import { isBlock as editorIsBlock, isEnd as editorIsEnd, isStart as editorIsStart, leaf as editorLeaf, parent as editorParent, range as editorRange, unhangRange as editorUnhangRange, } from '../interfaces/editor'; import { type Node, NodeApi, type NodeMatchPredicate, } from '../interfaces/node'; import { type Path, PathApi } from '../interfaces/path'; import type { Point } from '../interfaces/point'; import { RangeApi } from '../interfaces/range'; import { SelectionApi } from '../interfaces/selection'; import type { NodeMutationMethods, NodeSetNodesOptions, } from '../interfaces/transforms/node'; import { getDefined } from '../internal/get-defined'; import { select } from '../transforms-selection/select'; import { matchPath } from '../utils/match-path'; import { normalizeNodeMatch } from '../utils/node-match'; import { splitNodesKeepingType } from './split-nodes'; type SetNodeUpdate = { newProperties: Record; path: Path; properties: Record; }; export const NON_SETTABLE_NODE_PROPERTIES: ReadonlySet = new Set([ 'children', 'text', ...Object.getOwnPropertyNames(Object.prototype), ]); const getParentEntry = (editor: unknown, at: Location) => editorParent(editor as Editor, at); const isUntouchedEdgeText = ( editor: Editor, node: Node, path: Path, [start, end]: readonly [Point, Point] ) => { if (!NodeApi.isText(node) || PathApi.equals(start.path, end.path)) { return false; } if ( !(PathApi.equals(path, start.path) && start.offset === node.text.length) && !(PathApi.equals(path, end.path) && end.offset === 0) ) { return false; } const [parentNode] = getParentEntry(editor, path); // A void's text is empty, so a range edge inside it sits at both its start // and its end; the range still selects the whole void. return !( NodeApi.isElement(parentNode) && getEditorSchema(editor).isVoid(parentNode) ); }; const isEdgeInsideText = (node: Node, path: Path, edges: readonly Point[]) => NodeApi.isText(node) && edges.some( (edge) => PathApi.equals(edge.path, path) && edge.offset > 0 && edge.offset < node.text.length ); const isSoleText = (editor: Editor, path: Path) => { const [parentNode] = getParentEntry(editor, path); return ( NodeApi.isElement(parentNode) && typeof parentNode.type === 'string' && getEditorSchema(editor).getElementContent(parentNode.type)?.max === 1 ); }; export const setNodes = (( editor: Editor, props: Partial, options: NodeSetNodesOptions = {} ) => { runEditorTransaction(editor, (tx) => { const { at: optionAt, compare: optionCompare, hanging = false, match: optionMatch, marks = false, merge: optionMerge, mode: optionMode = 'lowest', split: optionSplit = false, voids: optionVoids = false, } = options; let match = normalizeNodeMatch(options.type, optionMatch); let at = optionAt === undefined ? tx.resolveTarget() : optionAt; let compare = optionCompare; const merge = optionMerge; let mode = optionMode; let split = optionSplit; let voids = optionVoids; let splitEdges: readonly [Point, Point] | undefined; let refusedEdges: Point[] = []; if (!at) { return; } if (SelectionApi.isNode(at)) { for (const target of at.paths) { setNodes(editor, props, { ...options, at: target }); } return; } const root = (SelectionApi.isNode(at) ? at.root : LocationApi.isRange(at) ? (at.anchor.root ?? at.focus.root) : undefined) ?? getActiveUpdateRoot(editor) ?? 'main'; if (marks) { if (PathApi.isPath(at)) { at = editorRange(editor, at); } if (!RangeApi.isRange(at)) { return; } const originalMatch = match; const markKeys = Object.keys(props).filter( (key) => !NON_SETTABLE_NODE_PROPERTIES.has(key) ); const marksMatch: NodeMatchPredicate = (node, path) => { if (!NodeApi.isText(node)) { return false; } if (originalMatch && !originalMatch(node, path)) { return false; } const [parentNode] = getParentEntry(editor, path); if (!NodeApi.isElement(parentNode)) { return false; } return ( markKeys.every((key) => getEditorSchema(editor).isTextPropertyAllowedAt(key, path, root) ) && (!getEditorSchema(editor).isVoid(parentNode) || getEditorSchema(editor).isMarkableVoid(parentNode)) ); }; const isExpandedRange = RangeApi.isExpanded(at); let markAcceptingVoidSelected = false; if (!isExpandedRange) { const [selectedNode, selectedPath] = editorNode(editor, at); if (marksMatch(selectedNode, selectedPath)) { const [parentNode] = getParentEntry(editor, selectedPath); markAcceptingVoidSelected = NodeApi.isElement(parentNode) && getEditorSchema(editor).isMarkableVoid(parentNode); } } if (!isExpandedRange && !markAcceptingVoidSelected) { return; } match = marksMatch; mode = 'lowest'; split = true; voids = true; } if (match == null) { match = SelectionApi.isNode(at) ? () => true : PathApi.isPath(at) ? matchPath(editor, at) : (n) => NodeApi.isElement(n) && editorIsBlock(editor, n); } if (!hanging && RangeApi.isRange(at)) { at = editorUnhangRange(editor, at, { voids }); } if (split && RangeApi.isRange(at)) { if ( RangeApi.isCollapsed(at) && editorLeaf(editor, at.anchor)[0].text.length > 0 ) { // If the range is collapsed in a non-empty node and 'split' is true, there's nothing to // set that won't get normalized away return; } const rangeAnchor = editor.anchor(at, { association: 'inward', deletion: 'nearest', }); const [start, end] = RangeApi.edges(at); const splitMode = mode === 'lowest' ? 'lowest' : 'highest'; const nodeMatch = getDefined(match); const refused = [start, end].map((point) => { const node = NodeApi.get(editor, point.path); return ( isEdgeInsideText(node, point.path, [point]) && nodeMatch(node, point.path) && isSoleText(editor, point.path) ); }); const splitMatchAt = (point: Point, isRefused: boolean): NodeMatchPredicate => (node, path) => !( isRefused && (splitMode === 'lowest' ? PathApi.isCommon(path, point.path) : PathApi.equals(path, point.path)) ) && nodeMatch(node, path); const endAtEndOfNode = editorIsEnd(editor, end, end.path); splitNodesKeepingType(editor, { at: end, match: splitMatchAt(end, refused[1]), mode: splitMode, voids, always: !endAtEndOfNode, }); const startAtStartOfNode = editorIsStart(editor, start, start.path); splitNodesKeepingType(editor, { at: start, match: splitMatchAt(start, refused[0]), mode: splitMode, voids, always: !startAtStartOfNode, }); at = getDefined(rangeAnchor.release()); if (RangeApi.isRange(at)) { splitEdges = RangeApi.edges(at); refusedEdges = splitEdges.filter((_, index) => refused[index]); } if (options.at == null) { const preserved = at; withoutPlacement(editor, () => select(editor, preserved)); } } if (!compare) { compare = (prop, nodeProp) => prop !== nodeProp; } const updates: SetNodeUpdate[] = []; for (const [node, path] of getNodes(editor, { at, match, mode, voids, })) { const properties: Record = {}; const newProperties: Record = {}; // You can't set properties on the editor node. if (path.length === 0) { continue; } if ( splitEdges && (isUntouchedEdgeText(editor, node, path, splitEdges) || isEdgeInsideText(node, path, refusedEdges)) ) { continue; } let hasChanges = false; for (const k in props) { if (NON_SETTABLE_NODE_PROPERTIES.has(k)) { continue; } const value: unknown = Object.hasOwn(node, k) ? node[k as keyof Node] : undefined; const newValue: unknown = props[k as keyof Node]; if (compare(newValue, value)) { hasChanges = true; // Omit new properties from the old properties list if (Object.hasOwn(node, k)) properties[k] = value; // Omit properties that have been removed from the new properties list if (merge) { if (newValue != null) newProperties[k] = merge(value, newValue); } else if (newValue != null) { newProperties[k] = marks ? getEditorSchema(editor).mergeTextPropertyAt( k, value, newValue, path, root ) : newValue; } } } if (hasChanges) { if (NodeApi.isElement(node) && typeof newProperties.type === 'string') { refuseVetoedWrite(editor, { kind: 'retype', node, path, root, type: newProperties.type, }); const changed = getEditorSchema(editor).elementForTypeChangeAt( node, newProperties.type, path, root ); for (const [key, value] of Object.entries( NodeApi.extractProps(node) )) { if ( key === 'type' || Object.hasOwn(props, key) || Object.hasOwn(changed, key) ) { continue; } properties[key] = value; } node.children.forEach((child, index) => { const kept = changed.children[index]; if (kept === child || !NodeApi.isText(child)) return; const removedProperties = Object.fromEntries( Object.entries(NodeApi.extractProps(child)).filter( ([key]) => !Object.hasOwn(kept, key) ) ); if (Object.keys(removedProperties).length === 0) return; updates.push({ path: path.concat(index), properties: removedProperties, newProperties: {}, }); }); } updates.push({ path, properties, newProperties, }); } } if (updates.length > 0) { applyBuiltDocumentChange(editor, (builder, innerRoot) => builder.setNodes(innerRoot, updates) ); } }); }) as NodeMutationMethods['setNodes'];