UNPKG

bdd-use-countdown

Version:

React hook encapsulating countdown functionality

86 lines (84 loc) 2.73 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { useCountdown: () => useCountdown }); module.exports = __toCommonJS(index_exports); var import_react = require("react"); var import_bdd_date_ext = require("bdd-date-ext"); function useCountdown({ start = new import_bdd_date_ext.DateX(), end, onStart, onEnd, timedActions = [] }) { const [values, setValues] = (0, import_react.useState)( () => diffTime(start, end) ); const timerRef = (0, import_react.useRef)(null); const executedActionsRef = (0, import_react.useRef)(/* @__PURE__ */ new Set()); (0, import_react.useEffect)(() => { onStart?.(start); timerRef.current = setInterval(() => { const now = new import_bdd_date_ext.DateX(); const timeLeft = diffTime(now, end); setValues(timeLeft); for (const { timestamp, action } of timedActions) { const ts = timestamp.getTime(); if (now.getTime() >= ts && !executedActionsRef.current.has(ts)) { action(timestamp); executedActionsRef.current.add(ts); } } if (now.getTime() >= end.getTime()) { clearInterval(timerRef.current); onEnd?.(end); } }, 1e3); return () => clearInterval(timerRef.current); }, [end.getTime()]); return values; } function diffTime(from, to) { const durationMs = Math.max(to.getTime() - from.getTime(), 0); let remaining = durationMs; const ms = remaining % 1e3; remaining = Math.floor(remaining / 1e3); const s = remaining % 60; remaining = Math.floor(remaining / 60); const m = remaining % 60; remaining = Math.floor(remaining / 60); const h = remaining % 24; remaining = Math.floor(remaining / 24); const d = remaining; return { days: d, hours: h, minutes: m, seconds: s, milliseconds: ms }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { useCountdown });