RendyUI English

组件 / Stats band

Stats band

营销 · React / TypeScript Free

录制演示

Stats band 实现预览

源码

stats-band.tsx
/**
 * Stats band - original UI Stacks free component, MIT licensed.
 * Source: public page https://uistacks.dev/components/stats-band (code block reproduced verbatim, unmodified).
 * Upstream project: https://github.com/nazmijavier/uistacks
 */
"use client";

import { useEffect, useRef, useSyncExternalStore, type ReactNode } from "react";
import { animate, motion, useInView, useReducedMotion } from "motion/react";

export interface BandStat {
  /** The number it counts up to. */
  value: number;
  /** The short label under the number. */
  label: ReactNode;
  /** One quieter line under the label, e.g. where the number comes from. */
  detail?: ReactNode;
  /** Text before and after the number, e.g. "$" and "M". */
  prefix?: string;
  suffix?: string;
  /** Digits after the decimal point. Default 0. */
  decimals?: number;
}

export interface StatsBandProps {
  /** Three or four stats read best; they sit in one row on wide screens, two by two or stacked on narrow ones. */
  stats: BandStat[];
  /** A small line above the heading. */
  eyebrow?: ReactNode;
  /** The heading on the left (on top when narrow). Leave it out for numbers only. */
  title?: ReactNode;
  /** One line under the heading. */
  description?: ReactNode;
  /** Count-up length in ms. Default 1600. */
  duration?: number;
  /** Shows the final numbers without counting (also under reduced motion). */
  paused?: boolean;
  className?: string;
}

const noSubscribe = () => () => {};
// Values ease out long and soft, then settle (the kit's value curve).
const EASE = [0.22, 1, 0.36, 1] as const;

const fmt = (n: number, decimals = 0) => n.toLocaleString("en-US", { minimumFractionDigits: decimals, maximumFractionDigits: decimals });

/** The number: counts from 0 once `run` turns true; written to the DOM so the band never re-renders per frame. */
function Count({ s, run, still, duration, delay }: { s: BandStat; run: boolean; still: boolean; duration: number; delay: number }) {
  const ref = useRef<HTMLSpanElement>(null);
  const final = `${s.prefix ?? ""}${fmt(s.value, s.decimals)}${s.suffix ?? ""}`;

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const paint = (n: number) => (el.textContent = `${s.prefix ?? ""}${fmt(n, s.decimals)}${s.suffix ?? ""}`);
    if (still) return void paint(s.value);
    if (!run) return void paint(0);
    const c = animate(0, s.value, { duration: duration / 1000, delay: delay / 1000, ease: EASE, onUpdate: paint });
    return () => c.stop();
  }, [run, still, duration, delay, s.value, s.decimals, s.prefix, s.suffix]);

  return (
    <>
      <span ref={ref} aria-hidden className="tabular-nums">
        {final}
      </span>
      <span className="sr-only">{final}</span>
    </>
  );
}

/**
 * A wide band of big numbers for a landing page: an optional heading on the left, three or four stats on the right.
 * The first time it scrolls into view each number counts up in turn while a hairline above it draws across, so the
 * eye follows the row. Numbers use tabular figures, so nothing jitters while they count.
 */
export function StatsBand({ stats, eyebrow, title, description, duration = 1600, paused = false, className = "" }: StatsBandProps) {
  const prefers = useReducedMotion();
  const mounted = useSyncExternalStore(noSubscribe, () => true, () => false);
  const reduce = mounted && Boolean(prefers);
  const root = useRef<HTMLDivElement>(null);
  const inView = useInView(root, { once: true, amount: 0.35 });
  const still = paused || reduce || !mounted;
  const n = stats.length;
  const head = Boolean(title || eyebrow || description);
  const cols = n >= 4 ? "grid-cols-1 @[22rem]:grid-cols-2 @4xl:grid-cols-4" : n === 3 ? "grid-cols-1 @2xl:grid-cols-3" : "grid-cols-1 @[22rem]:grid-cols-2";
  const step = 140;

  return (
    <section ref={root} className={`@container w-full rounded-[20px] bg-surface p-6 shadow-[var(--shadow-card)] @3xl:p-8 ${className}`}>
      <div className={`flex flex-col gap-8 ${head ? "@5xl:flex-row @5xl:items-end @5xl:gap-12" : ""}`}>
        {head && (
          <div className="flex max-w-[360px] shrink-0 flex-col gap-2 @5xl:w-[300px]">
            {eyebrow && <p className="text-[13px] font-medium leading-5 text-fg-muted">{eyebrow}</p>}
            {title && <h2 className="text-balance text-[24px] font-medium leading-8 tracking-[-0.02em] text-fg">{title}</h2>}
            {description && <p className="text-pretty text-[14px] leading-5 text-fg-muted">{description}</p>}
          </div>
        )}
        <dl className={`grid min-w-0 flex-1 gap-x-8 gap-y-8 ${cols}`}>
          {stats.map((s, i) => (
            <div key={i} className="relative flex min-w-0 flex-col pt-5">
              {/* The hairline: a soft track with an ink line that draws across as the number counts. */}
              <span aria-hidden className="absolute inset-x-0 top-0 h-px bg-[var(--track)]" />
              <motion.span
                aria-hidden
                className="absolute inset-x-0 top-0 h-px origin-left bg-fg"
                initial={false}
                animate={{ scaleX: still || inView ? 1 : 0 }}
                transition={still ? { duration: 0 } : { duration: duration / 1000, delay: (i * step) / 1000, ease: EASE }}
              />
              <dt className="order-2 mt-2 text-[15px] font-medium leading-5 text-fg">{s.label}</dt>
              <dd className="order-1 text-[44px] font-medium leading-[52px] tracking-[-0.04em] text-fg @4xl:text-[52px] @4xl:leading-[60px]">
                <Count s={s} run={inView} still={still} duration={duration} delay={i * step} />
              </dd>
              {s.detail && <dd className="order-3 mt-1 text-pretty text-[13px] leading-5 text-fg-muted">{s.detail}</dd>}
            </div>
          ))}
        </dl>
      </div>
    </section>
  );
}

使用说明

把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。

包依赖 · motion、react

参数

名称类型说明
`stats``{ value; label; detail?; prefix?; suffix?; decimals? }[]`Three or four read best: one row when wide, two by two or stacked when narrow.
`eyebrow / title / description``ReactNode`The heading block on the left (on top when narrow). Leave all out for numbers only.
`duration``number`Count-up length in ms. Default 1600.
`paused``boolean`Shows the final numbers without counting (also under reduced motion).