json-joy
Version:
Collection of libraries for building collaborative editing apps.
27 lines (26 loc) • 796 B
JavaScript
import * as React from 'react';
import { useBrowserLayoutEffect } from '../hooks';
export const useCaret = () => {
const ref = React.useRef(null);
const timer = React.useRef();
useBrowserLayoutEffect(() => {
const span = ref.current;
if (!span)
return;
clearTimeout(timer.current);
timer.current = setTimeout(() => {
const selection = window.getSelection();
if (!selection)
return;
const range = document.createRange();
range.setStart(span, 0);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}, 1);
return () => {
clearTimeout(timer.current);
};
});
return ref;
};