UNPKG

react-spinning-number

Version:

<img src="./example/example.gif" width="100%">

79 lines (78 loc) 2.1 kB
import { jsxs as g, jsx as f } from "react/jsx-runtime"; import { useRef as p, useState as v, useMemo as k, useEffect as w } from "react"; import { Digit as C } from "./digit.js"; function E({ children: l, stagger: a = 100, ...d }) { const i = p(0), o = p([]), [y, b] = v(!1), h = k(() => { let r = 0, s = 0, m = 0; const t = l.toString().split("").reverse().map((e) => /\d/.test(e) ? (s += 1, { key: `number-${s}`, value: e }) : (r += 1, { key: `fixed-${r}`, value: e })).reverse().map((e) => { if (!e.key.startsWith("number-")) return e; const n = o.current.find( (u) => u.key === e.key ); return n && n.value !== e.value && (m += 1), { ...e, delay: n ? a * (m - 1) : 0 }; }), c = i.current - t.length; if (c > 0) { const e = new Array(c).fill(null).map((u, x) => ({ key: `number-${s + x + 1}`, value: null, delay: 0 })).reverse(), n = t.findIndex( (u) => u.key === `number-${s}` ); t.splice(n, 0, ...e); } else t.length > i.current && (i.current = t.length); return o.current = t.filter((e) => e.key.startsWith("number-")), t; }, [l, a]); return w(() => { setTimeout(() => { b(!0); }, 500); }, []), /* @__PURE__ */ g( "span", { style: { display: "flex", justifyContent: "start", alignItems: "center" }, children: [ /* @__PURE__ */ f( "span", { style: { position: "absolute", width: "1px", height: "1px", padding: "0", margin: "-1px", overflow: "hidden", clip: "rect(0,0,0,0)", whiteSpace: "nowrap", border: "0" }, children: l } ), h.map((r) => /* @__PURE__ */ f( C, { char: r.value, delay: r.delay, loaded: y, ...d }, r.key )) ] } ); } export { E as SpinningNumber };