UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

1 lines 2.12 kB
{"version":3,"file":"use-idle.mjs","names":[],"sources":["../../src/use-idle/use-idle.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\nexport interface UseIdleOptions {\n events?: (keyof DocumentEventMap)[];\n initialState?: boolean;\n}\n\nconst DEFAULT_OPTIONS: Required<UseIdleOptions> = {\n events: ['keydown', 'mousemove', 'touchmove', 'click', 'scroll', 'wheel'],\n initialState: true,\n};\n\nexport function useIdle(timeout: number, options?: UseIdleOptions) {\n const { events, initialState } = { ...DEFAULT_OPTIONS, ...options };\n const [idle, setIdle] = useState(initialState);\n const timer = useRef(-1);\n\n useEffect(() => {\n const handleEvents = () => {\n setIdle(false);\n\n if (timer.current) {\n window.clearTimeout(timer.current);\n }\n\n timer.current = window.setTimeout(() => {\n setIdle(true);\n }, timeout);\n };\n\n events.forEach((event) => document.addEventListener(event, handleEvents));\n\n // Start the timer immediately instead of waiting for the first event to happen\n timer.current = window.setTimeout(() => {\n setIdle(true);\n }, timeout);\n\n return () => {\n events.forEach((event) => document.removeEventListener(event, handleEvents));\n window.clearTimeout(timer.current);\n timer.current = -1;\n };\n }, [timeout]);\n\n return idle;\n}\n\nexport namespace useIdle {\n export type Options = UseIdleOptions;\n}\n"],"mappings":";;;AAOA,MAAM,kBAA4C;CAChD,QAAQ;EAAC;EAAW;EAAa;EAAa;EAAS;EAAU;CAAO;CACxE,cAAc;AAChB;AAEA,SAAgB,QAAQ,SAAiB,SAA0B;CACjE,MAAM,EAAE,QAAQ,iBAAiB;EAAE,GAAG;EAAiB,GAAG;CAAQ;CAClE,MAAM,CAAC,MAAM,WAAW,SAAS,YAAY;CAC7C,MAAM,QAAQ,OAAO,EAAE;CAEvB,gBAAgB;EACd,MAAM,qBAAqB;GACzB,QAAQ,KAAK;GAEb,IAAI,MAAM,SACR,OAAO,aAAa,MAAM,OAAO;GAGnC,MAAM,UAAU,OAAO,iBAAiB;IACtC,QAAQ,IAAI;GACd,GAAG,OAAO;EACZ;EAEA,OAAO,SAAS,UAAU,SAAS,iBAAiB,OAAO,YAAY,CAAC;EAGxE,MAAM,UAAU,OAAO,iBAAiB;GACtC,QAAQ,IAAI;EACd,GAAG,OAAO;EAEV,aAAa;GACX,OAAO,SAAS,UAAU,SAAS,oBAAoB,OAAO,YAAY,CAAC;GAC3E,OAAO,aAAa,MAAM,OAAO;GACjC,MAAM,UAAU;EAClB;CACF,GAAG,CAAC,OAAO,CAAC;CAEZ,OAAO;AACT"}