UNPKG

2.04 kBJavaScriptView Raw
1import { useRef } from 'react';
2import warning from "rc-util/es/warning";
3/**
4 * Keep input cursor in the correct position if possible.
5 * Is this necessary since we have `formatter` which may mass the content?
6 */
7export default function useCursor(input, focused) {
8 var selectionRef = useRef(null);
9 function recordCursor() {
10 // Record position
11 try {
12 var start = input.selectionStart,
13 end = input.selectionEnd,
14 value = input.value;
15 var beforeTxt = value.substring(0, start);
16 var afterTxt = value.substring(end);
17 selectionRef.current = {
18 start: start,
19 end: end,
20 value: value,
21 beforeTxt: beforeTxt,
22 afterTxt: afterTxt
23 };
24 } catch (e) {
25 // Fix error in Chrome:
26 // Failed to read the 'selectionStart' property from 'HTMLInputElement'
27 // http://stackoverflow.com/q/21177489/3040605
28 }
29 }
30
31 /**
32 * Restore logic:
33 * 1. back string same
34 * 2. start string same
35 */
36 function restoreCursor() {
37 if (input && selectionRef.current && focused) {
38 try {
39 var value = input.value;
40 var _selectionRef$current = selectionRef.current,
41 beforeTxt = _selectionRef$current.beforeTxt,
42 afterTxt = _selectionRef$current.afterTxt,
43 start = _selectionRef$current.start;
44 var startPos = value.length;
45 if (value.endsWith(afterTxt)) {
46 startPos = value.length - selectionRef.current.afterTxt.length;
47 } else if (value.startsWith(beforeTxt)) {
48 startPos = beforeTxt.length;
49 } else {
50 var beforeLastChar = beforeTxt[start - 1];
51 var newIndex = value.indexOf(beforeLastChar, start - 1);
52 if (newIndex !== -1) {
53 startPos = newIndex + 1;
54 }
55 }
56 input.setSelectionRange(startPos, startPos);
57 } catch (e) {
58 warning(false, "Something warning of cursor restore. Please fire issue about this: ".concat(e.message));
59 }
60 }
61 }
62 return [recordCursor, restoreCursor];
63}
\No newline at end of file