-
Notifications
You must be signed in to change notification settings - Fork 3
/
cross-browser.ts
35 lines (29 loc) · 1.03 KB
/
cross-browser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
/**
* Gecko has no .getSelection on ShadowRoot, only .activeElement
*/
export function getSelection(element: Node): Selection | null {
const root = element.getRootNode() as Document;
if (root.getSelection) {
return root.getSelection();
}
return document.getSelection();
}
/**
* Browser has potential support for multiple ranges per selection built in,
* but in reality only Gecko supports it.
* If there are multiple ranges, the latest range is the _main_ one.
*/
export function getRange(selection: Selection): Range | null {
const rangeCount = selection.rangeCount;
return rangeCount === 0 ? null : selection.getRangeAt(rangeCount - 1);
}
/**
* Avoid using selection.isCollapsed: it will always return
* true in shadow root in Gecko
* (this bug seems to also happens in Blink)
*/
export function isSelectionCollapsed(selection: Selection): boolean {
return getRange(selection)!.collapsed;
}