okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
743a6b3c6
main
1import { useEffect , useRef , useState } from 'react' ; 2import { tweenValue } from '../lib/tween' ; 3 4const reduced = () => typeof matchMedia === 'function' && matchMedia ( '(prefers-reduced-motion: reduce)' ). matches ; 5 6/** The number a reading is moving towards, shown as it travels there (a short count-up or count-down, 600 ms). Tabular figures keep the width steady. */ 7export function useTweened ( target :number | null , duration = 600 ) :number | null { 8const [ shown , setShown ] = useState < number | null >( target ); 9const from = useRef < number | null >( target ); 10const frame = useRef ( 0 ); 11useEffect (() => { 12if ( target === null || from . current === null || reduced () || target === from . current ) { from . current = target ; setShown ( target ); return ; } 13const start = performance . now (), origin = from . current ; 14cancelAnimationFrame ( frame . current ); 15const step = ( now :number ) => { 16const value = tweenValue ( origin , target , now - start , duration ); 17from . current = value ; setShown ( value ); 18if ( now - start < duration ) frame . current = requestAnimationFrame ( step ); else { from . current = target ; setShown ( target ); } 19}; 20frame . current = requestAnimationFrame ( step ); 21return () => cancelAnimationFrame ( frame . current ); 22}, [ target , duration ]); 23return shown ; 24} 25 26export function Num ({ value, format, className} :{ value :number | null ; format :( n :number ) => string ; className ?:string }) { 27const shown = useTweened ( value ); 28return < span className = { `num ${ className ?? '' } ` . trim ()} style = {{ fontVariantNumeric :'tabular-nums' }}>{ shown === null ?'—' :format ( shown )}</ span >; 29}