Last active
April 10, 2020 21:51
-
-
Save thomsbg/927d34a589c95980891dfbb94ebfc1a0 to your computer and use it in GitHub Desktop.
normalize delta
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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