# All files / src/Modal ChildRegistry.context.tsx

90.9% Statements 20/22
0% Branches 0/2
100% Functions 5/5
90% Lines 18/20

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
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    698x

    8x
    8x

    27x

    8x

    10x

    8x
    9x

    9x
    9x

    8x
    42x
    42x

    42x

    8x
    112x
    112x

    112x

     import React from 'react'

    const ChildRegistryContext = React.createContext<ChildRegistry>({})
    const ChildRegistryDispatch = React.createContext<
      React.Dispatch<ChildToRegister>
    >((childToRegister: ChildToRegister) => ({}))

    /**
     *  Tracks the children of the modal, primarily for managing focus
     */
    interface ChildRegistry {
      header?: React.RefObject<HTMLDivElement>
      body?: React.RefObject<HTMLDivElement>
      closeableButtons?: React.RefObject<HTMLDivElement>
    }

    const initState: ChildRegistry = {
      header: undefined,
      body: undefined,
      closeableButtons: undefined,
    }

    interface ChildToRegister {
      child: keyof ChildRegistry
      ref: React.MutableRefObject<null>
    }

    function registerChild(state: ChildRegistry, childToRegister: ChildToRegister) {
      return {
        ...state,
        [childToRegister.child]: childToRegister.ref,
      }
    }

    export function ChildRegistryProvider({
      children,
    }: {
      children: React.ReactNode
    }) {
      const [state, dispatch] = React.useReducer(registerChild, initState)
      return (
        <ChildRegistryContext.Provider value={state}>
          <ChildRegistryDispatch.Provider value={dispatch}>
            {children}
          </ChildRegistryDispatch.Provider>
        </ChildRegistryContext.Provider>
      )
    }

    export function useModalChildRegistryContext() {
      const context = React.useContext(ChildRegistryContext)
      Iif (!context) {
        throw new Error(
          'useModalChildRegistryContext must be used within a ChildRegistryProvider'
        )
      }
      return context
    }

    export function useModalChildRegistryDispatch() {
      const context = React.useContext(ChildRegistryDispatch)
      Iif (!context) {
        throw new Error(
          'useModalChildRegistryDispatch must be used within a ChildRegistryProvider'
        )
      }
      return context
    }