RendyUI English

区块 / Sales today

Sales today

Analytics · React / TypeScript Free

录制演示

Sales today 实现预览

源码

sales-today.tsx
/* Sales today — free block published by UI Stacks (public page source).
   Kept verbatim: the author publishes this block free, in full, at https://uistacks.dev/blocks/sales-today
   See replica/README.md for provenance. */
"use client";

import { useEffect, useId, useRef, useState, useSyncExternalStore, type KeyboardEvent, type PointerEvent } from "react";
import { animate, motion, useInView, useReducedMotion } from "motion/react";

/* ── Sample data: replace with your own ─────────────────────── */

const STORE = { workspace: "UI Stacks", scope: "All 6 stores", today: "Thu, Nov 12", yesterday: "Wed, Nov 11" };
/** "Now" in the sample: 10:38 AM. */
const NOW_MIN = 10 * 60 + 38;
/** Yesterday's full day, and the average order today and yesterday. */
const YESTERDAY_TOTAL = 4920;
const TICKET = { today: 7.85, yesterday: 7.62 };

/** Seeded random numbers, so the server and the browser draw the same lines. */
function seeded(seed: number) {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6d2b79f5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const SLOT = 10; // minutes per point
const SLOTS = (24 * 60) / SLOT;
/** Share of a day's sales at hour h: open 6 AM to 9 PM, a breakfast rush, a lunch bump and an afternoon lift. */
const dayShape = (h: number) =>
  h < 6 || h >= 21 ? 0 : 0.5 + 1.6 * Math.exp(-(((h - 8) / 1.3) ** 2)) + 0.8 * Math.exp(-(((h - 12.5) / 1.2) ** 2)) + 0.6 * Math.exp(-(((h - 15.5) / 1.4) ** 2));
/** Sales in 10-minute slots across one day, adding up to `amount`. */
function daySlots(amount: number, seed: number) {
  const r = seeded(seed);
  const w = Array.from({ length: SLOTS }, (_, k) => dayShape((k * SLOT) / 60) * (0.55 + 0.9 * r()));
  const sum = w.reduce((a, b) => a + b, 0);
  return w.map((x) => (amount * x) / sum);
}
/** Sales from midnight up to `minute`. */
function upTo(slots: number[], minute: number) {
  const f = minute / SLOT;
  const full = Math.floor(f);
  return slots.slice(0, full).reduce((a, b) => a + b, 0) + (slots[full] ?? 0) * (f - full);
}

const YEST_SLOTS = daySlots(YESTERDAY_TOTAL, 131);
/** Today runs 12% ahead of yesterday by the same time. */
const TODAY_SLOTS = (() => {
  const raw = daySlots(5000, 211);
  const k = (1.12 * upTo(YEST_SLOTS, NOW_MIN)) / upTo(raw, NOW_MIN);
  return raw.map((x) => x * k);
})();

/** One point every 10 minutes over the whole day; `today` is null after now. */
type Point = { minute: number; today: number | null; yesterday: number };
const POINTS: Point[] = Array.from({ length: SLOTS + 1 }, (_, i) => {
  const minute = i * SLOT;
  return { minute, today: minute <= NOW_MIN ? Math.round(upTo(TODAY_SLOTS, minute)) : null, yesterday: Math.round(upTo(YEST_SLOTS, minute)) };
});
/** Today's line ends exactly at now. */
const NOW_POINT = { minute: NOW_MIN, today: Math.round(upTo(TODAY_SLOTS, NOW_MIN)), yesterday: Math.round(upTo(YEST_SLOTS, NOW_MIN)) };
const NOW_INDEX = Math.floor(NOW_MIN / SLOT); // the last 10-minute point before now

const BUSIEST = (() => {
  let best = 6;
  let value = 0;
  for (let h = 6; h + 1 <= NOW_MIN / 60; h++) {
    const v = upTo(TODAY_SLOTS, (h + 1) * 60) - upTo(TODAY_SLOTS, h * 60);
    if (v > value) [best, value] = [h, v];
  }
  return { hour: best, value: Math.round(value) };
})();

/* ── Helpers ────────────────────────────────────────────────── */

const ease = [0.22, 1, 0.36, 1] as const;
const ring = "outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]";
const usd = (v: number) => v.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const usd2 = (v: number) => v.toLocaleString("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 });
const hourText = (h: number) => `${h % 12 || 12} ${h < 12 || h === 24 ? "AM" : "PM"}`;
const clock = (minute: number) => {
  const h = Math.floor(minute / 60) % 24;
  const m = Math.round(minute % 60);
  return `${h % 12 || 12}:${String(m).padStart(2, "0")} ${h < 12 ? "AM" : "PM"}`;
};
const r2 = (v: number) => Math.round(v * 100) / 100;
const pctChange = (a: number, b: number) => (b ? (a / b - 1) * 100 : 0);
const DAY_MIN = 24 * 60;

const noSubscribe = () => () => {};
/** Reduced motion, read only after hydration so the server and the first client render match. */
function useReduce() {
  const prefers = useReducedMotion();
  const hydrated = useSyncExternalStore(noSubscribe, () => true, () => false);
  return hydrated && Boolean(prefers);
}

function useWidth(fallback: number) {
  const [el, setEl] = useState<HTMLDivElement | null>(null);
  const [width, setWidth] = useState(fallback);
  useEffect(() => {
    if (!el) return;
    const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry.contentRect.width)));
    observer.observe(el);
    return () => observer.disconnect();
  }, [el]);
  return [setEl, width] as const;
}

