UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

1 lines 2.65 kB
{"version":3,"file":"use-focus-return.mjs","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 const activeElementAtClose = document.activeElement;\n timeout = window.setTimeout(() => {\n const currentActiveElement = document.activeElement;\n if (\n currentActiveElement === null ||\n currentActiveElement === document.body ||\n currentActiveElement === activeElementAtClose\n ) {\n returnFocus();\n }\n }, 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,oBAAoB,OAAoB,IAAI;CAClD,MAAM,oBAAoB;EACxB,IACE,kBAAkB,WAClB,WAAW,kBAAkB,WAC7B,OAAO,kBAAkB,QAAQ,UAAU,YAE3C,kBAAkB,SAAS,MAAM,EAAE,eAAe,KAAK,CAAC;CAE5D;CAEA,mBAAmB;EACjB,IAAI,UAAU;EAEd,MAAM,qBAAqB,UAAyB;GAClD,IAAI,MAAM,QAAQ,OAChB,OAAO,aAAa,OAAO;EAE/B;EAEA,SAAS,iBAAiB,WAAW,iBAAiB;EAEtD,IAAI,QACF,kBAAkB,UAAU,SAAS;OAChC,IAAI,mBAAmB;GAC5B,MAAM,uBAAuB,SAAS;GACtC,UAAU,OAAO,iBAAiB;IAChC,MAAM,uBAAuB,SAAS;IACtC,IACE,yBAAyB,QACzB,yBAAyB,SAAS,QAClC,yBAAyB,sBAEzB,YAAY;GAEhB,GAAG,EAAE;EACP;EAEA,aAAa;GACX,OAAO,aAAa,OAAO;GAC3B,SAAS,oBAAoB,WAAW,iBAAiB;EAC3D;CACF,GAAG,CAAC,QAAQ,iBAAiB,CAAC;CAE9B,OAAO;AACT"}