Overview
The update attributes operation modifies node attributes (like image src, link href, heading level) without changing the node's content or structure.
Interface
interface UpdateAttributesOperation extends Operation {
type: 'updateAttributes';
path: Path;
attributes: Record<string, any>; // New attribute values
previousAttributes?: Record<string, any>; // Store previous values for undo
}Usage
// Update image source
function updateImageSrc(editor: Editor, imagePath: Path, newSrc: string) {
const node = editor.getNodeAtPath(imagePath);
const operation: UpdateAttributesOperation = {
type: 'updateAttributes',
path: imagePath,
attributes: { src: newSrc },
previousAttributes: { src: node.attributes.src }
};
editor.applyOperation(operation);
}
// Update link href
function updateLinkHref(editor: Editor, linkPath: Path, newHref: string) {
const node = editor.getNodeAtPath(linkPath);
const operation: UpdateAttributesOperation = {
type: 'updateAttributes',
path: linkPath,
attributes: { href: newHref },
previousAttributes: { href: node.attributes.href }
};
editor.applyOperation(operation);
}
// Update heading level
function updateHeadingLevel(editor: Editor, headingPath: Path, newLevel: number) {
const node = editor.getNodeAtPath(headingPath);
const operation: UpdateAttributesOperation = {
type: 'updateAttributes',
path: headingPath,
attributes: { level: newLevel },
previousAttributes: { level: node.attributes.level }
};
editor.applyOperation(operation);
}
// Update multiple attributes
function updateMultipleAttributes(editor: Editor, path: Path, updates: Record<string, any>) {
const node = editor.getNodeAtPath(path);
const previous: Record<string, any> = {};
// Store previous values
for (const key in updates) {
previous[key] = node.attributes[key];
}
const operation: UpdateAttributesOperation = {
type: 'updateAttributes',
path: path,
attributes: updates,
previousAttributes: previous
};
editor.applyOperation(operation);
}Inverse Operation
The inverse restores previous attributes:
function getInverse(operation: UpdateAttributesOperation): UpdateAttributesOperation {
return {
type: 'updateAttributes',
path: operation.path,
attributes: operation.previousAttributes || {},
previousAttributes: operation.attributes
};
}