# All files / src/Search Search.hooks.ts

79.31% Statements 23/29
28.57% Branches 4/14
55.55% Functions 5/9
73.91% Lines 17/23

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
    605x

    5x
    11x
    11x
    11x
    11x

    11x

    11x
    10x

    11x

    1x
    1x
    1x

    1x

    1x

    1x

    11x

     import React from 'react'
    import { ChangeEvent } from '../_hooks/TextEntry'
    import { SearchHook, SearchHookConfig } from './Search.types'

    // TODO remove this and do a breaking change on Search to `useImperativeHandle`
    // to support controlled/uncontrolled behavior
    export function useSearch({
      onChange: externalOnChange = () => {},
      onClear = () => {},
      onSubmit = () => {},
      initialValue = '',
    }: SearchHookConfig): SearchHook {
      const [value, setValue] = React.useState(initialValue)

      React.useEffect(() => {
        setValue(initialValue)
      }, [initialValue])

      const isEmpty = value === ''

      function clear() {
        setValue('')
        onChange({ target: { value: '' } } as ChangeEvent)
        onClear()
      }

      function submit() {
        onSubmit(value)
      }

      function onChange(e: ChangeEvent) {
        setValue(e.target.value)

        externalOnChange(e)
      }

      function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
        if (e.key === 'Enter') {
          submit()
        } else Iif (e.key === 'Escape' || e.key === 'Esc') {
          // only let parent listeners (modal, overlay) know when empty
          Iif (value) {
            e.stopPropagation()
          }
          clear()
        }
      }

      return {
        clear,
        domHandlers: {
          onChange,
          onKeyDown,
        },
        isEmpty,
        submit,
        value,
      }
    }