# All files / src/Modal useInitializeModalFocus.ts

90% Statements 18/20
73.8% Branches 31/42
100% Functions 2/2
89.47% Lines 17/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    458x
    8x
    8x

    8x
    42x
    42x

    42x
    42x

    42x

    17x
    2x

    2x

    2x

    2x

    1x
    1x

    1x

     import { useFocusManager } from '@react-aria/focus'
    import { useEffect } from 'react'
    import { useModalChildRegistryContext } from './ChildRegistry.context'

    interface InitializeModalFocusProps {
      modalContainerRef: React.RefObject<HTMLDivElement>
      hasOnClose: boolean
    }

    export function useInitializeModalFocus({
      modalContainerRef,
      hasOnClose,
    }: InitializeModalFocusProps) {
      const focusManager = useFocusManager()
      const childrenRegistryStatus = useModalChildRegistryContext()

      useEffect(() => {
        // the same reason that Modal has a FocusScope with autoFocus={!!onClose}
        if (!hasOnClose) return
        const closeButtonElement = modalContainerRef?.current?.querySelector(
          '[data-internal="close-button"]'
        )
        const anyFocusedItem =
          childrenRegistryStatus.body?.current?.querySelector(':focus')

        Iif (closeButtonElement == null) {
          // if no focus header button is represented then no need to change focus on next elements
          return
        }
        if (childrenRegistryStatus.body?.current) {
          // if nothing has been focused within body then focus in the scrollable body
          if (anyFocusedItem == null) {
            childrenRegistryStatus.body?.current?.focus()
          }
          // if there is a footer section the focus on the left most interactive element
        } else Iif (childrenRegistryStatus.closeableButtons?.current) {
          focusManager.focusNext({
            from: closeButtonElement ?? undefined,
          })
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [childrenRegistryStatus])
    }