Skip to content

Commit

Permalink
fix: fix auto focus for inputs (#1040)
Browse files Browse the repository at this point in the history
just don't look at the internals and you'll be good.
  • Loading branch information
revam authored Sep 3, 2024
1 parent f96ccc4 commit c3430c4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
1 change: 1 addition & 0 deletions src/components/Collection/Tmdb/EpisodeSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ const EpisodeSelect = React.memo((props: Props) => {
className="z-[110] w-[var(--button-width)] rounded-lg bg-panel-background focus:outline-none"
>
<Input
autoFocus
id="episode-search"
type="text"
value={searchText}
Expand Down
13 changes: 4 additions & 9 deletions src/components/Input/Input.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { useContext, useEffect, useMemo, useRef } from 'react';
import React, { useContext, useEffect, useMemo } from 'react';
import type { PlacesType } from 'react-tooltip';
import { Icon } from '@mdi/react';
import cx from 'classnames';

import { BodyVisibleContext } from '@/core/router';
import useAutoFocusRef from '@/hooks/useAutoFocusRef';

type EndIcon = {
icon: string;
Expand Down Expand Up @@ -42,7 +43,7 @@ type TooltipAttributes = {

const Input = React.memo((props: Props) => {
const {
autoFocus,
autoFocus = false,
center,
className,
disabled,
Expand All @@ -64,15 +65,9 @@ const Input = React.memo((props: Props) => {
} = props;

const bodyVisible = useContext(BodyVisibleContext);
const inputRef = useRef<HTMLInputElement>(null);
const inputRef = useAutoFocusRef(autoFocus, bodyVisible);
const [isShow, setIsShow] = React.useState(false);

useEffect(() => {
if (autoFocus && bodyVisible && inputRef.current) {
inputRef.current?.focus();
}
}, [autoFocus, bodyVisible]);

useEffect(() => {
if (isOverlay) return;
setIsShow(_ => false);
Expand Down
23 changes: 23 additions & 0 deletions src/hooks/useAutoFocusRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type React from 'react';

import useEventCallback from './useEventCallback';

function useAutoFocusRef(autoFocus: boolean, bodyVisible: boolean): React.MutableRefObject<HTMLInputElement | null> {
// eslint-disable-next-line no-undef
const ref: React.MutableRefObject<HTMLInputElement | null> & { timeout?: NodeJS.Timeout } = useEventCallback(
(element: HTMLInputElement | null) => {
ref.current = element;
if (autoFocus && bodyVisible && element) {
if (ref.timeout) clearTimeout(ref.timeout);
ref.timeout = setTimeout(() => {
if (ref.timeout) delete ref.timeout;
element.focus();
}, 0);
}
},
// eslint-disable-next-line no-undef
) as unknown as React.MutableRefObject<HTMLInputElement> & { timeout?: NodeJS.Timeout };
return ref;
}

export default useAutoFocusRef;

0 comments on commit c3430c4

Please sign in to comment.