Improve definition of caretRangeFromPoint

This commit is contained in:
toasted-nutbread 2019-08-31 17:39:13 -04:00
parent 548607ea7f
commit d296ebd593

View File

@ -105,8 +105,8 @@ function docRangeFromPoint({x, y}) {
} }
} }
const range = document.caretRangeFromPoint(x, y); const range = caretRangeFromPoint(x, y);
if (range !== null && isPointInRange(point, range)) { if (range !== null) {
if (imposter !== null) { if (imposter !== null) {
docSetImposterStyle(imposterContainer.style, 'z-index', '-2147483646'); docSetImposterStyle(imposterContainer.style, 'z-index', '-2147483646');
docSetImposterStyle(imposter.style, 'pointer-events', 'none'); docSetImposterStyle(imposter.style, 'pointer-events', 'none');
@ -235,15 +235,29 @@ function isPointInRect(x, y, rect) {
y >= rect.top && y < rect.bottom); y >= rect.top && y < rect.bottom);
} }
if (typeof document.caretRangeFromPoint !== 'function') { const caretRangeFromPoint = (() => {
document.caretRangeFromPoint = (x, y) => { if (typeof document.caretRangeFromPoint === 'function') {
const position = document.caretPositionFromPoint(x, y); // Chrome, Edge
if (position && position.offsetNode && position.offsetNode.nodeType === Node.TEXT_NODE) { return (x, y) => document.caretRangeFromPoint(x, y);
const range = document.createRange();
range.setStart(position.offsetNode, position.offset);
range.setEnd(position.offsetNode, position.offset);
return range;
} }
if (typeof document.caretPositionFromPoint === 'function') {
// Firefox
return (x, y) => {
const position = document.caretPositionFromPoint(x, y);
const node = position.offsetNode;
if (node === null) {
return null; return null;
}
const range = document.createRange();
const offset = (node.nodeType === Node.TEXT_NODE ? position.offset : 0);
range.setStart(node, offset);
range.setEnd(node, offset);
return range;
}; };
} }
// No support
return () => null;
})();