@w3ux/hooks 2.3.2 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -276,3 +276,4 @@ var useTimeLeft = (props) => {
276
276
  });
277
277
  /* @license Copyright 2024 w3ux authors & contributors
278
278
  SPDX-License-Identifier: GPL-3.0-only */
279
+ //# sourceMappingURL=index.cjs.map
package/index.cjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.tsx","../src/useEffectIgnoreInitial.tsx","../src/useOnResize.tsx","../src/useOutsideAlerter.tsx","../src/useSafeContext.tsx","../src/useSize.tsx","../src/useTimeLeft/index.tsx","../src/util.ts","../src/useTimeLeft/defaults.ts"],"sourcesContent":["/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nexport * from './useEffectIgnoreInitial'\nexport * from './useOnResize'\nexport * from './useOutsideAlerter'\nexport * from './useSafeContext'\nexport * from './useSize'\nexport * from './useTimeLeft'\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport { useEffect, useRef } from 'react'\n\nexport const useEffectIgnoreInitial = <T, U>(fn: T, deps: U[]) => {\n const isInitial = useRef<boolean>(true)\n\n useEffect(\n () => {\n if (!isInitial.current) {\n if (typeof fn === 'function') {\n fn()\n }\n }\n isInitial.current = false\n },\n deps ? [...deps] : undefined\n )\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { RefObject } from 'react'\nimport { useEffect, useRef } from 'react'\n\ninterface UseOnResizeOptions {\n outerElement?: RefObject<HTMLElement | null>\n throttle?: number\n}\n\n/**\n * Custom hook that triggers a callback function when the specified element\n * or the window is resized.\n *\n * @param callback - The function to be executed on resize.\n * @param options - Optional parameters to customize the behavior:\n * - outerElement: A ref to an HTMLElement to listen for resize events.\n * - throttle: Optional duration in milliseconds to throttle the callback execution.\n * Default is 100 milliseconds.\n */\nexport const useOnResize = (\n callback: () => void,\n options: UseOnResizeOptions = {}\n) => {\n const { outerElement, throttle: throttleDuration = 100 } = options\n const lastExecutedRef = useRef<number>(0)\n\n // Throttled resize handler to limit the frequency of callback execution.\n const handleResize = () => {\n const now = Date.now()\n\n // Check if the callback can be executed based on the throttle duration.\n if (now - lastExecutedRef.current < throttleDuration) {\n return\n }\n\n lastExecutedRef.current = now\n callback()\n }\n\n useEffect(() => {\n // Determine the target for the resize event listener.\n const target = outerElement?.current || window\n\n // Add the resize event listener when the component mounts.\n target.addEventListener('resize', handleResize)\n\n // Clean up the event listener when the component unmounts.\n return () => {\n target.removeEventListener('resize', handleResize)\n }\n }, [throttleDuration, callback])\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport { useEffect, type RefObject } from 'react'\n\n// A hook that alerts clicks outside of the passed ref.\nexport const useOutsideAlerter = (\n ref: RefObject<HTMLElement | null>,\n callback: () => void,\n ignore: string[] = []\n) => {\n useEffect(() => {\n const handleClickOutside = (ev: MouseEvent) => {\n if (ev) {\n if (ref.current && !ref.current.contains(ev.target as Node)) {\n const target = ev.target as HTMLElement\n // Ignore tags with a name of `ignore`, or if there is a class of `ignore` in the parent\n // tree.\n const tagName = target.tagName.toLowerCase()\n const ignored = ignore.some(\n (i) =>\n i.toLowerCase() === tagName || target.closest(`.${i}`) !== null\n )\n\n if (!ignored) {\n callback()\n }\n }\n }\n }\n document.addEventListener('mousedown', handleClickOutside)\n return () => {\n document.removeEventListener('mousedown', handleClickOutside)\n }\n }, [ref])\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { Context } from 'react'\nimport { createContext, useContext } from 'react'\n\nexport const useSafeContext = <T,>(ctx: T | null | undefined): T => {\n if (ctx === null || ctx === undefined) {\n throw new Error(\n 'Context value is null or undefined. Please ensure the context Provider is used correctly.'\n )\n }\n return ctx\n}\n\nexport const createSafeContext = <T,>(): [Context<T | null>, () => T] => {\n const Context = createContext<T | null>(null)\n const useHook = () => useSafeContext<T>(useContext(Context))\n return [Context, useHook]\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { RefObject } from 'react'\nimport { useEffect, useRef, useState } from 'react'\n\n// Define the type for the options parameter.\ninterface UseSizeOptions {\n outerElement?: RefObject<HTMLElement | null>\n throttle?: number\n}\n\n// Custom hook to get the width and height of a specified element. Updates the `size` state when the\n// specified \"outer element\" (or the window by default) resizes.\nexport const useSize = (\n element: RefObject<HTMLElement | null>,\n options: UseSizeOptions = {}\n) => {\n const { outerElement, throttle: throttleDuration = 100 } = options\n\n // Helper function to retrieve the width and height of an element\n // If no element is found, default dimensions are set to 0.\n const getSize = (el: HTMLElement | null = null) => {\n const width = el?.offsetWidth || 0\n const height = el?.offsetHeight || 0\n return { width, height }\n }\n\n // Ref to store the last execution time of the `resizeThrottle` handler.\n const lastExecutedRef = useRef<number>(0)\n\n // State to store the current width and height of the specified element.\n const [size, setSize] = useState<{ width: number; height: number }>(\n getSize(element?.current)\n )\n\n // Throttle the resize event handler to limit how often size updates occur.\n const handleResize = () => {\n const now = Date.now()\n if (now - lastExecutedRef.current < throttleDuration) {\n return\n } // Exit if `throttleDuration` has not passed.\n\n lastExecutedRef.current = now // Update last execution time.\n\n setSize(getSize(element?.current))\n }\n\n // Set up the resize event listener on mount and clean it up on unmount.\n useEffect(() => {\n // Determine the target for the resize event listener.\n // If `outerElement` is provided, listen to its resize events; otherwise, listen to the window's.\n const listenFor = outerElement?.current || window\n\n listenFor.addEventListener('resize', handleResize)\n\n // Clean up event listener when the component unmounts to avoid memory leaks.\n return () => {\n listenFor.removeEventListener('resize', handleResize)\n }\n }, [outerElement?.current])\n\n // Return the current size of the element.\n return size\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type {\n TimeLeftAll,\n TimeLeftRaw,\n TimeleftDuration,\n UseTimeleftProps,\n} from '@w3ux/types'\nimport { setStateWithRef } from '@w3ux/utils'\nimport { useEffect, useRef, useState } from 'react'\nimport { getDuration } from '../util'\n\nexport const useTimeLeft = (props?: UseTimeleftProps) => {\n const depsTimeleft = props?.depsTimeleft || []\n const depsFormat = props?.depsFormat || []\n\n // check whether timeleft is within a minute of finishing.\n const inLastHour = () => {\n const { days, hours } = getDuration(toRef.current)\n return !days && !hours\n }\n\n // get the amount of seconds left if timeleft is in the last minute.\n const lastMinuteCountdown = () => {\n const { seconds } = getDuration(toRef.current)\n if (!inLastHour()) {\n return 60\n }\n return seconds\n }\n\n // calculate resulting timeleft object from latest duration.\n const getTimeleft = (c?: TimeleftDuration): TimeLeftAll => {\n const { days, hours, minutes, seconds } = c || getDuration(toRef.current)\n const raw: TimeLeftRaw = {\n days,\n hours,\n minutes,\n }\n if (!days && !hours) {\n raw.seconds = seconds\n }\n return {\n raw,\n }\n }\n\n // the end time as a date.\n const [to, setTo] = useState<Date | null>(null)\n const toRef = useRef(to)\n\n // resulting timeleft object to be returned.\n const [timeleft, setTimeleft] = useState<TimeLeftAll>(getTimeleft())\n\n // timeleft refresh intervals.\n const [minInterval, setMinInterval] = useState<\n ReturnType<typeof setInterval> | undefined\n >(undefined)\n const minIntervalRef = useRef(minInterval)\n\n const [secInterval, setSecInterval] = useState<\n ReturnType<typeof setInterval> | undefined\n >(undefined)\n const secIntervalRef = useRef(secInterval)\n\n // refresh effects.\n useEffect(() => {\n setTimeleft(getTimeleft())\n if (inLastHour()) {\n // refresh timeleft every second.\n if (!secIntervalRef.current) {\n const interval = setInterval(() => {\n if (!inLastHour()) {\n clearInterval(secIntervalRef.current)\n setStateWithRef(undefined, setSecInterval, secIntervalRef)\n }\n setTimeleft(getTimeleft())\n }, 1000)\n\n setStateWithRef(interval, setSecInterval, secIntervalRef)\n }\n }\n // refresh timeleft every minute.\n else if (!minIntervalRef.current) {\n const interval = setInterval(() => {\n if (inLastHour()) {\n clearInterval(minIntervalRef.current)\n setStateWithRef(undefined, setMinInterval, minIntervalRef)\n }\n setTimeleft(getTimeleft())\n }, 60000)\n setStateWithRef(interval, setMinInterval, minIntervalRef)\n }\n }, [to, inLastHour(), lastMinuteCountdown(), ...depsTimeleft])\n\n // re-render the timeleft upon formatting changes.\n useEffect(() => {\n setTimeleft(getTimeleft())\n }, [...depsFormat])\n\n // clear intervals on unmount\n useEffect(\n () => () => {\n clearInterval(minInterval)\n clearInterval(secInterval)\n },\n []\n )\n\n // Set the end time and calculate timeleft.\n const setFromNow = (dateFrom: Date, dateTo: Date) => {\n setTimeleft(getTimeleft(getDuration(dateFrom)))\n setStateWithRef(dateTo, setTo, toRef)\n }\n\n return {\n setFromNow,\n timeleft,\n }\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\nimport { differenceInDays, getUnixTime, intervalToDuration } from 'date-fns'\nimport { defaultDuration } from './useTimeLeft/defaults.js'\n\n// calculates the current timeleft duration.\nexport const getDuration = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n\n// Helper: Adds `seconds` to the current time and returns the resulting date.\nexport const secondsFromNow = (seconds: number): Date => {\n const end = new Date()\n end.setSeconds(end.getSeconds() + seconds)\n return end\n}\n\n// Helper: Calculates the duration between the current time and the provided date.\nexport const getDurationFromNow = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\n\nexport const defaultDuration: TimeleftDuration = {\n days: 0,\n hours: 0,\n minutes: 0,\n seconds: 0,\n lastMinute: false,\n}\n\nexport const defaultRefreshInterval = 60\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,mBAAkC;AAE3B,IAAM,yBAAyB,CAAO,IAAO,SAAc;AAChE,QAAM,gBAAY,qBAAgB,IAAI;AAEtC;AAAA,IACE,MAAM;AACJ,UAAI,CAAC,UAAU,SAAS;AACtB,YAAI,OAAO,OAAO,YAAY;AAC5B,aAAG;AAAA,QACL;AAAA,MACF;AACA,gBAAU,UAAU;AAAA,IACtB;AAAA,IACA,OAAO,CAAC,GAAG,IAAI,IAAI;AAAA,EACrB;AACF;;;ACfA,IAAAA,gBAAkC;AAiB3B,IAAM,cAAc,CACzB,UACA,UAA8B,CAAC,MAC5B;AACH,QAAM,EAAE,cAAc,UAAU,mBAAmB,IAAI,IAAI;AAC3D,QAAM,sBAAkB,sBAAe,CAAC;AAGxC,QAAM,eAAe,MAAM;AACzB,UAAM,MAAM,KAAK,IAAI;AAGrB,QAAI,MAAM,gBAAgB,UAAU,kBAAkB;AACpD;AAAA,IACF;AAEA,oBAAgB,UAAU;AAC1B,aAAS;AAAA,EACX;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zB,QAAI,WAAW,GAAG;AAEhB,UAAI,CAAC,eAAe,SAAS;AAC3B,cAAM,WAAW,YAAY,MAAM;AACjC,cAAI,CAAC,WAAW,GAAG;AACjB,0BAAc,eAAe,OAAO;AACpC,8CAAgB,QAAW,gBAAgB,cAAc;AAAA,UAC3D;AACA,sBAAY,YAAY,CAAC;AAAA,QAC3B,GAAG,GAAI;AAEP,0CAAgB,UAAU,gBAAgB,cAAc;AAAA,MAC1D;AAAA,IACF,WAES,CAAC,eAAe,SAAS;AAChC,YAAM,WAAW,YAAY,MAAM;AACjC,YAAI,WAAW,GAAG;AAChB,wBAAc,eAAe,OAAO;AACpC,4CAAgB,QAAW,gBAAgB,cAAc;AAAA,QAC3D;AACA,oBAAY,YAAY,CAAC;AAAA,MAC3B,GAAG,GAAK;AACR,wCAAgB,UAAU,gBAAgB,cAAc;AAAA,IAC1D;AAAA,EACF,GAAG,CAAC,IAAI,WAAW,GAAG,oBAAoB,GAAG,GAAG,YAAY,CAAC;AAG7D,+BAAU,MAAM;AACd,gBAAY,YAAY,CAAC;AAAA,EAC3B,GAAG,CAAC,GAAG,UAAU,CAAC;AAGlB;AAAA,IACE,MAAM,MAAM;AACV,oBAAc,WAAW;AACzB,oBAAc,WAAW;AAAA,IAC3B;AAAA,IACA,CAAC;AAAA,EACH;AAGA,QAAM,aAAa,CAAC,UAAgB,WAAiB;AACnD,gBAAY,YAAY,YAAY,QAAQ,CAAC,CAAC;AAC9C,sCAAgB,QAAQ,OAAO,KAAK;AAAA,EACtC;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":["import_react","import_react","import_react","import_react","import_react"]}
package/index.js CHANGED
@@ -243,3 +243,4 @@ export {
243
243
  };
244
244
  /* @license Copyright 2024 w3ux authors & contributors
245
245
  SPDX-License-Identifier: GPL-3.0-only */
246
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/useEffectIgnoreInitial.tsx","../src/useOnResize.tsx","../src/useOutsideAlerter.tsx","../src/useSafeContext.tsx","../src/useSize.tsx","../src/useTimeLeft/index.tsx","../src/util.ts","../src/useTimeLeft/defaults.ts"],"sourcesContent":["/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport { useEffect, useRef } from 'react'\n\nexport const useEffectIgnoreInitial = <T, U>(fn: T, deps: U[]) => {\n const isInitial = useRef<boolean>(true)\n\n useEffect(\n () => {\n if (!isInitial.current) {\n if (typeof fn === 'function') {\n fn()\n }\n }\n isInitial.current = false\n },\n deps ? [...deps] : undefined\n )\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { RefObject } from 'react'\nimport { useEffect, useRef } from 'react'\n\ninterface UseOnResizeOptions {\n outerElement?: RefObject<HTMLElement | null>\n throttle?: number\n}\n\n/**\n * Custom hook that triggers a callback function when the specified element\n * or the window is resized.\n *\n * @param callback - The function to be executed on resize.\n * @param options - Optional parameters to customize the behavior:\n * - outerElement: A ref to an HTMLElement to listen for resize events.\n * - throttle: Optional duration in milliseconds to throttle the callback execution.\n * Default is 100 milliseconds.\n */\nexport const useOnResize = (\n callback: () => void,\n options: UseOnResizeOptions = {}\n) => {\n const { outerElement, throttle: throttleDuration = 100 } = options\n const lastExecutedRef = useRef<number>(0)\n\n // Throttled resize handler to limit the frequency of callback execution.\n const handleResize = () => {\n const now = Date.now()\n\n // Check if the callback can be executed based on the throttle duration.\n if (now - lastExecutedRef.current < throttleDuration) {\n return\n }\n\n lastExecutedRef.current = now\n callback()\n }\n\n useEffect(() => {\n // Determine the target for the resize event listener.\n const target = outerElement?.current || window\n\n // Add the resize event listener when the component mounts.\n target.addEventListener('resize', handleResize)\n\n // Clean up the event listener when the component unmounts.\n return () => {\n target.removeEventListener('resize', handleResize)\n }\n }, [throttleDuration, callback])\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport { useEffect, type RefObject } from 'react'\n\n// A hook that alerts clicks outside of the passed ref.\nexport const useOutsideAlerter = (\n ref: RefObject<HTMLElement | null>,\n callback: () => void,\n ignore: string[] = []\n) => {\n useEffect(() => {\n const handleClickOutside = (ev: MouseEvent) => {\n if (ev) {\n if (ref.current && !ref.current.contains(ev.target as Node)) {\n const target = ev.target as HTMLElement\n // Ignore tags with a name of `ignore`, or if there is a class of `ignore` in the parent\n // tree.\n const tagName = target.tagName.toLowerCase()\n const ignored = ignore.some(\n (i) =>\n i.toLowerCase() === tagName || target.closest(`.${i}`) !== null\n )\n\n if (!ignored) {\n callback()\n }\n }\n }\n }\n document.addEventListener('mousedown', handleClickOutside)\n return () => {\n document.removeEventListener('mousedown', handleClickOutside)\n }\n }, [ref])\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { Context } from 'react'\nimport { createContext, useContext } from 'react'\n\nexport const useSafeContext = <T,>(ctx: T | null | undefined): T => {\n if (ctx === null || ctx === undefined) {\n throw new Error(\n 'Context value is null or undefined. Please ensure the context Provider is used correctly.'\n )\n }\n return ctx\n}\n\nexport const createSafeContext = <T,>(): [Context<T | null>, () => T] => {\n const Context = createContext<T | null>(null)\n const useHook = () => useSafeContext<T>(useContext(Context))\n return [Context, useHook]\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { RefObject } from 'react'\nimport { useEffect, useRef, useState } from 'react'\n\n// Define the type for the options parameter.\ninterface UseSizeOptions {\n outerElement?: RefObject<HTMLElement | null>\n throttle?: number\n}\n\n// Custom hook to get the width and height of a specified element. Updates the `size` state when the\n// specified \"outer element\" (or the window by default) resizes.\nexport const useSize = (\n element: RefObject<HTMLElement | null>,\n options: UseSizeOptions = {}\n) => {\n const { outerElement, throttle: throttleDuration = 100 } = options\n\n // Helper function to retrieve the width and height of an element\n // If no element is found, default dimensions are set to 0.\n const getSize = (el: HTMLElement | null = null) => {\n const width = el?.offsetWidth || 0\n const height = el?.offsetHeight || 0\n return { width, height }\n }\n\n // Ref to store the last execution time of the `resizeThrottle` handler.\n const lastExecutedRef = useRef<number>(0)\n\n // State to store the current width and height of the specified element.\n const [size, setSize] = useState<{ width: number; height: number }>(\n getSize(element?.current)\n )\n\n // Throttle the resize event handler to limit how often size updates occur.\n const handleResize = () => {\n const now = Date.now()\n if (now - lastExecutedRef.current < throttleDuration) {\n return\n } // Exit if `throttleDuration` has not passed.\n\n lastExecutedRef.current = now // Update last execution time.\n\n setSize(getSize(element?.current))\n }\n\n // Set up the resize event listener on mount and clean it up on unmount.\n useEffect(() => {\n // Determine the target for the resize event listener.\n // If `outerElement` is provided, listen to its resize events; otherwise, listen to the window's.\n const listenFor = outerElement?.current || window\n\n listenFor.addEventListener('resize', handleResize)\n\n // Clean up event listener when the component unmounts to avoid memory leaks.\n return () => {\n listenFor.removeEventListener('resize', handleResize)\n }\n }, [outerElement?.current])\n\n // Return the current size of the element.\n return size\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type {\n TimeLeftAll,\n TimeLeftRaw,\n TimeleftDuration,\n UseTimeleftProps,\n} from '@w3ux/types'\nimport { setStateWithRef } from '@w3ux/utils'\nimport { useEffect, useRef, useState } from 'react'\nimport { getDuration } from '../util'\n\nexport const useTimeLeft = (props?: UseTimeleftProps) => {\n const depsTimeleft = props?.depsTimeleft || []\n const depsFormat = props?.depsFormat || []\n\n // check whether timeleft is within a minute of finishing.\n const inLastHour = () => {\n const { days, hours } = getDuration(toRef.current)\n return !days && !hours\n }\n\n // get the amount of seconds left if timeleft is in the last minute.\n const lastMinuteCountdown = () => {\n const { seconds } = getDuration(toRef.current)\n if (!inLastHour()) {\n return 60\n }\n return seconds\n }\n\n // calculate resulting timeleft object from latest duration.\n const getTimeleft = (c?: TimeleftDuration): TimeLeftAll => {\n const { days, hours, minutes, seconds } = c || getDuration(toRef.current)\n const raw: TimeLeftRaw = {\n days,\n hours,\n minutes,\n }\n if (!days && !hours) {\n raw.seconds = seconds\n }\n return {\n raw,\n }\n }\n\n // the end time as a date.\n const [to, setTo] = useState<Date | null>(null)\n const toRef = useRef(to)\n\n // resulting timeleft object to be returned.\n const [timeleft, setTimeleft] = useState<TimeLeftAll>(getTimeleft())\n\n // timeleft refresh intervals.\n const [minInterval, setMinInterval] = useState<\n ReturnType<typeof setInterval> | undefined\n >(undefined)\n const minIntervalRef = useRef(minInterval)\n\n const [secInterval, setSecInterval] = useState<\n ReturnType<typeof setInterval> | undefined\n >(undefined)\n const secIntervalRef = useRef(secInterval)\n\n // refresh effects.\n useEffect(() => {\n setTimeleft(getTimeleft())\n if (inLastHour()) {\n // refresh timeleft every second.\n if (!secIntervalRef.current) {\n const interval = setInterval(() => {\n if (!inLastHour()) {\n clearInterval(secIntervalRef.current)\n setStateWithRef(undefined, setSecInterval, secIntervalRef)\n }\n setTimeleft(getTimeleft())\n }, 1000)\n\n setStateWithRef(interval, setSecInterval, secIntervalRef)\n }\n }\n // refresh timeleft every minute.\n else if (!minIntervalRef.current) {\n const interval = setInterval(() => {\n if (inLastHour()) {\n clearInterval(minIntervalRef.current)\n setStateWithRef(undefined, setMinInterval, minIntervalRef)\n }\n setTimeleft(getTimeleft())\n }, 60000)\n setStateWithRef(interval, setMinInterval, minIntervalRef)\n }\n }, [to, inLastHour(), lastMinuteCountdown(), ...depsTimeleft])\n\n // re-render the timeleft upon formatting changes.\n useEffect(() => {\n setTimeleft(getTimeleft())\n }, [...depsFormat])\n\n // clear intervals on unmount\n useEffect(\n () => () => {\n clearInterval(minInterval)\n clearInterval(secInterval)\n },\n []\n )\n\n // Set the end time and calculate timeleft.\n const setFromNow = (dateFrom: Date, dateTo: Date) => {\n setTimeleft(getTimeleft(getDuration(dateFrom)))\n setStateWithRef(dateTo, setTo, toRef)\n }\n\n return {\n setFromNow,\n timeleft,\n }\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\nimport { differenceInDays, getUnixTime, intervalToDuration } from 'date-fns'\nimport { defaultDuration } from './useTimeLeft/defaults.js'\n\n// calculates the current timeleft duration.\nexport const getDuration = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n\n// Helper: Adds `seconds` to the current time and returns the resulting date.\nexport const secondsFromNow = (seconds: number): Date => {\n const end = new Date()\n end.setSeconds(end.getSeconds() + seconds)\n return end\n}\n\n// Helper: Calculates the duration between the current time and the provided date.\nexport const getDurationFromNow = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\n\nexport const defaultDuration: TimeleftDuration = {\n days: 0,\n hours: 0,\n minutes: 0,\n seconds: 0,\n lastMinute: false,\n}\n\nexport const defaultRefreshInterval = 60\n"],"m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AC3B,GAAG,GAAK;AACR,sBAAgB,UAAU,gBAAgB,cAAc;AAAA,IAC1D;AAAA,EACF,GAAG,CAAC,IAAI,WAAW,GAAG,oBAAoB,GAAG,GAAG,YAAY,CAAC;AAG7D,EAAAA,WAAU,MAAM;AACd,gBAAY,YAAY,CAAC;AAAA,EAC3B,GAAG,CAAC,GAAG,UAAU,CAAC;AAGlB,EAAAA;AAAA,IACE,MAAM,MAAM;AACV,oBAAc,WAAW;AACzB,oBAAc,WAAW;AAAA,IAC3B;AAAA,IACA,CAAC;AAAA,EACH;AAGA,QAAM,aAAa,CAAC,UAAgB,WAAiB;AACnD,gBAAY,YAAY,YAAY,QAAQ,CAAC,CAAC;AAC9C,oBAAgB,QAAQ,OAAO,KAAK;AAAA,EACtC;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":["useEffect","useRef","useEffect","useEffect","useRef","useEffect","useRef","useState","useState","useRef","useEffect"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@w3ux/hooks",
3
- "version": "2.3.2",
3
+ "version": "2.3.3",
4
4
  "license": "GPL-3.0-only",
5
5
  "type": "module",
6
6
  "description": "A collection of general purpose React hooks",
package/util.cjs CHANGED
@@ -102,3 +102,4 @@ var getDurationFromNow = (toDate) => {
102
102
  });
103
103
  /* @license Copyright 2024 w3ux authors & contributors
104
104
  SPDX-License-Identifier: GPL-3.0-only */
105
+ //# sourceMappingURL=util.cjs.map
package/util.cjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/util.ts","../src/useTimeLeft/defaults.ts"],"sourcesContent":["/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\nimport { differenceInDays, getUnixTime, intervalToDuration } from 'date-fns'\nimport { defaultDuration } from './useTimeLeft/defaults.js'\n\n// calculates the current timeleft duration.\nexport const getDuration = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n\n// Helper: Adds `seconds` to the current time and returns the resulting date.\nexport const secondsFromNow = (seconds: number): Date => {\n const end = new Date()\n end.setSeconds(end.getSeconds() + seconds)\n return end\n}\n\n// Helper: Calculates the duration between the current time and the provided date.\nexport const getDurationFromNow = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\n\nexport const defaultDuration: TimeleftDuration = {\n days: 0,\n hours: 0,\n minutes: 0,\n seconds: 0,\n lastMinute: false,\n}\n\nexport const defaultRefreshInterval = 60\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,sBAAkE;;;ACC3D,IAAM,kBAAoC;AAAA,EAC/C,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAS;AAAA,EACT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;AAE3C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
package/util.js CHANGED
@@ -75,3 +75,4 @@ export {
75
75
  };
76
76
  /* @license Copyright 2024 w3ux authors & contributors
77
77
  SPDX-License-Identifier: GPL-3.0-only */
78
+ //# sourceMappingURL=util.js.map
package/util.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/util.ts","../src/useTimeLeft/defaults.ts"],"sourcesContent":["/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\nimport { differenceInDays, getUnixTime, intervalToDuration } from 'date-fns'\nimport { defaultDuration } from './useTimeLeft/defaults.js'\n\n// calculates the current timeleft duration.\nexport const getDuration = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n\n// Helper: Adds `seconds` to the current time and returns the resulting date.\nexport const secondsFromNow = (seconds: number): Date => {\n const end = new Date()\n end.setSeconds(end.getSeconds() + seconds)\n return end\n}\n\n// Helper: Calculates the duration between the current time and the provided date.\nexport const getDurationFromNow = (toDate: Date | null): TimeleftDuration => {\n if (!toDate) {\n return defaultDuration\n }\n if (getUnixTime(toDate) <= getUnixTime(new Date())) {\n return defaultDuration\n }\n\n toDate.setSeconds(toDate.getSeconds())\n const d = intervalToDuration({\n start: Date.now(),\n end: toDate,\n })\n\n const days = differenceInDays(toDate, Date.now())\n const hours = d?.hours || 0\n const minutes = d?.minutes || 0\n const seconds = d?.seconds || 0\n const lastHour = days === 0 && hours === 0\n const lastMinute = lastHour && minutes === 0\n\n return {\n days,\n hours,\n minutes,\n seconds,\n lastMinute,\n }\n}\n","/* @license Copyright 2024 w3ux authors & contributors\nSPDX-License-Identifier: GPL-3.0-only */\n\nimport type { TimeleftDuration } from '@w3ux/types'\n\nexport const defaultDuration: TimeleftDuration = {\n days: 0,\n hours: 0,\n minutes: 0,\n seconds: 0,\n lastMinute: false,\n}\n\nexport const defaultRefreshInterval = 60\n"],"mappings":";AAIA,SAAS,kBAAkB,aAAa,0BAA0B;;;ACC3D,IAAM,kBAAoC;AAAA,EAC/C,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;;;ADHO,IAAM,cAAc,CAAC,WAA0C;AACpE,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AACA,MAAI,YAAY,MAAM,KAAK,YAAY,oBAAI,KAAK,CAAC,GAAG;AAClD,WAAO;AAAA,EACT;AAEA,SAAO,WAAW,OAAO,WAAW,CAAC;AACrC,QAAM,IAAI,mBAAmB;AAAA,IAC3B,OAAO,KAAK,IAAI;AAAA,IAChB,KAAK;AAAA,EACP,CAAC;AAED,QAAM,OAAO,iBAAiB,QAAQ,KAAK,IAAI,CAAC;AAChD,QAAM,QAAQ,GAAG,SAAS;AAC1B,QAAM,UAAU,GAAG,WAAW;AAC9B,QAAM,UAAU,GAAG,WAAW;AAC9B,QAAM,WAAW,SAAS,KAAK,UAAU;AACzC,QAAM,aAAa,YAAY,YAAY;AAE3C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAGO,IAAM,iBAAiB,CAAC,YAA0B;AACvD,QAAM,MAAM,oBAAI,KAAK;AACrB,MAAI,WAAW,IAAI,WAAW,IAAI,OAAO;AACzC,SAAO;AACT;AAGO,IAAM,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