{"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>();\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,gBAAiB,CAAA,KAAA,EAAgB,OAAwB,GAAA,EAAa,EAAA;AACpF,EAAA,MAAM,EAAE,QAAA,GAAW,GAAK,EAAA,KAAA,GAAQ,KAAQ,GAAA,OAAA;AAExC,EAAA,MAAM,CAAC,YAAA,EAA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