Skip to content

There can be more than Notion and Miro. AFFiNE(pronounced [ə‘fain]) is a next-gen knowledge base that brings planning, sorting and creating all together. Privacy first, open-source, customizable and ready to use.

796 B
Raw Blame
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;
};