{"version":3,"file":"use-focus-return.cjs","names":[],"sources":["../../src/use-focus-return/use-focus-return.ts"],"sourcesContent":["import { useRef } from 'react';\nimport { useDidUpdate } from '../use-did-update/use-did-update';\n\nexport interface UseFocusReturnInput {\n  opened: boolean;\n  shouldReturnFocus?: boolean;\n}\n\nexport type UseFocusReturnReturnValue = () => void;\n\nexport function useFocusReturn({\n  opened,\n  shouldReturnFocus = true,\n}: UseFocusReturnInput): UseFocusReturnReturnValue {\n  const lastActiveElement = useRef<HTMLElement>(null);\n  const returnFocus = () => {\n    if (\n      lastActiveElement.current &&\n      'focus' in lastActiveElement.current &&\n      typeof lastActiveElement.current.focus === 'function'\n    ) {\n      lastActiveElement.current?.focus({ preventScroll: true });\n    }\n  };\n\n  useDidUpdate(() => {\n    let timeout = -1;\n\n    const clearFocusTimeout = (event: KeyboardEvent) => {\n      if (event.key === 'Tab') {\n        window.clearTimeout(timeout);\n      }\n    };\n\n    document.addEventListener('keydown', clearFocusTimeout);\n\n    if (opened) {\n      lastActiveElement.current = document.activeElement as HTMLElement;\n    } else if (shouldReturnFocus) {\n      timeout = window.setTimeout(returnFocus, 10);\n    }\n\n    return () => {\n      window.clearTimeout(timeout);\n      document.removeEventListener('keydown', clearFocusTimeout);\n    };\n  }, [opened, shouldReturnFocus]);\n\n  return returnFocus;\n}\n\nexport namespace useFocusReturn {\n  export type Input = UseFocusReturnInput;\n  export type ReturnValue = UseFocusReturnReturnValue;\n}\n"],"mappings":";;;;AAUA,SAAgB,eAAe,EAC7B,QACA,oBAAoB,QAC6B;CACjD,MAAM,qBAAA,GAAA,MAAA,QAAwC,KAAK;CACnD,MAAM,oBAAoB;AACxB,MACE,kBAAkB,WAClB,WAAW,kBAAkB,WAC7B,OAAO,kBAAkB,QAAQ,UAAU,WAE3C,mBAAkB,SAAS,MAAM,EAAE,eAAe,MAAM,CAAC;;AAI7D,wBAAA,mBAAmB;EACjB,IAAI,UAAU;EAEd,MAAM,qBAAqB,UAAyB;AAClD,OAAI,MAAM,QAAQ,MAChB,QAAO,aAAa,QAAQ;;AAIhC,WAAS,iBAAiB,WAAW,kBAAkB;AAEvD,MAAI,OACF,mBAAkB,UAAU,SAAS;WAC5B,kBACT,WAAU,OAAO,WAAW,aAAa,GAAG;AAG9C,eAAa;AACX,UAAO,aAAa,QAAQ;AAC5B,YAAS,oBAAoB,WAAW,kBAAkB;;IAE3D,CAAC,QAAQ,kBAAkB,CAAC;AAE/B,QAAO"}