Overview
The insert node operation adds block or inline nodes to the document at a specific path. Used for inserting paragraphs, headings, lists, and other structured content.
Interface
interface InsertNodeOperation extends Operation {
type: 'insertNode';
path: Path;
node: Node;
}
interface Node {
type: string;
children?: Node[];
attributes?: Record<string, any>;
text?: string; // For text nodes
}Usage
// Insert paragraph
function insertParagraph(editor: Editor, position: Path) {
const operation: InsertNodeOperation = {
type: 'insertNode',
path: position,
node: {
type: 'paragraph',
children: [
{ type: 'text', text: '' }
]
}
};
editor.applyOperation(operation);
}
// Insert heading
function insertHeading(editor: Editor, position: Path, level: number, text: string) {
const operation: InsertNodeOperation = {
type: 'insertNode',
path: position,
node: {
type: 'heading',
attributes: { level },
children: [
{ type: 'text', text: text }
]
}
};
editor.applyOperation(operation);
}
// Insert list item
function insertListItem(editor: Editor, position: Path, text: string) {
const operation: InsertNodeOperation = {
type: 'insertNode',
path: position,
node: {
type: 'listItem',
children: [
{
type: 'paragraph',
children: [
{ type: 'text', text: text }
]
}
]
}
};
editor.applyOperation(operation);
}Inverse Operation
The inverse of insert node is delete node:
function getInverse(operation: InsertNodeOperation): DeleteNodeOperation {
return {
type: 'deleteNode',
path: operation.path,
deletedNode: operation.node // Store for undo
};
}Examples
// Example: Insert paragraph at cursor
function insertParagraphAtCursor(editor: Editor) {
const selection = editor.getSelection();
const position = [selection.start[0] + 1]; // After current block
const operation: InsertNodeOperation = {
type: 'insertNode',
path: position,
node: {
type: 'paragraph',
children: [
{ type: 'text', text: '' }
]
}
};
editor.applyOperation(operation);
// Move cursor to new paragraph
editor.setSelection({
start: [position[0], 0],
end: [position[0], 0]
});
}
// Example: Insert image
function insertImage(editor: Editor, position: Path, url: string) {
const operation: InsertNodeOperation = {
type: 'insertNode',
path: position,
node: {
type: 'image',
attributes: { src: url, alt: '' }
}
};
editor.applyOperation(operation);
}