UNPKG

@fewings/fancy-react

Version:
2 lines (1 loc) 2.21 kB
import{AnimatePresence as O,motion as H}from"motion/react";import{useEffect as N,useMemo as W,useRef as _}from"react";import{useEffect as k,useMemo as v,useRef as y,useState as A}from"react";import{motion as R,useAnimate as $}from"motion/react";import{usePrevState as E}from"@fewings/react/hooks";import{jsx as b,jsxs as M}from"react/jsx-runtime";function S({to:t,countDur:u,widthDur:f,direction:m="random",onSizeChange:d}){let l=E(t)??0,r=v(()=>m==="up"||l<t,[m,t]),[i,o]=A({w:0,h:0}),n=y(null),w=()=>{n.current&&clearTimeout(n.current)},g=y(null),p=e=>{let s=g.current;s&&(s.style.visibility=e?"visible":"hidden",h.current.style.display=e?"none":"block")},[h,z]=$(),C=y(0),a=v(()=>{let e=C.current;return C.current=t,e},[t]),P=t>a?1:-1,D=v(()=>{let e=Array.from({length:Math.abs(t-a)+1},(s,x)=>a+x*P);return r?e:e.reverse()},[t,a,r]);return k(()=>{w(),p(!1);let e=[0,`calc(-100% + ${i.h}px)`];return z(h.current,{y:r?e:e.reverse()},{duration:u,onPlay:()=>{p(!1)},onComplete:()=>{n.current=window.setTimeout(()=>{p(!0)},(u+1)*1e3)}}),()=>{w()}},[i.h,t,u,a,r]),M(R.div,{style:{position:"relative",display:"inline-block",overflow:"hidden"},initial:{width:0,transformOrigin:"left"},animate:{width:"auto",transformOrigin:"left"},exit:{width:0,transformOrigin:"right"},transition:{duration:f},children:[b("div",{ref:h,style:{position:"absolute",top:0,left:0,willChange:"transform"},children:D.map(e=>b("div",{children:e},e))}),b("div",{ref:e=>{if(!e||(g.current=e,i.w===e.offsetWidth&&i.h===e.offsetHeight))return;let s={w:e.offsetWidth,h:e.offsetHeight};o(s),d?.(s)},children:t})]})}var T=t=>/^\d+$/.test(t);import{jsx as c}from"react/jsx-runtime";function X({value:t,countDur:u=.5,sizeDur:f=.3,format:m=r=>`${r}`,style:d,...l}){let r=_(m),i=W(()=>r.current(t).split(""),[t]);return N(()=>{r.current=m}),c("div",{style:{width:"fit-content",height:"fit-content",display:"flex",alignItems:"center",...d},...l,children:c(O,{children:i.map((o,n)=>T(o)?c(S,{to:+o,countDur:u,widthDur:f},n):c(H.div,{initial:{opacity:0,width:0},animate:{opacity:1,width:"auto"},exit:{width:0,opacity:0},transition:{duration:f,transformOrigin:"left"},children:o},`${o}${n!==0&&n!==i.length-1?n:""}`))})})}export{X as AnimateNumber};