const LOOP_MS = 12000;
/**
 * While the chart is on screen and nobody is using it, `run` bumps every LOOP_MS so the line draws again. Hovering
 * pauses the loop; a click or a key press stops it until the pointer leaves. No looping with reduced motion.
 */
function useLoop<T extends HTMLElement = HTMLDivElement>() {
  const ref = useRef<T>(null);
  const visible = useInView(ref);
  const [run, setRun] = useState(0);
  const [hover, setHover] = useState(false);
  const [used, setUsed] = useState(false);
  useEffect(() => {
    if (!visible || hover || used) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const id = window.setTimeout(() => setRun((r) => r + 1), LOOP_MS);
    return () => window.clearTimeout(id);
  }, [visible, hover, used, run]);
  const handlers = {
    onPointerEnter: () => setHover(true),
    onPointerLeave: () => {
      setHover(false);
      setUsed(false);
    },
    onPointerDown: () => setUsed(true),
    onKeyDown: () => setUsed(true),
  };
  return { ref, run, handlers };
}

/* ── The block ──────────────────────────────────────────────── */

/** Today's sales as a running total against yesterday's, scrubbable by the 10 minutes, with the day's key numbers. */
export default function SalesTodayBlock({ className = "" }: { className?: string }) {
  const uid = useId().replace(/:/g, "");
  const reduce = useReduce();
  const [plotRef, width] = useWidth(720);
  const [scrub, setScrub] = useState<number | null>(null);
  const { ref: loopRef, run, handlers } = useLoop<HTMLElement>();

  const W = Math.max(width, 1);
  const H = width >= 640 ? 168 : 128;
  const PAD = { top: 10, bottom: 4 };
  const onPace = Math.round(YESTERDAY_TOTAL * (NOW_POINT.today / NOW_POINT.yesterday));
  const hi = Math.max(YESTERDAY_TOTAL, onPace) * 1.08;
  const x = (minute: number) => (minute / DAY_MIN) * W;
  const y = (v: number) => PAD.top + (1 - v / hi) * (H - PAD.top - PAD.bottom);
  const todayPts = [...POINTS.slice(0, NOW_INDEX + 1), NOW_POINT];
  const todayLine = todayPts.map((p, i) => `${i ? "L" : "M"}${r2(x(p.minute))},${r2(y(p.today!))}`).join("");
  const yestLine = POINTS.map((p, i) => `${i ? "L" : "M"}${r2(x(p.minute))},${r2(y(p.yesterday))}`).join("");

  // The point being read: a scrubbed 10-minute mark, or now.
  const at = scrub === null ? NOW_POINT : POINTS[scrub];
  const todayAt = at.today ?? NOW_POINT.today;
  const change = pctChange(at.today ?? NOW_POINT.today, at.today === null ? NOW_POINT.yesterday : at.yesterday);
  const up = change >= 0;
  const past = at.today === null;

  // The headline counts up with each draw.
  const [rolled, setRolled] = useState(NOW_POINT.today);
  useEffect(() => {
    const controls = animate(reduce ? NOW_POINT.today : 0, NOW_POINT.today, { duration: reduce ? 0 : 1.2, ease, onUpdate: setRolled });
    return () => controls.stop();
  }, [run, reduce]);

  const indexAt = (e: PointerEvent<HTMLDivElement>) => {
    const r = e.currentTarget.getBoundingClientRect();
    const minute = ((e.clientX - r.left) / Math.max(r.width, 1)) * DAY_MIN;
    return Math.min(SLOTS, Math.max(0, Math.round(minute / SLOT)));
  };
  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const cur = scrub ?? NOW_INDEX;
    const next =
      e.key === "ArrowRight" ? cur + 1 : e.key === "ArrowLeft" ? cur - 1 : e.key === "PageUp" ? cur + 6 : e.key === "PageDown" ? cur - 6 : e.key === "Home" ? 0 : e.key === "End" ? SLOTS : null;
    if (next === null) {
      if (e.key === "Escape") setScrub(null);
      return;
    }
    e.preventDefault();
    setScrub(Math.min(SLOTS, Math.max(0, next)));
  };

  const orders = Math.round(NOW_POINT.today / TICKET.today);
  const ordersYest = Math.round(NOW_POINT.yesterday / TICKET.yesterday);
  const stats = [
    { label: "Orders so far", value: orders.toLocaleString("en-US"), sub: `${orders - ordersYest >= 0 ? "+" : "−"}${Math.abs(orders - ordersYest)} vs yesterday` },
    { label: "Average order", value: usd2(TICKET.today), sub: `${usd2(TICKET.yesterday)} yesterday` },
    { label: "Busiest hour", value: `${hourText(BUSIEST.hour)} – ${hourText(BUSIEST.hour + 1)}`, sub: `${usd(BUSIEST.value)} in sales` },
    { label: "On pace for", value: usd(onPace), sub: `${usd(YESTERDAY_TOTAL)} yesterday` },
  ];
  const clipId = `${uid}-draw-${run}`;
  const titleId = `${uid}-title`;

  return (
    <section ref={loopRef} {...handlers} aria-labelledby={titleId} className={"@container w-full min-w-0 " + className}>
      <div className="flex flex-col rounded-[20px] bg-surface p-5 shadow-[var(--shadow-card)]">
        <header className="flex flex-wrap items-start justify-between gap-x-6 gap-y-2">
          <div className="min-w-0">
            <h2 id={titleId} className="text-[15px] font-medium leading-5 text-fg">
              Sales today
            </h2>
            <p className="mt-0.5 truncate text-[13px] leading-5 text-fg-muted">
              {STORE.workspace} · {STORE.scope} · {STORE.today}
            </p>
          </div>
          <ul aria-label="Legend" className="flex items-center gap-4 text-[13px] leading-5 text-fg-muted">
            <li className="flex items-center gap-2">
              <span aria-hidden className="h-0.5 w-4 rounded-full bg-[var(--series-1)]" />
              Today
            </li>
            <li className="flex items-center gap-2">
              <span aria-hidden className="h-0.5 w-4 rounded-full bg-[color-mix(in_srgb,var(--fg)_28%,transparent)]" />
              Yesterday
            </li>
          </ul>
        </header>

        <div className="mt-4 flex flex-wrap items-end gap-x-10 gap-y-3">
          <div className="min-w-0">
            <div className="flex items-center gap-2">
              <p className="text-[13px] font-medium leading-5 text-fg-muted">Gross sales</p>
              <span className={`inline-flex h-5 items-center rounded-full px-1.5 text-[12px] font-medium tabular-nums ${up ? "bg-[var(--success-soft)] text-[var(--success-text)]" : "bg-[var(--danger-soft)] text-danger-text"}`}>
                <span className="sr-only">{up ? "Up" : "Down"} on yesterday by this time: </span>
                {`${up ? "+" : "−"}${Math.abs(change).toFixed(1)}%`}
              </span>
            </div>
            <p className="mt-1 text-[32px] font-medium leading-10 tracking-[-0.02em] text-fg tabular-nums">
              <span aria-hidden>{usd(scrub === null ? rolled : todayAt)}</span>
              <span className="sr-only">{usd(NOW_POINT.today)}</span>
            </p>
            <p className="text-[13px] leading-5 text-fg-muted tabular-nums">
              {past ? `So far · ${clock(at.minute)} hasn’t come yet` : scrub === null ? `By ${clock(NOW_MIN)}, now` : `By ${clock(at.minute)}`}
            </p>
          </div>
          <div className="min-w-0">
            <p className="text-[13px] font-medium leading-5 text-fg-muted">Yesterday by {clock(at.minute)}</p>
            <p className="mt-1 text-[20px] font-medium leading-7 tracking-[-0.01em] text-fg-muted tabular-nums">{usd(at.yesterday)}</p>
          </div>
        </div>

        <div ref={plotRef} className="relative mt-5 w-full [contain:inline-size]" style={{ height: H }}>
          <svg width={W} height={H} className="block overflow-visible" aria-hidden>
            <defs>
              <clipPath id={clipId}>
                <motion.rect x={-4} y={-8} height={H + 16} initial={{ width: reduce ? x(NOW_MIN) + 8 : 0 }} animate={{ width: x(NOW_MIN) + 8 }} transition={{ duration: reduce ? 0 : 1.2, ease }} />
              </clipPath>
            </defs>
            {Array.from({ length: 25 }, (_, h) => (
              <line key={h} x1={r2(x(h * 60))} x2={r2(x(h * 60))} y1={0} y2={H} stroke="color-mix(in srgb, var(--fg) 7%, transparent)" strokeWidth={1} />
            ))}
            <path d={yestLine} fill="none" stroke="color-mix(in srgb, var(--fg) 28%, transparent)" strokeWidth={1.5} strokeLinejoin="round" strokeLinecap="round" />
            <g key={run} clipPath={`url(#${clipId})`}>
              <path d={todayLine} fill="none" stroke="var(--series-1)" strokeWidth={1.5} strokeLinejoin="round" strokeLinecap="round" />
            </g>
            {scrub !== null ? (
              <g>
                <line x1={x(at.minute)} x2={x(at.minute)} y1={0} y2={H} stroke="var(--track-strong)" />
                <circle cx={x(at.minute)} cy={y(at.yesterday)} r={3.5} fill="var(--surface)" stroke="color-mix(in srgb, var(--fg) 45%, transparent)" strokeWidth={1.5} />
                {!past && <circle cx={x(at.minute)} cy={y(todayAt)} r={4} fill="var(--series-1)" stroke="var(--surface)" strokeWidth={2} />}
              </g>
            ) : (
              <motion.circle
                key={`now-${run}`}
                cx={x(NOW_MIN)}
                cy={y(NOW_POINT.today)}
                r={3.5}
                fill="var(--surface)"
                stroke="var(--series-1)"
                strokeWidth={1.5}
                initial={reduce ? false : { scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ type: "spring", stiffness: 420, damping: 30, delay: reduce ? 0 : 1.1 }}
              />
            )}
          </svg>
          <div
            role="slider"
            tabIndex={0}
            aria-label="Sales by time of day"
            aria-valuemin={0}
            aria-valuemax={SLOTS}
            aria-valuenow={scrub ?? NOW_INDEX}
            aria-valuetext={`${clock(at.minute)}: ${past ? "today not yet" : `today ${usd(todayAt)}`}, yesterday ${usd(at.yesterday)}`}
            onPointerMove={(e) => setScrub(indexAt(e))}
            onPointerDown={(e) => setScrub(indexAt(e))}
            onPointerLeave={() => setScrub(null)}
            onKeyDown={onKeyDown}
            onFocus={(e) => {
              if (e.currentTarget.matches(":focus-visible")) setScrub((s) => s ?? NOW_INDEX);
            }}
            onBlur={() => setScrub(null)}
            className={`absolute -inset-1 cursor-crosshair touch-pan-y rounded-[10px] ${ring}`}
          />
        </div>
        <div className="mt-2 flex justify-between text-[12px] leading-4 text-fg-subtle tabular-nums" aria-hidden>
          <span>12 AM</span>
          <span className="hidden @min-[480px]:inline">6 AM</span>
          <span className="hidden @min-[480px]:inline">12 PM</span>
          <span className="hidden @min-[480px]:inline">6 PM</span>
          <span>12 AM</span>
        </div>

        <dl className="mt-5 grid grid-cols-2 gap-x-4 gap-y-4 border-t border-border pt-4 @min-[720px]:grid-cols-4">
          {stats.map((s, i) => (
            <div key={s.label} className={`min-w-0 ${i ? "@min-[720px]:border-l @min-[720px]:border-border @min-[720px]:pl-4" : ""}`}>
              <dt className="truncate text-[13px] leading-5 text-fg-muted">{s.label}</dt>
              <dd className="mt-1 truncate text-[20px] font-medium leading-7 tracking-[-0.01em] text-fg tabular-nums">{s.value}</dd>
              <dd className="truncate text-[12px] leading-4 text-fg-muted tabular-nums">{s.sub}</dd>
            </div>
          ))}
        </dl>
      </div>
    </section>
  );
}

使用说明

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

包依赖 · motion、react