Usage meter
90 lines · 1 file · MIT
“1,284 of 2,000 links” with a bar that turns butter near the limit and danger past it.
Links
1,284 of 5,000
Clicks counted · resets Dec 1
1,640 of 2,000
Links keep working. Past 2,000 clicks, new ones are not counted until Dec 1.
Members
7 of 3
Over the limit. Four members lose write access on Dec 14.
import { useId, type ReactNode } from "react";
import { cn } from "./cn";
type Level = "ok" | "near" | "over";
/** Warns at 80% of the limit, the same line rdyrct draws for tracked clicks. */
const NEAR_AT = 0.8;
function levelOf(count: number, limit: number): Level {
if (count > limit) return "over";
if (limit > 0 && count / limit >= NEAR_AT) return "near";
return "ok";
}
const FILL = { ok: "bg-accent", near: "bg-butter", over: "bg-danger" } satisfies Record<
Level,
string
>;
const FIGURE = { ok: "", near: "text-butter", over: "text-danger" } satisfies Record<Level, string>;
const format = (n: number) => n.toLocaleString("en-US");
/**
* Usage against a limit: "1,284 of 2,000 links", a thin bar, and a colour
* that warns before it complains. The accent until 80%, butter from there,
* danger past the limit. The state is also said in words (`note`), so colour
* never carries it alone.
*
* Figures are tabular Figtree, not mono: nobody types 1,284.
*/
export function Meter({
label,
count,
limit,
hint,
note,
className,
}: {
/** What is counted: "Links", "Members". */
label: string;
count: number;
limit: number;
/** After the label, muted: "resets Dec 1". */
hint?: string;
/** A sentence under the bar, for a near or over meter. */
note?: ReactNode;
className?: string;
}) {
const level = levelOf(count, limit);
const share = limit > 0 ? Math.min(1, count / limit) : 1;
const id = useId();
return (
<div className={cn("flex flex-col gap-2", className)}>
<div className="grid grid-cols-[1fr_auto] items-baseline gap-x-6 gap-y-2">
<p id={id} className="text-sm">
{label}
{hint && <span className="text-xs text-muted"> · {hint}</span>}
</p>
<p className="text-right text-sm tnum">
<span className={cn("font-semibold", FIGURE[level])}>{format(count)}</span>{" "}
<span className="text-muted">of {format(limit)}</span>
</p>
<div
role="meter"
aria-labelledby={id}
aria-valuemin={0}
aria-valuemax={limit}
aria-valuenow={count}
aria-valuetext={`${format(count)} of ${format(limit)}`}
className="col-span-2 h-1.5 overflow-hidden rounded-full bg-surface-2"
>
<div
className={cn(
"h-full rounded-full transition-[width,background-color] duration-300 ease-out motion-reduce:transition-none",
FILL[level],
)}
style={{ width: `${Math.max(2, share * 100)}%` }}
/>
</div>
</div>
{note && (
<p className="max-w-prose text-sm text-pretty">
{level === "over" && <span className="font-semibold">Over the limit. </span>}
{note}
</p>
)}
</div>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/meter- Category
- Display
- Files
- meter.tsx