Receipts
Social proof with nothing made up. Stars, the latest release, npm installs and a line from the release notes load live from public APIs, each linking to its source, and it says plainly when it is offline.
npx shadcn@latest add https://captain-ui.vercel.app/r/receipts.jsonReceipts for the engine underneath
Captain UI animates with Motion. These figures load live from GitHub and npm, and every one links to where it came from.
stars on GitHub for motiondivision/motionlatest versionGitHub releasesinstalls from npm last weeknpmsince the last pushGitHub commitsforksGitHub
Fetching from GitHub and npm.
"use client";
// Captain UI · Receipts, MIT. Social proof with nothing made up: live figures and a quote fetched from GitHub and npm, each linking to its source, with an honest offline state.
import { motion, useReducedMotion } from "motion/react";
import { useEffect, useState, type ReactNode } from "react";
import { EASE, cx } from "@/registry/captain/ui/captain";
import { Icon } from "@/registry/captain/ui/icons";
type ReceiptsProps = {
/** A public GitHub repository, as "owner/name". */
repo: string;
/** An npm package, for weekly downloads. */
npm?: string;
title: ReactNode;
body?: ReactNode;
className?: string;
};
type Data = {
stars: number;
forks: number;
pushedAt: string;
release?: { tag: string; at: string; url: string; quote?: string };
downloads?: number;
description?: string;
fetchedAt: number;
};
type State = { kind: "loading" } | { kind: "live"; data: Data } | { kind: "cached"; data: Data } | { kind: "offline" };
const FRESH = 10 * 60 * 1000;
/** The first plain sentence of a release note, with markdown stripped. */
function firstSentence(md?: string | null) {
if (!md) return undefined;
for (const raw of md.split("\n")) {
const line = raw
.replace(/^[\s>*#-]+/, "")
.replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[`*_]/g, "")
.replace(/\s*\(?#\d+\)?\s*$/, "")
.replace(/\s*@[\w-]+/g, "")
.trim();
if (line.length < 18 || /^(what's changed|changelog|full changelog|features|fixes|bug fixes|breaking)/i.test(line)) continue;
const s = line.split(/(?<=[.!?])\s/)[0] ?? line;
return s.length > 140 ? `${s.slice(0, 137).trimEnd()}...` : s;
}
return undefined;
}
async function load(repo: string, npm?: string): Promise<Data> {
const gh = (path: string) => fetch(`https://api.github.com/repos/${repo}${path}`, { headers: { Accept: "application/vnd.github+json" } });
// The list endpoints answer 200 with an empty array when a repo has no releases, so nothing logs a 404.
const [r, rels, dl] = await Promise.all([
gh(""),
gh("/releases?per_page=1").catch(() => null),
npm ? fetch(`https://api.npmjs.org/downloads/point/last-week/${encodeURIComponent(npm)}`).catch(() => null) : Promise.resolve(null),
]);
if (!r.ok) throw new Error(`GitHub ${r.status}`);
const j = await r.json();
const data: Data = { stars: j.stargazers_count, forks: j.forks_count, pushedAt: j.pushed_at, fetchedAt: Date.now() };
const rel = rels?.ok ? ((await rels.json()) as { tag_name: string; published_at: string; html_url: string; body?: string }[])[0] : undefined;
if (rel) {
data.release = { tag: rel.tag_name, at: rel.published_at, url: rel.html_url, quote: firstSentence(rel.body) };
} else {
// No GitHub releases: fall back to the newest tag and the date of its commit.
const tags = await gh("/tags?per_page=1").catch(() => null);
const tag = tags?.ok ? ((await tags.json()) as { name: string; commit: { sha: string } }[])[0] : undefined;
if (tag) {
const c = await gh(`/commits/${tag.commit.sha}`).catch(() => null);
const at = c?.ok ? (await c.json()).commit?.committer?.date : undefined;
if (at) data.release = { tag: tag.name, at, url: `https://github.com/${repo}/releases/tag/${encodeURIComponent(tag.name)}` };
}
}
if (j.description) data.description = j.description;
if (dl?.ok) data.downloads = (await dl.json()).downloads;
return data;
}
const compact = (n: number) => new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 }).format(n);
const full = (n: number) => new Intl.NumberFormat("en-US").format(n);
function ago(iso: string | number) {
const s = (new Date(iso).getTime() - Date.now()) / 1000;
const rtf = new Intl.RelativeTimeFormat("en-GB", { numeric: "auto" });
const steps: [Intl.RelativeTimeFormatUnit, number][] = [["year", 31536000], ["month", 2592000], ["week", 604800], ["day", 86400], ["hour", 3600], ["minute", 60]];
for (const [unit, size] of steps) if (Math.abs(s) >= size) return rtf.format(Math.round(s / size), unit);
return "just now";
}
const clock = (t: number) => new Date(t).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });
export function Receipts({ repo, npm, title, body, className }: ReceiptsProps) {
const [state, setState] = useState<State>({ kind: "loading" });
const reduce = useReducedMotion();
const key = `cu-receipts:${repo}:${npm ?? ""}`;
useEffect(() => {
let alive = true;
let cached: Data | null = null;
try {
cached = JSON.parse(localStorage.getItem(key) ?? "null");
} catch {}
if (cached && Date.now() - cached.fetchedAt < FRESH) {
setState({ kind: "live", data: cached });
return;
}
load(repo, npm)
.then((data) => {
if (!alive) return;
setState({ kind: "live", data });
try {
localStorage.setItem(key, JSON.stringify(data));
} catch {}
})
.catch(() => alive && setState(cached ? { kind: "cached", data: cached } : { kind: "offline" }));
return () => {
alive = false;
};
}, [repo, npm, key]);
const d = state.kind === "live" || state.kind === "cached" ? state.data : null;
const gh = `https://github.com/${repo}`;
const rows: { label: string; value?: string; title?: string; href: string; source: string }[] = [
{
label: d?.release ? `latest version, tagged ${ago(d.release.at)}` : "latest version",
value: d?.release?.tag,
href: d?.release?.url ?? `${gh}/releases`,
source: "GitHub releases",
},
...(npm
? [{ label: "installs from npm last week", value: d?.downloads !== undefined ? compact(d.downloads) : undefined, title: d?.downloads !== undefined ? full(d.downloads) : undefined, href: `https://www.npmjs.com/package/${npm}`, source: "npm" }]
: []),
{ label: "since the last push", value: d ? ago(d.pushedAt) : undefined, title: d ? new Date(d.pushedAt).toUTCString() : undefined, href: `${gh}/commits`, source: "GitHub commits" },
{ label: "forks", value: d ? compact(d.forks) : undefined, title: d ? full(d.forks) : undefined, href: `${gh}/forks`, source: "GitHub" },
];
const enter = (i: number) =>
reduce ? { initial: { opacity: 0 }, animate: { opacity: 1 } } : { initial: { opacity: 0, y: 6 }, animate: { opacity: 1, y: 0 }, transition: { duration: 0.28, ease: EASE, delay: i * 0.05 } };
return (
<section className={cx("@container w-full", className)} aria-busy={state.kind === "loading"}>
<div className="grid grid-cols-1 gap-8 @[760px]:grid-cols-[minmax(0,5fr)_minmax(0,6fr)] @[760px]:gap-12">
<div>
<h2 className="text-[clamp(26px,4.4cqw,40px)] leading-[1.08] font-semibold tracking-[-0.03em] text-balance text-ink">{title}</h2>
{body ? <div className="mt-3 max-w-[44ch] text-[16px] leading-[1.55] text-ink-2">{body}</div> : null}
<a href={`${gh}/stargazers`} target="_blank" rel="noreferrer" className="group mt-8 block w-fit rounded-inner -mx-2 px-2 py-1 hover:bg-hover focus-visible:bg-hover">
{d ? (
<motion.span key="v" {...enter(0)} className="tnum block text-[clamp(56px,11cqw,96px)] leading-none font-semibold tracking-[-0.045em] text-ink" title={full(d.stars)}>
{compact(d.stars)}
</motion.span>
) : (
<span className="well block h-[clamp(56px,11cqw,96px)] w-[3.2em] rounded-inner text-[clamp(56px,11cqw,96px)]" aria-hidden="true" />
)}
<span className="mt-2 flex items-center gap-1.5 text-[15px] text-ink-2">
stars on GitHub for <span className="font-medium text-ink">{repo}</span>
<Icon name="arrowRight" size={14} className="-rotate-45 opacity-60 transition-opacity group-hover:opacity-100" />
</span>
</a>
</div>
<div className="grid content-start gap-1">
{rows.map((r, i) => (
<a
key={r.source + r.label}
href={r.href}
target="_blank"
rel="noreferrer"
className="group -mx-2 flex items-baseline gap-3 rounded-inner px-2 py-2.5 hover:bg-hover focus-visible:bg-hover"
>
{r.value ? (
<motion.span {...enter(i + 1)} className="tnum min-w-[4.5ch] text-[22px] leading-7 font-semibold tracking-[-0.02em] text-ink" title={r.title}>
{r.value}
</motion.span>
) : (
<span aria-hidden="true" className="well inline-block h-6 w-[4.5ch] translate-y-1 rounded-[5px] text-[22px]" />
)}
<span className="min-w-0 flex-1 text-[15px] text-ink-2">{r.label}</span>
<span className="hidden shrink-0 items-center gap-1 text-[13px] text-ink-3 @[420px]:inline-flex">
{r.source}
<Icon name="arrowRight" size={13} className="-rotate-45 opacity-60 transition-opacity group-hover:opacity-100" />
</span>
</a>
))}
{d && (d.release?.quote || d.description) ? (
<motion.figure {...enter(rows.length + 1)} className="well mt-4 rounded-shell p-5">
<blockquote className="text-[17px] leading-[1.5] text-ink">{d.release?.quote ?? d.description}</blockquote>
<figcaption className="mt-3 text-[13px] text-ink-2">
{d.release?.quote ? "From the " : "The maintainers, in the "}
<a
href={d.release?.quote ? d.release.url : gh}
target="_blank"
rel="noreferrer"
className="text-ink underline decoration-rim-strong underline-offset-[3px] hover:decoration-ink"
>
{d.release?.quote ? `${d.release.tag} release notes` : "repository description"}
</a>
</figcaption>
</motion.figure>
) : null}
<p role="status" className="mt-3 px-0 text-[13px] text-ink-3">
{state.kind === "loading"
? "Fetching from GitHub" + (npm ? " and npm" : "") + "."
: state.kind === "live"
? `Live from the GitHub${npm ? " and npm" : ""} public APIs, fetched ${clock(state.data.fetchedAt)}.`
: state.kind === "cached"
? `GitHub could not be reached, so these are the figures from ${clock(state.data.fetchedAt)}. Each link still goes to the live source.`
: "GitHub could not be reached just now. Each link still goes to the live source."}
</p>
</div>
</div>
</section>
);
}Usage
import { Receipts } from "@/components/ui/receipts"
<Receipts repo="motiondivision/motion" npm="motion" title="Receipts for the engine underneath" />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| repo | string | A public GitHub repository, as "owner/name". | |
| npm | string | An npm package name, for weekly installs. Optional. | |
| title | ReactNode | The section heading. | |
| body | ReactNode | A sentence saying what the figures are. |
Accessibility
- Every figure is a link to its source, named by its label and value.
- The section is aria-busy while fetching, and a status line says where the figures came from and when.
- Offline, it shows the last figures it saw with their date, or says it could not reach GitHub; it never invents a number.
- Unauthenticated GitHub calls are limited to 60 an hour per visitor, so results are cached for ten minutes in localStorage.