2023-02-22 20:13:33 +00:00
|
|
|
import { useRef, useState, useCallback, useEffect } from 'react';
|
|
|
|
|
|
|
|
export function useCaretPosition<
|
2023-09-04 15:20:36 +00:00
|
|
|
T extends HTMLInputElement | HTMLTextAreaElement = HTMLInputElement,
|
2023-02-22 20:13:33 +00:00
|
|
|
>() {
|
|
|
|
const node = useRef<T>(null);
|
|
|
|
const [start, setStart] = useState(0);
|
|
|
|
const [end, setEnd] = useState(0);
|
|
|
|
|
|
|
|
const updateCaret = useCallback(() => {
|
|
|
|
if (node.current) {
|
|
|
|
const { selectionStart, selectionEnd } = node.current;
|
|
|
|
|
|
|
|
setStart(selectionStart || 0);
|
|
|
|
setEnd(selectionEnd || 0);
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (node.current) {
|
|
|
|
node.current.setSelectionRange(start, end);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return { start, end, ref: node, updateCaret };
|
|
|
|
}
|