mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-02-14 13:25:12 +00:00
36 lines
796 B
TypeScript
36 lines
796 B
TypeScript
import { useLayoutEffect, useRef } from 'react';
|
|
|
|
export const useAutoFocus = <T extends HTMLElement = HTMLElement>(
|
|
autoFocus?: boolean
|
|
) => {
|
|
const ref = useRef<T | null>(null);
|
|
|
|
useLayoutEffect(() => {
|
|
if (ref.current && autoFocus) {
|
|
// to avoid clicking on something focusable(e.g MenuItem),
|
|
// then the input will not be focused
|
|
setTimeout(() => {
|
|
ref.current?.focus();
|
|
}, 0);
|
|
}
|
|
}, [autoFocus]);
|
|
|
|
return ref;
|
|
};
|
|
|
|
export const useAutoSelect = <T extends HTMLInputElement = HTMLInputElement>(
|
|
autoSelect?: boolean
|
|
) => {
|
|
const ref = useRef<T | null>(null);
|
|
|
|
useLayoutEffect(() => {
|
|
if (ref.current && autoSelect) {
|
|
setTimeout(() => {
|
|
ref.current?.select();
|
|
}, 0);
|
|
}
|
|
}, [autoSelect, ref]);
|
|
|
|
return ref;
|
|
};
|