1 | import { useRef } from 'react';
|
2 | import warning from "rc-util/es/warning";
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | export default function useCursor(input, focused) {
|
8 | var selectionRef = useRef(null);
|
9 | function recordCursor() {
|
10 |
|
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 |
|
26 |
|
27 |
|
28 | }
|
29 | }
|
30 |
|
31 | |
32 |
|
33 |
|
34 |
|
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 |