# Snippets
Small, dependency-free pieces for the parts that are easy to get subtly wrong. React + Tailwind v4 with the tokens
from [tokens.md](tokens.md); the logic ports to any stack. On plain HTML, keep the logic and translate each class to
CSS on the same tokens (`bg-accent/15` → `background: color-mix(in srgb, var(--color-accent) 15%, transparent)`).
## Numbers
```ts
const compact = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 }); // 1.2k, 3.4M
export const int = (n: number) => Math.round(n).toLocaleString('en');
export const usd = (n: number, digits = 0) => n.toLocaleString('en', { style: 'currency', currency: 'USD', maximumFractionDigits: digits });
/** Share of a total: never "0.0%" for a real but tiny share. */
export const share = (v: number) => (v === 0 ? '0%' : v < 0.1 ? '<0.1%' : v < 1 ? v.toFixed(1) + '%' : Math.round(v) + '%');
/** Seconds as a duration; round first, so 119.6 is "2m 0s", not "1m 60s". */
export const duration = (s: number) => { const t = Math.round(s); return t >= 60 ? `${Math.floor(t / 60)}m ${t % 60}s` : `${t}s`; };
export const plural = (n: number, word: string) => `${int(n)} ${word}${n === 1 ? '' : 's'}`;
```
## Round axis ticks
```ts
/** 0 and evenly spaced round ticks covering max: 0, 500, 1k, 1.5k… (steps of 1, 2, 2.5 or 5 × 10^n). */
export function niceTicks(max: number, count = 4): number[] {
if (!(max > 0)) return [0];
const raw = max / count, pow = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map(m => m * pow).find(s => s >= raw)!;
return Array.from({ length: Math.ceil(max / step) + 1 }, (_, i) => +(i * step).toFixed(10));
}
// chart top = last tick, label each with compact.format(tick)
```
## Delta badge
```tsx
/** Change vs the previous period. Tiny bases say what they were instead of shouting a percentage. */
export function Delta({ cur, prev, format = int, min = 5, invert = false, vs }: { cur: number; prev: number; format?: (n: number) => string; min?: number; invert?: boolean; vs?: string }) {
if (!prev) return null; // nothing to compare with
if (prev < min) return was {format(prev)} ;
const d = ((cur - prev) / prev) * 100, r = Math.round(d);
if (r === 0) return ±0% ;
const good = invert ? d < 0 : d > 0, text = Math.abs(d) > 999 ? (d > 0 ? '10×+' : '−99%') : `${d > 0 ? '▲' : '▼'} ${Math.abs(r)}%`;
return (
{text}
{vs && {vs} }{/* one or two words: "vs Sep", "yesterday" */}
);
}
```
## Same-elapsed-time comparison window
```ts
/** Previous window for a range starting at local midnight `start` and ending at `end` (now, for "last N days"):
* the same number of days right before it, cut at the same elapsed time. Today 00:00–15:00 → yesterday 00:00–15:00. */
export function previousWindow(start: number, end: number, days: number, midnightOf: (daysBefore: number) => number) {
const prevStart = midnightOf(days); // local midnight `days` days before `start` (DST-safe)
return { start: prevStart, end: Math.min(start, prevStart + (end - start) + 1) };
}
```
## KPI tile with the selected fill
```tsx
{label}
{format(cur)}
{/* no explanatory sub-line: `explain` ("3% of visitors") is the tile's title / tooltip */}
```
## Ranked row with a slim share bar
```tsx
const Bar = ({ pct, money }: { pct: number; money?: boolean }) => (
);
filterBy(row.x)}>
{icon}{row.name}
{int(row.y)}
{share((100 * row.y) / total)}
```
## Range calendar (one month, no library)
```tsx
'use client';
import { useState } from 'react';
const DAY = 864e5, ymd = (t: number) => new Date(t).toISOString().slice(0, 10);
const monthOf = (d: string) => d.slice(0, 7) + '-01';
const addMonths = (first: string, n: number) => { const d = new Date(first); d.setUTCMonth(d.getUTCMonth() + n); return ymd(d.getTime()); };
/** Click the first day, then the last; a click before the start moves the start. Dates are YYYY-MM-DD at UTC midnight. */
export function RangeCalendar({ from, to, max, min, onChange }: { from: string; to: string; max: string; min?: string; onChange: (from: string, to: string) => void }) {
const [month, setMonth] = useState(() => monthOf(to || from || max));
const [hover, setHover] = useState('');
const start = Date.parse(month), lead = (new Date(start).getUTCDay() + 6) % 7; // Monday first
const days = Array.from({ length: 42 }, (_, i) => ymd(start + (i - lead) * DAY)); // 6 rows: no height jump
const end = to || (from && hover > from ? hover : ''); // band follows the pointer
const pick = (d: string) => (!from || to || d < from ? onChange(d, '') : onChange(from, d));
const title = new Date(start).toLocaleDateString('en', { month: 'long', year: 'numeric', timeZone: 'UTC' });
return (
setHover('')}>
setMonth(m => addMonths(m, -1))} className="grid size-8 place-items-center rounded-full hover:bg-soft disabled:opacity-30">‹
{title}
= monthOf(max)} onClick={() => setMonth(m => addMonths(m, 1))} className="grid size-8 place-items-center rounded-full hover:bg-soft disabled:opacity-30">›
{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(w =>
{w}
)}
{days.map((d, i) => {
const out = d.slice(0, 7) !== month.slice(0, 7), off = d > max || (!!min && d < min);
const isStart = d === from, isEnd = !!end && d === end, inside = !!from && !!end && d > from && d < end;
const band = 'absolute inset-y-0 bg-accent/10';
return (
{(inside || (isEnd && !isStart)) && }
{(inside || (isStart && !!end && end !== from)) && }
pick(d)} onPointerEnter={() => setHover(d)}
aria-label={new Date(d).toLocaleDateString('en', { dateStyle: 'full', timeZone: 'UTC' })}
className={`relative grid size-9 place-items-center rounded-full text-[13px] tnum disabled:pointer-events-none disabled:text-line-strong
${isStart || isEnd ? 'bg-accent font-medium text-on-accent' : inside ? 'text-ink' : out ? 'text-muted/60 hover:bg-soft' : 'text-ink hover:bg-soft'}`}>
{+d.slice(8)}
{d === max && }
);
})}
);
}
```
Footer under it: the chosen range ("6 Oct – 17 Oct 2026"), the day count, and an accent Apply button disabled until
both ends exist. Pass `max` = the site's today (in its time zone, not the browser's).
## Ignore stale responses
```ts
const seq = useRef(0);
async function load() {
const n = ++seq.current;
const body = await fetch(url).then(r => (r.ok ? r.json() : null)).catch(() => null);
if (n !== seq.current) return; // a newer request started: this answer is for a site/range no longer shown
body ? setData(body) : setError('Couldn’t refresh. These are the last numbers loaded; retrying in a minute.');
}
```
## Heatmap tiers and cells
```tsx
/** Classed tiers at meaningful thresholds; the problem tier is warm, so the worst cell is the most visible. */
/** Intensity grows toward the problem: healthiest palest. Ink text everywhere (accent on accent fails 4.5:1). */
const tier = (rate: number) => rate >= 95 ? 't1' : rate >= 90 ? 't2' : rate >= 85 ? 't3' : 'warn';
const TIER = {
t1: 'bg-accent/[.07] text-ink-2', t2: 'bg-accent/15 text-ink', t3: 'bg-accent/25 text-ink',
warn: 'bg-warn/30 text-ink underline decoration-2 underline-offset-2', // non-colour cue survives greyscale
};
{days.map((d, i) => {d.short}{d.day} )}
{rows.map(r =>
{r.name}
{r.cells.map((c, i) => c == null
? remind(r)} aria-label={`${r.name}, ${days[i].label}: not marked. Remind ${r.owner}`}
className="grid h-9 place-items-center rounded-[10px] border-[1.5px] border-dashed border-warn/75 bg-warn/[.07] text-warn">{bell}
: {Math.round(c.rate)} )}
)}
```
## Bullet graph
```tsx
/** Few's spec: bar a third of the track, target as a perpendicular line, ranges darker for poor. */
export function Bullet({ value, target, ranges, max, label }: { value: number; target: number; ranges: number[]; max: number; label: string }) {
const pct = (v: number) => `${Math.min(100, (v / max) * 100)}%`;
const shade = ['bg-ink/40', 'bg-ink/25', 'bg-ink/10']; // ranges = ends of poor, fair, good; drawn poor on top
return (
{ranges.map((r, i) => )}
);
}
```
## Segmented share bar
```tsx
`${p.label} ${compact.format(p.value)}`).join(', ')}>
{parts.filter(p => p.value > 0).map(p => (
))}
```
## One tooltip for the whole screen
```ts
/** Any element with data-tip gets the same dark tooltip, on hover and on keyboard focus. */
const tip = document.getElementById('tip')!;
const show = (el: HTMLElement) => {
tip.textContent = el.dataset.tip!; tip.classList.add('show');
const r = el.getBoundingClientRect(), w = tip.offsetWidth, h = tip.offsetHeight;
tip.style.left = `${Math.max(8, Math.min(innerWidth - w - 8, r.left + r.width / 2 - w / 2))}px`;
tip.style.top = `${r.top - h - 8 < 8 ? r.bottom + 8 : r.top - h - 8}px`; // flip below near the top edge
};
const hide = () => tip.classList.remove('show');
for (const type of ['pointerover', 'focusin'] as const)
document.addEventListener(type, e => { const el = (e.target as Element).closest('[data-tip]'); el ? show(el) : hide(); });
document.addEventListener('scroll', hide, true);
document.addEventListener('keydown', e => { if (e.key === 'Escape') hide(); });
```