From d58d7a0e10a186de7f0c1d7f5513fd9695c01a6e Mon Sep 17 00:00:00 2001 From: Soreine Date: Mon, 7 Nov 2016 14:51:39 +0100 Subject: [PATCH] More efficient update of Selection.isBackward --- src/models/node.js | 25 +++++++++++++++++++++++++ src/models/selection.js | 10 ++++------ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/models/node.js b/src/models/node.js index 8a17364ed..81347e194 100644 --- a/src/models/node.js +++ b/src/models/node.js @@ -470,6 +470,31 @@ const Node = { return descendant }, + /** + * True if the node has both descendants in that order, false + * otherwise. The order is depth-first, post-order. + * + * @param {String} key1 + * @param {String} key2 + * @return {Boolean} True if nodes are found in this order + */ + + areDescendantSorted(key1, key2) { + let sorted + + this.forEachDescendant(n => { + if (n.key === key1) { + sorted = true + return false + } else if (n.key === key2) { + sorted = false + return false + } + }) + + return sorted + }, + /** * Get the depth of a child node by `key`, with optional `startAt`. * diff --git a/src/models/selection.js b/src/models/selection.js index 237d58bf6..0e80ba028 100644 --- a/src/models/selection.js +++ b/src/models/selection.js @@ -332,12 +332,10 @@ class Selection extends new Record(DEFAULTS) { // If `isBackward` is not set, derive it. if (isBackward == null) { - let texts = node.getTexts() - let anchorIndex = texts.indexOf(anchorNode) - let focusIndex = texts.indexOf(focusNode) - isBackward = anchorIndex == focusIndex - ? anchorOffset > focusOffset - : anchorIndex > focusIndex + if (anchorKey === focusKey) { + isBackward = anchorOffset > focusOffset + } else { + isBackward = !node.areDescendantSorted(anchorKey, focusKey) } // Merge in any updated properties.