What is a Delta and how does it work?
mainA Delta is a JSON-based format used to describe both rich text documents and the changes made to them.
Key Mental Models:
- Representing a Document: A Delta represents a document by expressing the sequence of instructions required to build that document starting from an empty state.
- Representing Changes: A Delta represents changes as an array of operations. Operations do not use absolute indices; instead, they describe changes at the current index. You use
retainoperations to skip or keep parts of the document to reach the desired position. - Operations: There are three types of operations:
insert: Adds text or an embed.delete: Removes a specific number of characters/embeds.retain: Keeps a range of characters and optionally modifies their attributes.
// Document with text "Gandalf the Grey"
// with "Gandalf" bolded, and "Grey" in grey
const delta = new Delta([
{ insert: 'Gandalf', attributes: { bold: true } },
{ insert: ' the ' },
{ insert: 'Grey', attributes: { color: '#ccc' } }
]);
// Change intended to be applied to above:
// Keep the first 12 characters, insert a white 'White'
// and delete the next four characters ('Grey')
const death = new Delta().retain(12)
.insert('White', { color: '#fff' })
.delete(4);
// Applying the change:
const restored = delta.compose(death);