2021-11-09 03:53:39 +01:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2022-01-08 02:46:01 +01:00
|
|
|
/**
|
|
|
|
* Gecko has no .getSelection on ShadowRoot, only .activeElement
|
2021-11-09 03:53:39 +01:00
|
|
|
*/
|
|
|
|
export function getSelection(element: Node): Selection | null {
|
|
|
|
const root = element.getRootNode();
|
|
|
|
|
|
|
|
if (root.getSelection) {
|
|
|
|
return root.getSelection();
|
|
|
|
}
|
|
|
|
|
2021-11-18 10:18:39 +01:00
|
|
|
return document.getSelection();
|
2021-11-09 03:53:39 +01:00
|
|
|
}
|
2022-01-08 02:46:01 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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);
|
|
|
|
}
|
2022-01-19 01:15:53 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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;
|
|
|
|
}
|