"use client";
import { AnimatePresence, motion } from "motion/react";
import { useId, useMemo, useState } from "react";
import { cn } from "@/lib/utils";
import { RollingDigits } from "./rolling-digits";
/**
* Stacked Bars — an original take inspired by bencho.dev's "Stacked bars".
* A compact traffic chart: four sources stack upward, bounces hang below the
* line. Point at a column (or arrow to it) and the rest step back while a
* breakdown springs in beside it. Day/Week regrows every bar left to right.
*/
const SOURCES = [
{ key: "direct", label: "Direct", colour: "#9b7bf0", mono: 0.92 },
{ key: "search", label: "Search", colour: "#4f86f7", mono: 0.74 },
{ key: "referral", label: "Referral", colour: "#7f93ad", mono: 0.56 },
{ key: "email", label: "Email", colour: "#e7a93c", mono: 0.4 },
] as const;
const BOUNCE = { label: "Bounced", colour: "#ef4444" };
type Row = { date: string; direct: number; search: number; referral: number; email: number; bounced: number };
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const label = (d: Date) => `${MONTHS[d.getMonth()]} ${d.getDate()}`;
/** Deterministic sample traffic so server and client render the same chart. */
function sample(n: number, range: "day" | "week"): Row[] {
let seed = range === "day" ? 104729 : 7919 * 131;
const r = () => {
seed = (seed * 48271) % 2147483647;
return seed / 2147483647;
};
for (let i = 0; i < 8; i++) r(); // warm up so the first rows aren't tiny
const end = new Date(2026, 9, 11);
const k = range === "day" ? 1 : 6.4;
return Array.from({ length: n }, (_, i) => {
const d = new Date(end);
d.setDate(end.getDate() - (n - 1 - i) * (range === "day" ? 1 : 7));
const wave = 0.82 + 0.18 * Math.sin(i * 1.3 + (range === "day" ? 0 : 2));
const quiet = r() < 0.1 ? 0.6 : 1;
const base = (950 + r() * 500) * wave * quiet * k;
return {
date: label(d),
direct: Math.round(base * (0.28 + r() * 0.14)),
search: Math.round(base * (0.22 + r() * 0.12)),
referral: Math.round(base * (0.1 + r() * 0.08)),
email: Math.round(base * (0.12 + r() * 0.1)),
bounced: Math.round(base * (0.05 + r() * 0.07)),
};
});
}
export function StackedBars({
bars = 20,
gap = 6,
mono = false,
outlined = false,
defaultRange = "day",
}: {
/** Number of columns (8–24). */
bars?: number;
/** Gap between columns, px. */
gap?: number;
/** One colour in shades instead of four hues. */
mono?: boolean;
outlined?: boolean;
defaultRange?: "day" | "week";
}) {
const n = Math.max(8, Math.min(24, Math.round(bars)));
const [range, setRange] = useState<"day" | "week">(defaultRange);
const [hover, setHover] = useState(-1);
const [focusI, setFocusI] = useState(-1);
const segId = useId();
const rows = useMemo(() => sample(n, range), [n, range]);
const visits = rows.reduce((s, r) => s + r.direct + r.search + r.referral + r.email, 0);
const peak = Math.max(...rows.map((r) => r.direct + r.search + r.referral + r.email));
const peakB = Math.max(...rows.map((r) => r.bounced));
const UP = 100;
const DOWN = 20;
const active = hover >= 0 ? hover : focusI;
const fill = (i: number) => (mono ? `color-mix(in oklab, var(--b-fg) ${SOURCES[i].mono * 100}%, transparent)` : SOURCES[i].colour);
const bounceFill = mono ? "color-mix(in oklab, var(--b-fg) 22%, transparent)" : BOUNCE.colour;
return (
<div
className={cn("relative w-[299px] rounded-[22px] bg-[var(--b-surface)] p-[18px] text-[var(--b-fg)] shadow-[var(--b-shadow)]", outlined && "ring-1 ring-[var(--b-line)]")}
>
<div className="flex items-start justify-between">
<div>
<div className="text-[16px] font-medium leading-[20px]">Traffic</div>
<div className="text-[13px] leading-[18px] text-[var(--b-fg-muted)]">Last {n} {range === "day" ? "days" : "weeks"}</div>
</div>
<div role="radiogroup" aria-label="Range" className="flex rounded-[12px] bg-[var(--b-surface-2)] p-[2px]">
{(["day", "week"] as const).map((r) => (
<button
key={r}
type="button"
role="radio"
aria-checked={range === r}
onClick={() => setRange(r)}
className="relative h-[28px] rounded-[10px] px-[12px] text-[13px] font-medium outline-none focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/30"
>
{range === r && (
<motion.span layoutId={`${segId}-seg`} className="absolute inset-0 rounded-[10px] bg-[var(--b-surface)] shadow-[0_1px_2px_rgba(0,0,0,0.25)]" transition={{ type: "spring", stiffness: 500, damping: 38 }} />
)}
<span className={cn("relative transition-colors", range === r ? "text-[var(--b-fg)]" : "text-[var(--b-fg-muted)]")}>{r === "day" ? "Day" : "Week"}</span>
</button>
))}
</div>
</div>
<div className="mt-[14px] flex items-baseline gap-[8px]">
<RollingDigits value={visits} className="text-[32px] font-medium leading-[36px] tracking-[-0.01em]" />
<span className="text-[14px] text-[var(--b-fg-muted)]">visits</span>
</div>
<div
role="listbox"
tabIndex={0}
aria-label={`Daily traffic, ${n} columns. Use the arrow keys to read each one.`}
aria-activedescendant={active >= 0 ? `${segId}-c${active}` : undefined}
onFocus={() => focusI < 0 && setFocusI(n - 1)}
onBlur={() => setFocusI(-1)}
onKeyDown={(e) => {
const cur = focusI < 0 ? n - 1 : focusI;
if (e.key === "ArrowRight") setFocusI(Math.min(n - 1, cur + 1));
else if (e.key === "ArrowLeft") setFocusI(Math.max(0, cur - 1));
else if (e.key === "Home") setFocusI(0);
else if (e.key === "End") setFocusI(n - 1);
else if (e.key === "Escape") setFocusI(-1);
else return;
e.preventDefault();
}}
onPointerLeave={() => setHover(-1)}
className="relative mt-[12px] flex h-[124px] items-stretch rounded-[6px] outline-none focus-visible:ring-2 focus-visible:ring-[var(--b-fg)]/25"
style={{ gap }}
>
<div className="pointer-events-none absolute inset-x-0 h-px bg-[var(--b-line)]" style={{ top: UP + 1 }} />
{rows.map((row, i) => {
const dim = active >= 0 && active !== i;
const tot = row.direct + row.search + row.referral + row.email;
const h = (tot / peak) * (UP - 8);
const segs = SOURCES.map((s) => Math.max(3, (row[s.key] / tot) * h));
return (
<div
key={i}
id={`${segId}-c${i}`}
role="option"
aria-selected={active === i}
aria-label={`${row.date}: ${tot.toLocaleString("en-US")} visits, ${row.bounced} bounced`}
onPointerEnter={() => setHover(i)}
className="relative flex-1"
>
<div className="absolute inset-x-0 flex flex-col-reverse gap-[2px]" style={{ bottom: 124 - UP + 2 }}>
{segs.map((sh, k) => (
<motion.span
key={`${range}-${k}`}
className="block w-full rounded-[2.5px] transition-[filter,opacity] duration-200"
style={{ background: fill(k), opacity: dim ? 0.38 : 1, transformOrigin: "bottom" }}
initial={{ height: 0 }}
animate={{ height: sh }}
transition={{ duration: 0.6, ease: [0.3, 0, 0.15, 1], delay: i * 0.014 + k * 0.02 }}
/>
))}
</div>
<motion.span
key={`${range}-b`}
className="absolute inset-x-0 block rounded-[2.5px] transition-opacity duration-200"
style={{ top: UP + 4, background: bounceFill, opacity: dim ? 0.3 : 0.75 }}
initial={{ height: 0 }}
animate={{ height: Math.max(3, (row.bounced / peakB) * DOWN) }}
transition={{ duration: 0.6, ease: [0.3, 0, 0.15, 1], delay: i * 0.014 }}
/>
{active === i && (
<motion.span
layoutId={`${segId}-ring`}
className="pointer-events-none absolute -inset-x-[3px] rounded-[6px] ring-[1.5px] ring-[var(--b-fg)]/70"
style={{ top: UP - h - 6, bottom: 124 - (UP + 4 + Math.max(3, (row.bounced / peakB) * DOWN)) - 3 }}
transition={{ type: "spring", stiffness: 380, damping: 34 }}
/>
)}
</div>
);
})}
<AnimatePresence>
{active >= 0 && (
<Tip key="tip" row={rows[active]} i={active} n={n} fill={fill} bounceFill={bounceFill} />
)}
</AnimatePresence>
</div>
<div className="mt-[10px] flex justify-between text-[13px] text-[var(--b-fg-muted)]">
<span>{rows[0].date}</span>
<span>{rows[n - 1].date}</span>
</div>
</div>
);
}
function Tip({ row, i, n, fill, bounceFill }: { row: Row; i: number; n: number; fill: (k: number) => string; bounceFill: string }) {
const tot = row.direct + row.search + row.referral + row.email;
const right = i < n * 0.55;
const colW = 263 / n;
const left = right ? (i + 1) * colW + 8 : i * colW - 140;
const top3 = [...SOURCES.map((s, k) => ({ label: s.label, v: row[s.key], c: fill(k) }))].sort((a, b) => b.v - a.v).slice(0, 2);
return (
<motion.div
className="pointer-events-none absolute top-[-2px] z-10 w-[132px] rounded-[14px] bg-[var(--b-surface)] p-[10px] text-[13px] shadow-[0_8px_24px_rgba(0,0,0,0.35)] ring-1 ring-[var(--b-line)]"
initial={{ opacity: 0, scale: 0.92, x: left, filter: "blur(3px)" }}
animate={{ opacity: 1, scale: 1, x: left, filter: "blur(0px)" }}
exit={{ opacity: 0, scale: 0.94, filter: "blur(3px)", transition: { duration: 0.12 } }}
transition={{ type: "spring", stiffness: 380, damping: 34 }}
style={{ transformOrigin: right ? "left center" : "right center" }}
>
<div className="flex justify-between">
<span className="text-[var(--b-fg-muted)]">{row.date}</span>
<span className="bencho-tabular font-medium">{tot.toLocaleString("en-US")}</span>
</div>
{[...top3, { label: BOUNCE.label, v: row.bounced, c: bounceFill }].map((r) => (
<div key={r.label} className="mt-[5px] flex items-center gap-[7px]">
<span className="size-[8px] rounded-[2px]" style={{ background: r.c }} />
<span className="flex-1">{r.label}</span>
<span className="bencho-tabular">{r.v.toLocaleString("en-US")}</span>
</div>
))}
</motion.div>
);
}
"use client";
import { AnimatePresence, motion } from "motion/react";
import { useState } from "react";
/**
* Per-digit odometer. Only the digits that change move: going up, the old
* digit rolls out the top while the new one rises in from below (and the
* reverse going down), with a touch of overshoot and motion blur.
*/
export function RollingDigits({
value,
className,
digitClassName,
group = true,
tabular = true,
format,
}: {
value: number;
/** Custom text for the value (e.g. 175.6K). Digits still roll by place. */
format?: (value: number) => string;
className?: string;
digitClassName?: string;
group?: boolean;
/** Equal-width digits (steppers). Turn off for inline counts. */
tabular?: boolean;
}) {
const [track, setTrack] = useState({ value, dir: 1 });
if (track.value !== value) setTrack({ value, dir: value > track.value ? 1 : -1 });
const dir = track.value !== value ? (value > track.value ? 1 : -1) : track.dir;
const text = format ? format(value) : group ? value.toLocaleString("en-US") : String(value);
const chars = text.split("");
// Key digits by their place value (counted from the right) so a carry
// only animates the places that actually changed.
const total = chars.filter((c) => /\d/.test(c)).length;
let seen = 0;
const keyed = chars.map((c) =>
/\d/.test(c)
? { c, key: `d${total - 1 - seen++}` }
: { c, key: `s${total - seen}` }
);
return (
<span className={`${tabular ? "bencho-tabular " : ""}relative inline-flex overflow-hidden ${className ?? ""}`} style={{ lineHeight: 1 }}>
<AnimatePresence initial={false} mode="popLayout">
{keyed.map(({ c, key }) =>
/\d/.test(c) ? (
<motion.span key={key} layout="position" className="relative inline-block" transition={{ layout: { type: "spring", stiffness: 500, damping: 40 } }}>
<AnimatePresence initial={false} mode="popLayout" custom={dir}>
<motion.span
key={c}
custom={dir}
className={`inline-block ${digitClassName ?? ""}`}
variants={{
enter: (d: number) => ({ y: d > 0 ? "70%" : "-70%", opacity: 0, filter: "blur(2px)" }),
center: { y: "0%", opacity: 1, filter: "blur(0px)" },
exit: (d: number) => ({ y: d > 0 ? "-70%" : "70%", opacity: 0, filter: "blur(2px)" }),
}}
initial="enter"
animate="center"
exit="exit"
transition={{ type: "spring", stiffness: 280, damping: 24, mass: 0.8, opacity: { duration: 0.22 } }}
>
{c}
</motion.span>
</AnimatePresence>
</motion.span>
) : (
<motion.span key={key} layout="position" className="inline-block" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
{c}
</motion.span>
)
)}
</AnimatePresence>
</span>
);
}
"use client";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
/**
* Neutral stage the Bencho Originals sit on. The block renders at its
* natural size and is scaled as a whole (like a device preview), so
* strokes, radii and type keep their proportions at any stage size.
*/
export function BenchoStage({
children,
scale = 1.25,
className,
}: {
children: ReactNode;
scale?: number;
className?: string;
}) {
return (
<div
className={cn(
"bencho bencho-font relative flex items-center justify-center overflow-hidden rounded-2xl text-[var(--b-fg)]",
"bg-[var(--b-stage)]",
className
)}
>
<div style={{ transform: `scale(${scale})` }} className="origin-center">
{children}
</div>
</div>
);
}
/* Bencho Originals — shared surface tokens (light / dark). */
.bencho {
--b-stage: #f1f1f1;
--b-surface: #ffffff;
--b-surface-2: #f1f1f1;
--b-fg: #171717;
--b-fg-muted: rgb(23 23 23 / 0.5);
--b-ink: #171717;
--b-invert: #171717;
--b-invert-fg: #ffffff;
--b-line: rgb(0 0 0 / 0.06);
--b-shadow: 0 1px 2px rgb(0 0 0 / 0.04), 0 0 0 1px rgb(0 0 0 / 0.04);
}
.dark .bencho {
--b-stage: #171717;
--b-surface: #262626;
--b-surface-2: #333333;
--b-fg: #ffffff;
--b-fg-muted: rgb(255 255 255 / 0.55);
--b-ink: #ffffff;
--b-invert: #ffffff;
--b-invert-fg: #262626;
--b-line: rgb(255 255 255 / 0.06);
--b-shadow: none;
}
.bencho-font {
font-family: var(--font-bencho-inter), var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
font-feature-settings: "cv11", "ss01";
-webkit-font-smoothing: antialiased;
}
.bencho-tabular { font-variant-numeric: tabular-nums; }
/* Code panel: Shiki dual-theme output, with line numbers */
.bencho-code pre.shiki { background: transparent !important; margin: 0; }
.bencho-code .shiki span { color: var(--shiki-light); }
.dark .bencho-code .shiki span { color: var(--shiki-dark); }
.bencho-code .shiki code { counter-reset: line; display: block; }
.bencho-code .shiki .line::before {
counter-increment: line;
content: counter(line);
display: inline-block;
width: 2.2em;
margin-right: 1.1em;
text-align: right;
opacity: 0.32;
}