···
import { contains } from './element';
interface RestoreInputSelection {
4
-
element: HTMLElement;
4
+
element: HTMLInputElement;
method: 'setSelectionRange';
arguments: [number, number, 'forward' | 'backward' | 'none' | undefined];
···
25
-
const isInputElement = (node: HTMLElement): node is HTMLInputElement =>
25
+
const hasSelection = (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) {
38
-
} else if (isInputElement(target)) {
38
+
} else if (hasSelection(element)) {
method: 'setSelectionRange',
43
-
target.selectionStart!,
44
-
target.selectionEnd!,
45
-
target.selectionDirection || undefined,
43
+
element.selectionStart!,
44
+
element.selectionEnd!,
45
+
element.selectionDirection || undefined,
···
/** Restores a given snapshot of a selection, falling back to a simple focus. */
export const restoreSelection = (restore: RestoreSelection | null) => {
63
-
const target = restore && restore.element;
64
-
if (!restore || !target || !target.parentNode) {
63
+
if (!restore || !restore.element.parentNode) {
66
-
} else if (restore.method === 'setSelectionRange' && isInputElement(target)) {
68
-
target.setSelectionRange(...restore.arguments);
65
+
} else if (restore.method === 'setSelectionRange') {
66
+
restore.element.focus();
67
+
restore.element.setSelectionRange(...restore.arguments);
} else if (restore.method === 'range') {
const selection = window.getSelection()!;
70
+
restore.element.focus();
selection.removeAllRanges();
selection.addRange(restore.range);
74
+
restore.element.focus();