Overview
The set node type operation changes a node's type (e.g., paragraph to heading, heading to paragraph) while preserving its content and children.
Interface
interface SetNodeTypeOperation extends Operation {
type: 'setNodeType';
path: Path;
nodeType: string; // New node type
previousType?: string; // Store previous type for undo
attributes?: Record<string, any>; // Optional new attributes
previousAttributes?: Record<string, any>; // Store previous attributes
}Usage
// Convert paragraph to heading
function paragraphToHeading(editor: Editor, paragraphPath: Path, level: number) {
const node = editor.getNodeAtPath(paragraphPath);
const operation: SetNodeTypeOperation = {
type: 'setNodeType',
path: paragraphPath,
nodeType: 'heading',
previousType: node.type,
attributes: { level },
previousAttributes: node.attributes
};
editor.applyOperation(operation);
}
// Convert heading to paragraph
function headingToParagraph(editor: Editor, headingPath: Path) {
const node = editor.getNodeAtPath(headingPath);
const operation: SetNodeTypeOperation = {
type: 'setNodeType',
path: headingPath,
nodeType: 'paragraph',
previousType: node.type,
previousAttributes: node.attributes
};
editor.applyOperation(operation);
}
// Change heading level
function changeHeadingLevel(editor: Editor, headingPath: Path, newLevel: number) {
const node = editor.getNodeAtPath(headingPath);
const operation: SetNodeTypeOperation = {
type: 'setNodeType',
path: headingPath,
nodeType: 'heading', // Same type
previousType: node.type,
attributes: { level: newLevel },
previousAttributes: { level: node.attributes.level }
};
editor.applyOperation(operation);
}
// Convert list item to paragraph
function listItemToParagraph(editor: Editor, itemPath: Path) {
const node = editor.getNodeAtPath(itemPath);
const operation: SetNodeTypeOperation = {
type: 'setNodeType',
path: itemPath,
nodeType: 'paragraph',
previousType: node.type,
previousAttributes: node.attributes
};
editor.applyOperation(operation);
}Inverse Operation
The inverse restores previous node type:
function getInverse(operation: SetNodeTypeOperation): SetNodeTypeOperation {
return {
type: 'setNodeType',
path: operation.path,
nodeType: operation.previousType!,
previousType: operation.nodeType,
attributes: operation.previousAttributes,
previousAttributes: operation.attributes
};
}