okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-ui5 e9a2ca44a (round-7 UI, time-skip fixes, mode switch mid-goal, /plan, queued messages, uninstaller icon; includes agent6 eecb29593) into f-split-int743a6b3c6

main
1.6 KiB29 linesraw
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 {
8  const [shown, setShown] = useState<number | null>(target);
9  const from = useRef<number | null>(target);
10  const frame = useRef(0);
11  useEffect(() => {
12    if (target === null || from.current === null || reduced() || target === from.current) { from.current = target; setShown(target); return; }
13    const start = performance.now(), origin = from.current;
14    cancelAnimationFrame(frame.current);
15    const step = (now: number) => {
16      const value = tweenValue(origin, target, now - start, duration);
17      from.current = value; setShown(value);
18      if (now - start < duration) frame.current = requestAnimationFrame(step); else { from.current = target; setShown(target); }
19    };
20    frame.current = requestAnimationFrame(step);
21    return () => cancelAnimationFrame(frame.current);
22  }, [target, duration]);
23  return shown;
24}
25
26export function Num({ value, format, className }: { value: number | null; format: (n: number) => string; className?: string }) {
27  const shown = useTweened(value);
28  return <span className={`num ${className ?? ''}`.trim()} style={{ fontVariantNumeric: 'tabular-nums' }}>{shown === null ? '—' : format(shown)}</span>;
29}