Skip to content

Commit 0eddadb

Browse files
committed
fix: editable.getSelection
1 parent 4ac0388 commit 0eddadb

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

src/core.js

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import createDefaultEvents from './create-default-events'
1212
import browser from 'bowser'
1313
import {textNodesUnder, getTextNodeAndRelativeOffset} from './util/element'
1414
import {binaryCursorSearch} from './util/binary_search'
15-
import {domArray, createRange} from './util/dom'
15+
import {domArray, createRange, nodeContainsRange} from './util/dom'
1616

1717
/**
1818
* The Core module provides the Editable class that defines the Editable.JS
@@ -315,21 +315,15 @@ export class Editable {
315315
* @returns A Cursor or Selection object or undefined.
316316
*/
317317
getSelection (editableHost) {
318-
let selection = this.dispatcher.selectionWatcher.getFreshSelection()
319-
if (!(editableHost && selection)) return selection
318+
const selection = this.dispatcher.selectionWatcher.getFreshSelection()
319+
if (!editableHost || !selection) return selection
320320

321321
const range = selection.range
322+
322323
// Check if the selection is inside the editableHost
323-
// The try...catch is required if the editableHost was removed from the DOM.
324-
try {
325-
if (range.compareNode(editableHost) !== range.NODE_BEFORE_AND_AFTER) {
326-
selection = undefined
327-
}
328-
} catch (e) {
329-
selection = undefined
324+
if (editableHost?.isConnected && nodeContainsRange(editableHost, range)) {
325+
return selection
330326
}
331-
332-
return selection
333327
}
334328

335329
/**

src/util/dom.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,14 @@ export const containsNodeText = (range, node) => {
142142
return comparisonStart <= 0 && comparisonEnd >= 0
143143
}
144144

145+
export const nodeContainsRange = (node, range) => {
146+
const nodeRange = document.createRange()
147+
nodeRange.selectNodeContents(node)
148+
const comparisonStart = range.compareBoundaryPoints(Range.START_TO_START, nodeRange)
149+
const comparisonEnd = range.compareBoundaryPoints(Range.END_TO_END, nodeRange)
150+
return comparisonStart >= 0 && comparisonEnd <= 0
151+
}
152+
145153
const isCharacterDataNode = (node) => {
146154
return node && (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.COMMENT_NODE)
147155
}

0 commit comments

Comments
 (0)