Cleanup - unused files / unused exports / duplicate exports
[ProtonMail-WebClient.git] / packages / components / hooks / useContactFocus.tsx
blobbdb2fe6eb5a56d880747ee57b1d6479671c1b2fe
1 import type { MutableRefObject } from 'react';
2 import { useEffect, useRef, useState } from 'react';
4 import { useHandler } from './useHandler';
6 export interface ContactFocusContext {
7     elementIDs: string[];
8     listRef: MutableRefObject<HTMLElement | null>;
11 export const useContactFocus = ({ elementIDs, listRef }: ContactFocusContext) => {
12     const [focusIndex, setFocusIndex] = useState<number>();
14     const getFocusedId = () => (focusIndex !== undefined ? elementIDs[focusIndex] : undefined);
16     const focusedIDRef = useRef(getFocusedId());
18     const handleFocus = useHandler((index) => {
19         setFocusIndex(index);
20     });
22     const focusOnElementByIndex = (index: number) => {
23         const element = listRef.current?.querySelector(
24             `[data-shortcut-target="contact-container"][data-element-id="${elementIDs[index]}"]`
25         ) as HTMLElement;
26         element?.focus();
27     };
29     useEffect(() => {
30         if (focusIndex !== undefined) {
31             focusOnElementByIndex(focusIndex);
32         }
34         focusedIDRef.current = getFocusedId();
35     }, [focusIndex]);
37     return {
38         focusIndex,
39         getFocusedId,
40         setFocusIndex,
41         handleFocus,
42     };