# All files / src/Form closeWithConfirm.tsx

95.23% Statements 20/21
90.9% Branches 10/11
66.66% Functions 4/6
94.11% Lines 16/17

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
    5517x
    17x

    17x
    25x
    25x

    25x

    7x
    6x
    3x
    2x

    1x

    1x

    25x

    17x

    17x
    175x

     import React from 'react'
    import { useI18nContext } from '../_hooks/I18n'

    type ConditionalCloseFunction<
      onClose extends undefined | ((...args: any[]) => any)
    > = onClose extends (...args: any[]) => any ? onClose : undefined

    interface UseCloseWithConfirmState {
      closeWithConfirm: <onClose extends undefined | ((...args: any[]) => any)>(
        func: onClose
      ) => ConditionalCloseFunction<onClose>
      setFormIsDifferent: React.Dispatch<React.SetStateAction<boolean>>
    }

    export const useCloseWithConfirmState = (): UseCloseWithConfirmState => {
      const I18n = useI18nContext()
      const [isFormDifferent, setFormIsDifferent] = React.useState(false)

      const closeWithConfirm = React.useCallback(
        (onClose: Function | undefined) =>
          onClose
            ? (...args: any[]) => {
                if (isFormDifferent && onClose) {
                  if (
                    window.confirm(
                      I18n.t('core.form.closeWithConfirm.confirmMessage')
                    )
                  ) {
                    return onClose(...args)
                  }
                } else {
                  return onClose?.(...args)
                }
              }
            : undefined,
        [isFormDifferent]
      ) as unknown as UseCloseWithConfirmState['closeWithConfirm']

      return {
        closeWithConfirm,
        setFormIsDifferent,
      }
    }

    export const CloseWithConfirmContext =
      React.createContext<UseCloseWithConfirmState>({
        setFormIsDifferent: () => {},
        // @ts-ignore
        closeWithConfirm: (onClose) => onClose,
      })

    export const useCloseWithConfirmContext = () => {
      return React.useContext(CloseWithConfirmContext)
    }