{"version":3,"file":"useDelayedSwitch.mjs","sources":["../../../src/utils/useDelayedSwitch.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\n\ntype DelayOptions = {\n  // Minimal amount of time the switch will be on.\n  duration?: number;\n  // Delay after which switch will turn on.\n  delay?: number;\n};\n\n/**\n * Hook that delays changing of boolean switch to prevent too much time spent in \"on\" state. It is kind of a throttle\n * but you can specify different time for on and off throttling so this only allows a boolean values and also prefers\n * to stay \"off\" so turning \"on\" is always delayed while turning \"off\" is throttled.\n *\n * This is useful for showing loading elements to prevent it flashing too much in case of quick loading time or\n * prevent it flash if loaded state comes right after switch to loading.\n */\nexport function useDelayedSwitch(value: boolean, options: DelayOptions = {}): boolean {\n  const { duration = 250, delay = 250 } = options;\n\n  const [delayedValue, setDelayedValue] = useState(value);\n  const onStartTime = useRef<Date | undefined>(undefined);\n\n  useEffect(() => {\n    let timeout: ReturnType<typeof setTimeout> | undefined;\n    if (value) {\n      // If toggling to \"on\" state we always setTimeout no matter how long we have been \"off\".\n      timeout = setTimeout(() => {\n        onStartTime.current = new Date();\n        setDelayedValue(value);\n      }, delay);\n    } else {\n      // If toggling to \"off\" state we check how much time we were already \"on\".\n      const timeSpent = onStartTime.current ? Date.now() - onStartTime.current.valueOf() : 0;\n      const turnOff = () => {\n        onStartTime.current = undefined;\n        setDelayedValue(value);\n      };\n      if (timeSpent >= duration) {\n        // We already spent enough time \"on\" so change right away.\n        turnOff();\n      } else {\n        timeout = setTimeout(turnOff, duration - timeSpent);\n      }\n    }\n    return () => {\n      if (timeout) {\n        clearTimeout(timeout);\n        timeout = undefined;\n      }\n    };\n  }, [value, duration, delay]);\n\n  return delayedValue;\n}\n"],"names":[],"mappings":";;;AAiBO,SAAS,gBAAA,CAAiB,KAAA,EAAgB,OAAA,GAAwB,EAAC,EAAY;AACpF,EAAA,MAAM,EAAE,QAAA,GAAW,GAAA,EAAK,KAAA,GAAQ,KAAI,GAAI,OAAA;AAExC,EAAA,MAAM,CAAC,YAAA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