Skip to content

Commit

Permalink
fix: editable.getSelection
Browse files Browse the repository at this point in the history
  • Loading branch information
peyerluk committed Oct 17, 2023
1 parent 4ac0388 commit 0eddadb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
18 changes: 6 additions & 12 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import createDefaultEvents from './create-default-events'
import browser from 'bowser'
import {textNodesUnder, getTextNodeAndRelativeOffset} from './util/element'
import {binaryCursorSearch} from './util/binary_search'
import {domArray, createRange} from './util/dom'
import {domArray, createRange, nodeContainsRange} from './util/dom'

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

const range = selection.range

// Check if the selection is inside the editableHost
// The try...catch is required if the editableHost was removed from the DOM.
try {
if (range.compareNode(editableHost) !== range.NODE_BEFORE_AND_AFTER) {
selection = undefined
}
} catch (e) {
selection = undefined
if (editableHost?.isConnected && nodeContainsRange(editableHost, range)) {
return selection
}

return selection
}

/**
Expand Down
8 changes: 8 additions & 0 deletions src/util/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,14 @@ export const containsNodeText = (range, node) => {
return comparisonStart <= 0 && comparisonEnd >= 0
}

export const nodeContainsRange = (node, range) => {
const nodeRange = document.createRange()
nodeRange.selectNodeContents(node)
const comparisonStart = range.compareBoundaryPoints(Range.START_TO_START, nodeRange)
const comparisonEnd = range.compareBoundaryPoints(Range.END_TO_END, nodeRange)
return comparisonStart >= 0 && comparisonEnd <= 0
}

const isCharacterDataNode = (node) => {
return node && (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.COMMENT_NODE)
}
Expand Down

0 comments on commit 0eddadb

Please sign in to comment.