···
import { contains } from './element';
interface RestoreInputSelection {
method: 'setSelectionRange';
arguments: [number, number, 'forward' | 'backward' | 'none' | undefined];
···
-
const isInputElement = (node: HTMLElement): node is HTMLInputElement =>
(node.nodeName === 'INPUT' || node.nodeName === 'TEXTAREA') &&
typeof (node as HTMLInputElement).selectionStart === 'number' &&
typeof (node as HTMLInputElement).selectionEnd === 'number';
···
const element = node && target && node !== target ? node : target;
if (!element || !target) {
-
} else if (isInputElement(target)) {
method: 'setSelectionRange',
-
target.selectionStart!,
-
target.selectionDirection || undefined,
···
/** Restores a given snapshot of a selection, falling back to a simple focus. */
export const restoreSelection = (restore: RestoreSelection | null) => {
-
const target = restore && restore.element;
-
if (!restore || !target || !target.parentNode) {
-
} else if (restore.method === 'setSelectionRange' && isInputElement(target)) {
-
target.setSelectionRange(...restore.arguments);
} else if (restore.method === 'range') {
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(restore.range);