Skip to content

Instantly share code, notes, and snippets.

@thomsbg
Last active April 10, 2020 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomsbg/927d34a589c95980891dfbb94ebfc1a0 to your computer and use it in GitHub Desktop.
Save thomsbg/927d34a589c95980891dfbb94ebfc1a0 to your computer and use it in GitHub Desktop.
normalize delta
function eachHardLine(delta, fn) {
let buffer = new Delta();
new Delta(delta).eachLine((line, attributes) => {
buffer = buffer.concat(line);
if (attributes.br) {
buffer.insert('\n', attributes);
} else {
fn(buffer, attributes);
buffer = new Delta();
}
});
if (buffer.length > 0) {
fn(buffer, {});
}
}
// ensure all these constraints:
// - objects are isolated on their own line
// - empty attributes objects are omitted
// - adjacent string ops with the same attributes are merged
function normalize(delta) {
const result = new Delta();
eachHardLine(delta, (line, attributes) => {
let objectWasLast = false;
for (let [index, op] of line.ops.entries()) {
if (typeof op.insert === 'string') {
// objects must be the last op of the line,
// insert a line break to make it so
if (objectWasLast) result.insert('\n', attributes);
objectWasLast = false;
} else {
// objects must be the first op of the line,
// insert a line break to make it so
if (index > 0) result.insert('\n', attributes);
objectWasLast = true;
}
// use Delta#insert() to ensure that empty attributes are omitted
// and that adjacent string ops with the same attributes are merged
result.insert(op.insert, op.attributes);
}
// re-insert the original line break
result.insert('\n', attributes);
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment