Anki/ts/domlib/location/document.ts
Henrik Giesel 610ef8f043
Save and restore location on ContentEditable (#1481)
* Add utility functions for saving and restoring the caret location

* Implement cross-browser.getSelection

* Save and restore location on ContentEditable

* Fix refocus by clicking on a field that had a non-collapsed selection
2021-11-09 12:53:39 +10:00

55 lines
1.7 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { SelectionLocation, SelectionLocationContent } from "./selection";
import { getSelectionLocation } from "./selection";
import { findNodeFromCoordinates } from "./node";
import { getSelection } from "../../lib/cross-browser";
export function saveSelection(base: Node): SelectionLocation | null {
return getSelectionLocation(base);
}
function unselect(selection: Selection): void {
selection.empty();
}
function setSelectionToLocationContent(
node: Node,
selection: Selection,
range: Range,
location: SelectionLocationContent,
) {
const focusLocation = location.focus;
const focusOffset = focusLocation.offset;
const focusNode = findNodeFromCoordinates(node, focusLocation.coordinates);
if (location.direction === "forward") {
range.setEnd(focusNode!, focusOffset!);
selection.addRange(range);
} /* location.direction === "backward" */ else {
selection.addRange(range);
selection.extend(focusNode!, focusOffset!);
}
}
export function restoreSelection(base: Node, location: SelectionLocation): void {
const selection = getSelection(base)!;
unselect(selection);
const range = new Range();
const anchorNode = findNodeFromCoordinates(base, location.anchor.coordinates);
range.setStart(anchorNode!, location.anchor.offset!);
if (location.collapsed) {
range.collapse(true);
selection.addRange(range);
} else {
setSelectionToLocationContent(
base,
selection,
range,
location as SelectionLocationContent,
);
}
}