UNPKG

@yamada-ui/react

Version:

React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion

1 lines 1.94 kB
{"version":3,"file":"index.cjs","names":[],"sources":["../../../../src/hooks/use-idle/index.ts"],"sourcesContent":["\"use client\"\n\nimport { useEffect, useRef, useState } from \"react\"\n\nconst DEFAULT_EVENTS: (keyof DocumentEventMap)[] = [\n \"keypress\",\n \"mousemove\",\n \"touchmove\",\n \"click\",\n \"scroll\",\n]\n\nconst DEFAULT_OPTIONS = {\n events: DEFAULT_EVENTS,\n initialState: true,\n}\n\nexport interface IdleOptions {\n events?: (keyof DocumentEventMap)[]\n initialState?: boolean\n}\n\n/**\n * `useIdle` is a custom hook that detects whether the user has been idle for a certain amount of time in milliseconds.\n *\n * @see https://yamada-ui.com/docs/hooks/use-idle\n */\nexport const useIdle = (timeout: number, options?: IdleOptions) => {\n const { events, initialState } = { ...DEFAULT_OPTIONS, ...options }\n const [idle, setIdle] = useState<boolean>(initialState)\n const timeoutId = useRef<NodeJS.Timeout>(undefined)\n\n useEffect(() => {\n const handleEvent = () => {\n setIdle(false)\n\n if (timeoutId.current) clearTimeout(timeoutId.current)\n\n timeoutId.current = setTimeout(() => setIdle(true), timeout)\n }\n\n events.forEach((event) => document.addEventListener(event, handleEvent))\n\n return () => {\n events.forEach((event) =>\n document.removeEventListener(event, handleEvent),\n )\n }\n }, [events, timeout])\n\n return idle\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,kBAAkB;CACtB,QATiD;EACjD;EACA;EACA;EACA;EACA;EACD;CAIC,cAAc;CACf;;;;;;AAYD,MAAa,WAAW,SAAiB,YAA0B;CACjE,MAAM,EAAE,QAAQ,iBAAiB;EAAE,GAAG;EAAiB,GAAG;EAAS;CACnE,MAAM,CAAC,MAAM,+BAA6B,aAAa;CACvD,MAAM,8BAAmC,OAAU;AAEnD,4BAAgB;EACd,MAAM,oBAAoB;AACxB,WAAQ,MAAM;AAEd,OAAI,UAAU,QAAS,cAAa,UAAU,QAAQ;AAEtD,aAAU,UAAU,iBAAiB,QAAQ,KAAK,EAAE,QAAQ;;AAG9D,SAAO,SAAS,UAAU,SAAS,iBAAiB,OAAO,YAAY,CAAC;AAExE,eAAa;AACX,UAAO,SAAS,UACd,SAAS,oBAAoB,OAAO,YAAY,CACjD;;IAEF,CAAC,QAAQ,QAAQ,CAAC;AAErB,QAAO"}