Overview
The insert text operation adds text content to the document at a specific path. It's the most common operation for user input.
Interface
interface InsertTextOperation extends Operation {
type: 'insertText';
path: Path;
text: string;
marks?: Mark[]; // Optional formatting marks
}
// Path represents position in document tree
type Path = number[];
// Mark represents text formatting
interface Mark {
type: string; // e.g., 'bold', 'italic'
value?: any;
}Usage
// Basic usage
function insertText(editor: Editor, position: Path, text: string) {
const operation: InsertTextOperation = {
type: 'insertText',
path: position,
text: text
};
editor.applyOperation(operation);
}
// With formatting marks
function insertBoldText(editor: Editor, position: Path, text: string) {
const operation: InsertTextOperation = {
type: 'insertText',
path: position,
text: text,
marks: [{ type: 'bold', value: true }]
};
editor.applyOperation(operation);
}
// In transaction
function insertTextInTransaction(editor: Editor, position: Path, text: string) {
const tx = editor.beginTransaction();
tx.add({
type: 'insertText',
path: position,
text: text
});
tx.commit();
}Inverse Operation
The inverse of insert text is delete text:
function getInverse(operation: InsertTextOperation): DeleteTextOperation {
return {
type: 'deleteText',
path: operation.path,
length: operation.text.length
};
}
// Usage in undo
function undoInsertText(editor: Editor, operation: InsertTextOperation) {
const inverse = getInverse(operation);
editor.applyOperation(inverse);
}Examples
// Example: User types "Hello"
function handleUserInput(editor: Editor, text: string) {
const selection = editor.getSelection();
const operation: InsertTextOperation = {
type: 'insertText',
path: selection.start,
text: text
};
editor.applyOperation(operation);
// Update selection
editor.setSelection({
start: [selection.start[0], selection.start[1] + text.length],
end: [selection.start[0], selection.start[1] + text.length]
});
}
// Example: Insert with existing marks
function insertWithCurrentMarks(editor: Editor, text: string) {
const selection = editor.getSelection();
const activeMarks = editor.getActiveMarks(selection);
const operation: InsertTextOperation = {
type: 'insertText',
path: selection.start,
text: text,
marks: activeMarks
};
editor.applyOperation(operation);
}