Skip to content

Commit

Permalink
track all implicit newline indexes and shift for delete
Browse files Browse the repository at this point in the history
  • Loading branch information
jhchen committed Aug 19, 2021
1 parent a02978f commit cf101f6
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions core/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,29 @@ class Editor {
}

applyDelta(delta) {
let consumeNextNewline = false;
this.scroll.update();
let scrollLength = this.scroll.length();
this.scroll.batchStart();
// Track indexes of violations of newline requirements
// (at end of doc and before block embeds)
const implicitNewlines = [];
const normalizedDelta = normalizeDelta(delta);
normalizedDelta.reduce((index, op) => {
const length = Op.length(op);
let attributes = op.attributes || {};
if (op.insert != null) {
if (typeof op.insert === 'string') {
let text = op.insert;
if (text.endsWith('\n') && consumeNextNewline) {
consumeNextNewline = false;
if (text.endsWith('\n') && implicitNewlines.length > 0) {
implicitNewlines.shift();
text = text.slice(0, -1);
}
if (
(index >= scrollLength ||
this.scroll.descendant(BlockEmbed, index)[0]) &&
!text.endsWith('\n')
) {
consumeNextNewline = true;
implicitNewlines.push(index + length);
}
this.scroll.insertAt(index, text);
const [line, offset] = this.scroll.line(index);
Expand All @@ -55,7 +57,7 @@ class Editor {
this.scroll.query(key, Scope.INLINE) != null &&
this.scroll.descendant(BlockEmbed, index)[0]
) {
consumeNextNewline = true;
implicitNewlines.push(index);
}
this.scroll.insertAt(index, key, op.insert[key]);
}
Expand All @@ -66,7 +68,10 @@ class Editor {
});
return index + length;
}, 0);
normalizedDelta.reduce((index, op) => {
const implicitDelta = implicitNewlines.reduce((delta, index) => {
return delta.retain(index).delete(1);
}, new Delta());
normalizedDelta.compose(implicitDelta).reduce((index, op) => {
if (typeof op.delete === 'number') {
this.scroll.deleteAt(index, op.delete);
return index;
Expand Down

0 comments on commit cf101f6

Please sign in to comment.