Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
quill-delta
Advanced tools
The quill-delta npm package is a library for representing and manipulating rich text documents and operational transformations. It is primarily used with the Quill text editor to apply changes to the document in a collaborative environment. Deltas are a data format that encode document changes and can be composed, transformed, and applied to documents.
Creating and manipulating deltas
This code sample demonstrates how to create a simple delta that represents the insertion of the text 'Hello, world!'.
{"ops":[{"insert":"Hello, world!"}]}
Composing deltas
This code sample shows how to compose a delta that retains the first 6 characters, deletes the next 5 characters, and then inserts the text 'Quill'.
{"ops":[{"retain":6},{"delete":5},{"insert":"Quill"}]}
Applying deltas to a document
This code sample illustrates applying a delta to a document that retains the first 6 characters and then inserts the bolded text 'Editor'.
{"ops":[{"retain":6},{"insert":"Editor","attributes":{"bold":true}}]}
The 'ot' package is a library for operational transformation, which is a technology for collaborative editing. It provides similar functionalities for representing and manipulating document changes. Compared to quill-delta, 'ot' is more generic and not specifically tied to the Quill editor.
ShareDB is a real-time database backend based on operational transformation. It allows for collaborative editing of JSON documents. While quill-delta focuses on text documents, ShareDB can handle a wider range of data types and structures.
Yjs is a CRDT-based (Conflict-free Replicated Data Types) framework for building collaborative applications. It supports rich text editing and can be integrated with various editors, including Quill. Yjs offers a different approach to collaborative editing compared to the operational transformation used by quill-delta.
Deltas are a simple, yet expressive format that can be used to describe contents and changes. The format is JSON based, and is human readable, yet easily parsible by machines. Deltas can describe any rich text document, includes all text and formatting information, without the ambiguity and complexity of HTML.
A Delta is made up of an Array of Operations, which describe changes to a document. They can be an insert
, delete
or retain
. Note operations do not take an index. They always describe the change at the current index. Use retains to "keep" or "skip" certain parts of the document.
Don’t be confused by its name Delta—Deltas represents both documents and changes to documents. If you think of Deltas as the instructions from going from one document to another, the way Deltas represent a document is by expressing the instructions starting from an empty document.
// Document with text "Gandalf the Grey"
// with "Gandalf" bolded, and "Grey" in grey
var 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, delete the next 4,
// and insert a white 'White'
var death = new Delta().retain(12)
.delete(4)
.insert('White', { color: '#fff' });
// {
// ops: [
// { retain: 12 },
// { delete: 4 },
// { insert: 'White', attributes: { color: '#fff' } }
// ]
// }
// Applying the above:
var restored = delta.compose(death);
// {
// ops: [
// { insert: 'Gandalf ', attributes: { bold: true } },
// { insert: 'the ' },
// { insert: 'White', attributes: { color: '#fff' } }
// ]
// }
This README describes Deltas in its general form and API functionality. Additional information on the way Quill specifically uses Deltas can be found on its own Delta docs. A walkthough of the motivation and design thinking behind Deltas are on Designing the Delta Format.
This format is suitable for Operational Transform and defines several functions to support this use case.
These methods called on or with non-document Deltas will result in undefined behavior.
Insert operations have an insert
key defined. A String value represents inserting text. Any other type represents inserting an embed (however only one level of object comparison will be performed for equality).
In both cases of text and embeds, an optional attributes
key can be defined with an Object to describe additonal formatting information. Formats can be changed by the retain operation.
// Insert a bolded "Text"
{ insert: "Text", attributes: { bold: true } }
// Insert a link
{ insert: "Google", attributes: { href: 'https://www.google.com' } }
// Insert an embed
{
insert: { image: 'https://octodex.github.com/images/labtocat.png' },
attributes: { alt: "Lab Octocat" }
}
// Insert another embed
{
insert: { video: 'https://www.youtube.com/watch?v=dMH0bHeiRNg' },
attributes: {
width: 420,
height: 315
}
}
Delete operations have a Number delete
key defined representing the number of characters to delete. All embeds have a length of 1.
// Delete the next 10 characters
{ delete: 10 }
Retain operations have a Number retain
key defined representing the number of characters to keep (other libraries might use the name keep or skip). An optional attributes
key can be defined with an Object to describe formatting changes to the character range. A value of null
in the attributes
Object represents removal of that key.
Note: It is not necessary to retain the last characters of a document as this is implied.
// Keep the next 5 characters
{ retain: 5 }
// Keep and bold the next 5 characters
{ retain: 5, attributes: { bold: true } }
// Keep and unbold the next 5 characters
// More specifically, remove the bold key in the attributes Object
// in the next 5 characters
{ retain: 5, attributes: { bold: null } }
Creates a new Delta object.
new Delta()
new Delta(ops)
new Delta(delta)
ops
- Array of operationsdelta
- Object with an ops
key set to an array of operationsNote: No validity/sanity check is performed when constructed with ops or delta. The new delta's internal ops array will also be assigned to ops or delta.ops without deep copying.
var delta = new Delta([
{ insert: 'Hello World' },
{ insert: '!', attributes: { bold: true }}
]);
var packet = JSON.stringify(delta);
var other = new Delta(JSON.parse(packet));
var chained = new Delta().insert('Hello World').insert('!', { bold: true });
Appends an insert operation. Returns this
for chainability.
insert(text, attributes)
insert(embed, attributes)
text
- String representing text to insertembed
- Number representing embed type to insertattributes
- Optional attributes to applydelta.insert('Text', { bold: true, color: '#ccc' });
delta.insert(1, { src: 'https://octodex.github.com/images/labtocat.png' });
Appends a delete operation. Returns this
for chainability.
delete(length)
length
- Number of characters to deletedelta.delete(5);
Appends a retain operation. Returns this
for chainability.
retain(length, attributes)
length
- Number of characters to retainattributes
- Optional attributes to applydelta.retain(4).retain(5, { color: '#0c6' });
Returns a new Delta representing the concatenation of this and another document Delta's operations.
concat(other)
other
- Document Delta to concatenateDelta
- Concatenated document Deltavar a = new Delta().insert('Hello');
var b = new Delta().insert('!', { bold: true });
// {
// ops: [
// { insert: 'Hello' },
// { insert: '!', attributes: { bold: true } }
// ]
// }
var concat = a.concat(b);
Returns a Delta representing the difference between two documents.
diff(other)
other
- Document Delta to diff againstDelta
- difference between the two documentsvar a = new Delta().insert('Hello');
var b = new Delta().insert('Hello!');
var diff = a.diff(b); // { ops: [{ retain: 5 }, { insert: '!' }] }
// a.compose(diff) == b
Iterates through document Delta, calling a given function with a Delta and attributes object, representing the line segment.
eachLine(predicate, newline)
predicate
- function to call on each line groupnewline
- newline character, defaults to \n
var delta = new Delta().insert('Hello\n\n')
.insert('World')
.insert({ image: 'octocat.png' })
.insert('\n', { align: 'right' })
.insert('!');
delta.eachline(function(line, attributes) {
console.log(line, attributes);
});
// Should log:
// { ops: [{ insert: 'Hello' }] }, {}
// { ops: [] }, {}
// { ops: [{ insert: 'World' }, { insert: { image: 'octocat.png' } }] }, { align: 'right' }
// { ops: [{ insert: '!' }] }, {}
Returns an array of operations that passes a given function.
filter(predicate)
predicate
- Function to test each operation against. Return true
to keep the operation, false
otherwise.Array
- Filtered resulting arrayvar delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
var text = delta.filter(function(op) {
return typeof op.insert === 'string';
}).map(function(op) {
return op.insert;
}).join('');
Iterates through operations, calling the provided function for each operation.
forEach(predicate)
predicate
- Function to call during iteration, passing in the current operation.delta.forEach(function(op) {
console.log(op);
});
Returns length of a Delta, which is the sum of the lengths of its operations.
length()
new Delta().insert('Hello').length(); // Returns 5
new Delta().insert('A').retain(2).delete(1) // Returns 4
Returns a new array with the results of calling provided function on each operation.
map(predicate)
predicate
- Function to call, passing in the current operation, returning an element of the new array to be returnedArray
- A new array with each element being the result of the given function.var delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
var text = delta.map(function(op) {
if (typeof op.insert === 'string') {
return op.insert;
} else {
return '';
}
}).join('');
Create an array op two arrays, the first with operations that pass the given function, the other that failed.
partition(predicate)
predicate
- Function to call, passing in the current operation, returning whether that operation passedArray
- A new array of two Arrays, the first with passed operations, the other with failed operationsvar delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
var results = delta.partition(function(op) {
return typeof op.insert === 'string';
});
var passed = results[0]; // [{ insert: 'Hello', attributes: { bold: true }},
{ insert: 'World'}]
var failed = results[1]; // [{ insert: { image: 'https://octodex.github.com/images/labtocat.png' }}]
Applies given function against an accumulator and each operation to reduce to a single value.
reduce(predicate, initialValue)
predicate
- Function to call per iteration, returning an accumulated valueinitialValue
- Initial value to pass to first call to predicateany
- the accumulated valuevar delta = new Delta().insert('Hello', { bold: true })
.insert({ image: 'https://octodex.github.com/images/labtocat.png' })
.insert('World!');
var length = delta.reduce(function(length, op) {
return length + (op.insert.length || 1);
}, 0);
Returns copy of delta with subset of operations.
slice()
slice(start)
slice(start, end)
start
- Start index of subset, defaults to 0end
- End index of subset, defaults to rest of operationsvar delta = new Delta().insert('Hello', { bold: true }).insert(' World');
// {
// ops: [
// { insert: 'Hello', attributes: { bold: true } },
// { insert: ' World' }
// ]
// }
var copy = delta.slice();
// { ops: [{ insert: 'World' }] }
var world = delta.slice(6);
// { ops: [{ insert: ' ' }] }
var space = delta.slice(5, 6);
Returns a Delta that is equivalent to applying the operations of own Delta, followed by another Delta.
compose(other)
other
- Delta to composevar a = new Delta().insert('abc');
var b = new Delta().retain(1).delete(1);
var composed = a.compose(b); // composed == new Delta().insert('ac');
Transform given Delta against own operations.
transform(other, priority)
transform(index)
- Alias for transformPosition
other
- Delta to transformpriority
- Boolean used to break tiesDelta
- transformed Deltavar a = new Delta().insert('a');
var b = new Delta().insert('b');
b = a.transform(b, true); // new Delta().retain(1).insert('b');
Transform an index against the delta. Useful for representing cursor/selection positions.
transformPosition(index)
index
- index to transformNumber
- transformed indexvar index = 12;
var transformedIndex = delta.transformPosition(index);
FAQs
Format for representing rich text documents and changes.
We found that quill-delta demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.