Overview
Toggle format is a composite operation that applies or removes formatting based on current state.
Usage
// Toggle format is a composite operation
function toggleFormat(editor: Editor, selection: Selection, format: string) {
const hasFormat = editor.hasFormat(selection, format);
if (hasFormat) {
// Remove format
editor.applyOperation({
type: 'removeFormat',
path: selection.start,
length: selection.length,
format: format
});
} else {
// Apply format
editor.applyOperation({
type: 'applyFormat',
path: selection.start,
length: selection.length,
format: format,
value: true
});
}
}
// In transaction
function toggleFormatInTransaction(editor: Editor, selection: Selection, format: string) {
const tx = editor.beginTransaction();
const hasFormat = editor.hasFormat(selection, format);
if (hasFormat) {
tx.add({
type: 'removeFormat',
path: selection.start,
length: selection.length,
format: format
});
} else {
tx.add({
type: 'applyFormat',
path: selection.start,
length: selection.length,
format: format,
value: true
});
}
tx.commit();
}