Stat cards
Four headline numbers with sparklines and a period switch. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.
Need this designed into your product? Book a call
Install
Add it to your project with the CLI.
HTML, CSS and JS
npx designme add stat-cardsReact
npx designme add stat-cards --reactAstro
npx designme add stat-cards --astroshadcn, React
npx shadcn@latest add https://designme.dev/r/shadcn/stat-cards.json shadcn, Astro
npx shadcn@latest add https://designme.dev/r/shadcn/astro/stat-cards.json The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.
About
What it is for and what it does.
A row of headline numbers, each on its own card (in Studio, a cell of one panel) with an icon, its change against the period before and a sparkline. A head holds a title, like Workspace, on the left and a period switch, such as 7 days, 30 days and Quarter, on the right; the switch rolls every number and line to the new values at once. It works as the top row of an agent dashboard, for numbers like runs, hours saved and spend.
- At the top of a dashboard, to show the few numbers people check first.
- When you want to show an agent's runs, time saved or cost at a glance.
- When the same numbers need comparing across a few fixed periods.
- Each card shows an icon, a label, a large number that rolls to its value, and its change against the period before as a percentage.
- A sparkline per card draws in from the left, in the card's
color, or the chart palette in order: the accent, then violet, green and orange. In Studio the four are cells of one panel, split by hairlines, with the title and period switch in an off-white head strip; each sparkline is a thin line in the same colours (the accent is white in Studio's dark mode), and the area under it fades from the line's colour to nothing. - Each stat has one entry in
valuesper entry inperiods, and switching the period updates every card together. - Pointing at the change shows the period's
comparetext, like "vs previous 30 days". The cards aren't buttons, so pointing at a card itself changes nothing. prefixandsuffixwrap the number, like "$" or "h".sparkRangeputs every sparkline on the same scale; by default each card scales to its own lowest and highest point.- The change sits in a tinted chip with dark text in its hue: green when the change is good news, red when it isn't, with a true minus sign. For a number that is better when it falls, like spend, set
lowerIsBetterand a fall turns green. - Four across on a wide screen, and two by two on tablets and phones.
- The period switch is a role="group" labelled "Period", with aria-pressed on the active option.
- Screen readers hear the
comparetext after each number's change, so the comparison doesn't depend on pointing. - Sparklines are aria-hidden SVGs.
- The sparkline draw-in is skipped, and number roll-ups finish at once, when the user prefers reduced motion.
Usage
Import it in React and drive it from your own state, or place it in an Astro page.
React
import { StatCards } from '@/components/designme/stat-cards/StatCards';React example
The demo above as a React component, 26 lines you can copy.
'use client';
// The animated preview from designme.dev, rebuilt from the React component: the numbers roll up and the switch changes the period.
import { StatCards, type StatCardsPeriod, type StatCardsStat } from './StatCards';
const PERIODS: StatCardsPeriod[] = [
{ label: '7 days', compare: 'vs previous 7 days' },
{ label: '30 days', compare: 'vs previous 30 days' },
{ label: 'Quarter', compare: 'vs last quarter' }
];
// each card has one shape that wobbles a little differently per period, like real weeks do
const wobble = (base: number[], p: number) => base.map((y, k) => y + Math.sin(k * 1.7 + p * 2) * (p ? 1 : .5));
const stat = (icon: StatCardsStat['icon'], label: string, nums: [number, number][], base: number[], extra: Partial<StatCardsStat> = {}): StatCardsStat =>
({ icon, label, values: nums.map(([value, change], p) => ({ value, change, points: wobble(base, p) })), ...extra });
const STATS: StatCardsStat[] = [
stat('spark', 'Agent runs', [[412, 12], [1730, 18], [4980, 22]], [3, 4, 4, 5, 6, 5, 7, 8]),
stat('users', 'Active editors', [[318, 4], [1130, 9], [1620, 31]], [5, 5, 6, 6, 6, 7, 7, 8]),
stat('clock', 'Hours saved', [[96, 15], [402, 21], [1180, 26]], [2, 3, 3, 4, 5, 6, 6, 8], { suffix: 'h' }),
stat('coins', 'Agent spend', [[84, -6], [341, -3], [960, 8]], [6, 5, 6, 5, 4, 4, 4, 3], { prefix: '$', lowerIsBetter: true })
];
export default function StatCardsDemo() {
return <div style={{ width: '100%' }}><StatCards title="Workspace" stats={STATS} periods={PERIODS} defaultPeriod={1} sparkRange={[0, 8.75]} /></div>;
}
Astro
In a page in src/pages. It plays the demo above; change its stat-cards.js to show your own data. Attributes like class go on its root element.
---
import StatCards from '../components/designme/stat-cards/StatCards.astro';
---
<StatCards />
<StatCards data-style="soft" class="my-class" />Props
Everything StatCards takes.
| Prop | Type | What it does |
|---|---|---|
title | ReactNode | What the numbers are about, like "Workspace": on the left of the head, on one line with the period switch |
statsrequired | StatCardsStat[] | |
periodsrequired | StatCardsPeriod[] | |
period | number | The period on show, by index. Leave it out to let the switch pick it |
defaultPeriod | number | |
onPeriodChange | (period: number) => void | |
sparkRange | [number, number] | The values at the bottom and top of every sparkline. Defaults to each card's own lowest and highest point |
className | string |
Code
The full source, as the CLI installs it.
StatCards.tsxReact · 123 lines
'use client';
import { useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { cx } from '../lib/cx';
import { useControllable, useTween } from '../lib/hooks';
import { Icon, type IconName } from '../lib/icons';
import { enter, Seg, Swap, Tip } from '../lib/motion';
import '../designme.css';
import './stat-cards.css';
export interface StatCardsValue {
/** The number in large type, which rolls to it */
value: number;
/** Change against the period before, in percent. Its chip is green when the change is good news and red when it isn't
(see `lowerIsBetter`) */
change: number;
/** The sparkline, oldest first */
points: number[];
}
export interface StatCardsStat {
/** Identifies the card. Defaults to its label */
key?: string;
icon: IconName;
/** Like "Agent runs" */
label: string;
/** One entry per period, in the same order as `periods` */
values: StatCardsValue[];
/** Before the number, like "$" */
prefix?: string;
/** After the number, like "h" */
suffix?: string;
/** The sparkline's colour, any CSS colour. Defaults to the chart palette: the accent for the first card, then violet, green and orange */
color?: string;
/** For a number that is better when it falls, like spend: its chip turns green as it falls and red as it rises */
lowerIsBetter?: boolean;
}
export interface StatCardsPeriod {
/** The switch label, like "30 days" */
label: string;
/** What the change is measured against, like "vs previous 30 days": shown when you point at the change chip, and read
after the number by screen readers */
compare?: string;
}
export interface StatCardsProps {
/** What the numbers are about, like "Workspace": on the left of the head, on one line with the period switch */
title?: ReactNode;
stats: StatCardsStat[];
periods: StatCardsPeriod[];
/** The period on show, by index. Leave it out to let the switch pick it */
period?: number;
defaultPeriod?: number;
onPeriodChange?: (period: number) => void;
/** The values at the bottom and top of every sparkline. Defaults to each card's own lowest and highest point */
sparkRange?: [number, number];
className?: string;
}
const FLAT = 'M0 30 L100 30';
function Card({ stat, index, period, compare, drawn, range }: { stat: StatCardsStat; index: number; period: number; compare?: string; drawn: boolean; range?: [number, number] }) {
const v = stat.values[Math.min(period, stat.values.length - 1)];
const shown = useTween(drawn ? v.value : 0, 900, 0);
const all = stat.values.flatMap(x => x.points);
const [lo, hi] = range ?? [Math.min(...all), Math.max(...all)];
const d = v.points.map((y, k) => `${k === 0 ? 'M' : 'L'}${(k / Math.max(1, v.points.length - 1) * 100).toFixed(1)} ${(29 - (y - lo) / (hi - lo || 1) * 28).toFixed(1)}`).join(' ');
const { className: entering, style } = enter(index * 70);
// the sparkline draws in from the left as its card arrives
const spark = useRef<SVGSVGElement>(null), gid = 'dm-scx-' + useId().replace(/:/g, '');
useEffect(() => {
const el = spark.current; if (!el || !el.animate || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
const a = el.animate([{ clipPath: 'inset(-4px 100% -4px 0)' }, { clipPath: 'inset(-4px 0% -4px 0)' }], { duration: 1000, delay: 300 + index * 70, easing: 'cubic-bezier(.45,0,.2,1)', fill: 'backwards' });
return () => a.cancel();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// the chip: green when the change is good news, red when it isn't, with a true minus sign; pointing at it says what it is
// measured against. The card isn't a button, so pointing at the card itself changes nothing
const good = stat.lowerIsBetter ? v.change <= 0 : v.change >= 0;
const text = (v.change > 0 ? '+' : v.change < 0 ? '\u2212' : '') + Math.abs(v.change) + '%';
return (
<div className={cx('dm-scx-c dm-panel', entering)} style={style}>
<span className="dm-scx-k"><span className="dm-ic"><Icon name={stat.icon} size="xs" /></span>{stat.label}</span>
<div className="dm-scx-v">
<b className="dm-num">{(stat.prefix ?? '') + Math.round(shown).toLocaleString('en-US') + (stat.suffix ?? '')}</b>
<Tip label={compare ?? ''} off={!compare || !drawn}>
<Swap className={cx('dm-scx-d dm-num', drawn && cx('dm-tag', good ? 'dm-ok' : 'dm-bad', v.change >= 0 ? 'dm-up' : 'dm-dn'))}>{drawn ? text : ''}</Swap>
</Tip>
{compare && <span className="dm-scx-sr">{compare}</span>}
</div>
<div className="dm-scx-sp">
{/* the line and, under it, the area down to the axis, which Studio fills with the line's colour fading to nothing */}
<svg ref={spark} viewBox="0 0 100 30" preserveAspectRatio="none" aria-hidden="true" style={{ color: stat.color ?? `var(--dm-c${index % 6 + 1})` }}>
<defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="currentColor" stopOpacity=".22" /><stop offset="1" stopColor="currentColor" stopOpacity="0" /></linearGradient></defs>
<path className="dm-ar" style={{ fill: `url(#${gid})` }} d={(drawn ? d : FLAT) + ' L100 30 L0 30 Z'} />
<path className="dm-ln" stroke={stat.color ?? `var(--dm-c${index % 6 + 1})`} d={drawn ? d : FLAT} />
</svg>
</div>
</div>
);
}
/** A row of numbers with their change and a sparkline. Switch the period and they roll to the new values. */
export function StatCards({ title, stats, periods, period, defaultPeriod = 0, onPeriodChange, sparkRange, className }: StatCardsProps) {
const [at, setAt] = useControllable(period, defaultPeriod, onPeriodChange);
// the numbers roll up and the lines draw a moment after the cards come in
const [drawn, setDrawn] = useState(false);
useEffect(() => { const t = setTimeout(() => setDrawn(true), 200); return () => clearTimeout(t); }, []);
return (
<div data-dm="" className={cx('dm-scx', className)}>
{(title != null || periods.length > 1) && (
<div className="dm-scx-h">
{title != null && <b className="dm-scx-t">{title}</b>}
{periods.length > 1 && <Seg className="dm-scx-sg" label="Period" value={String(at)} onChange={v => setAt(+v)} options={periods.map((p, i) => ({ value: String(i), label: p.label }))} />}
</div>
)}
<div className="dm-scx-grid">
{stats.map((s, i) => <Card key={s.key ?? s.label} stat={s} index={i} period={at} compare={periods[at]?.compare} drawn={drawn} range={sparkRange} />)}
</div>
</div>
);
}
stat-cards.cssReact · 46 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Stat cards ---------- */
/* a row of headline numbers, each with its change against the period before and a sparkline in the chart palette. The cards
aren't buttons, so a pointer over them changes nothing; the change chip says what it is measured against when you point
at it */
.dm-scx{display:flex;flex-direction:column;gap:10px;width:100%}
/* the head: what the numbers are about on the left, on one line with the period switch (owner, 27 Nov: the switch alone
left a bare bar over the cards) */
.dm-scx-h{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-3)}
.dm-scx-t{min-width:0;font-size:14px;line-height:20px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
/* the card is wide in the library, and the four figures take more of its row, so each is bigger and the whole sits balanced */
.dm-card.dm-wide .dm-stage-in:has(>.dm-scx){max-width:960px}
.dm-scx-sg button{font-size:12px;height:26px;padding:0 10px}
.dm-scx-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
@media (max-width:820px){.dm-scx-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
/* phones keep two columns, two rows, with the cards' 16px insets, and the change chip goes under the number when it can't fit
beside it */
@media (max-width:520px){.dm-scx-grid{gap:var(--dm-s-2)}.dm-scx-v{flex-wrap:wrap;row-gap:var(--dm-s-1)}.dm-scx-sp{height:28px}}
.dm-scx-c{padding:var(--dm-s-4);display:flex;flex-direction:column;gap:6px;min-width:0}
.dm-scx-k{display:flex;align-items:center;gap:6px;font-size:12.5px;line-height:18px;color:var(--dm-muted)}
.dm-scx-k .dm-ic{display:grid;color:var(--dm-fg2)}
.dm-scx-v{display:flex;align-items:center;gap:var(--dm-s-2)}
.dm-scx-v b{font-size:14px;line-height:20px;font-weight:500;letter-spacing:-.02em}
.dm-scx-d{font-size:12px;font-weight:500}
.dm-scx-d.dm-tag{display:inline-flex;height:20px;padding:0 6px;cursor:default}
.dm-scx-sr{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
.dm-scx-sp{height:34px;margin-top:var(--dm-s-1)}
.dm-scx-sp svg{width:100%;height:100%;overflow:visible}
.dm-scx-sp path{fill:none;stroke-width:1.75;vector-effect:non-scaling-stroke;stroke-linejoin:round;transition:d .8s var(--dm-ease)}
/* the area under a line, which only Studio draws */
.dm-scx-sp path.dm-ar{display:none;stroke:none}
/* Studio (owner, 17 and 18 Nov): each card's content 16px in from every edge */
:root[data-style="studio"] .dm-scx-c.dm-panel,:root [data-style="studio"] .dm-scx-c.dm-panel,:root [data-style="studio"].dm-scx-c.dm-panel{padding:16px}
/* Studio (owner, 21 Nov: "design something custom because apart from the switcher and the shape of the containers there's no
difference between Soft and Studio"): one panel instead of four cards. The period switch sits in its off-white head strip
under a hairline; under it the figures are cells of one grid, split by half-strength hairlines (the grid's 1px gaps), each
with its label, figure and change chip (a status chip) on the same lines as its neighbours', 16px in. The sparklines keep
the chart palette, as Soft's do (the first in the accent, white in dark through its token, then --dm-c2 to --dm-c4): thin lines
with straight segments and sharp corners, the area under each fading from its line's colour to nothing */
:root[data-style="studio"] .dm-scx,:root [data-style="studio"] .dm-scx,:root [data-style="studio"].dm-scx{gap:0;background:var(--dm-surface);border-radius:var(--dm-r-card);box-shadow:var(--dm-shadow);overflow:hidden}
:root[data-style="studio"] .dm-scx-h,:root [data-style="studio"] .dm-scx-h,:root [data-style="studio"].dm-scx-h{align-items:center;min-height:48px;padding:var(--dm-strip-y) 16px;background:var(--dm-strip);border-bottom:1px solid var(--dm-line)}
:root[data-style="studio"] .dm-scx>.dm-scx-grid,:root [data-style="studio"] .dm-scx>.dm-scx-grid,:root [data-style="studio"].dm-scx>.dm-scx-grid{gap:1px;background:color-mix(in srgb,var(--dm-line) 50%,var(--dm-surface))}
:root[data-style="studio"] .dm-scx>.dm-scx-grid>.dm-scx-c.dm-panel,:root [data-style="studio"] .dm-scx>.dm-scx-grid>.dm-scx-c.dm-panel,:root [data-style="studio"].dm-scx>.dm-scx-grid>.dm-scx-c.dm-panel{background:var(--dm-surface);border-radius:0;box-shadow:none}
:root[data-style="studio"] .dm-scx-sp path.dm-ln,:root [data-style="studio"] .dm-scx-sp path.dm-ln,:root [data-style="studio"].dm-scx-sp path.dm-ln{stroke-width:1.25;stroke-linejoin:miter}
:root[data-style="studio"] .dm-scx-sp path.dm-ar,:root [data-style="studio"] .dm-scx-sp path.dm-ar,:root [data-style="studio"].dm-scx-sp path.dm-ar{display:inline}
StatCards.astroAstro · 27 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Stat cards: Four headline numbers with sparklines and a period switch.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change stat-cards.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './stat-cards.css';
export interface Props extends HTMLAttributes<'div'> {
/** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', 'wide', className]} data-c="stat-cards" {...rest}>
<div class="stage-in"><Fragment is:raw>
<div class="scx">
<div class="scx-h"><b class="scx-t">Workspace</b><div class="seg2 scx-sg" role="group" aria-label="Period"><button aria-pressed="false" data-v="0">7 days</button><button aria-pressed="true" data-v="1">30 days</button><button aria-pressed="false" data-v="2">Quarter</button></div></div>
<div class="scx-grid"></div>
</div>
</Fragment></div>
</div>
<script>
import './stat-cards.js';
</script>
stat-cards.htmlHTML · 9 lines
<div class="card wide" data-c="stat-cards">
<div class="stage-in">
<div class="scx">
<div class="scx-h"><b class="scx-t">Workspace</b><div class="seg2 scx-sg" role="group" aria-label="Period"><button aria-pressed="false" data-v="0">7 days</button><button aria-pressed="true" data-v="1">30 days</button><button aria-pressed="false" data-v="2">Quarter</button></div></div>
<div class="scx-grid"></div>
</div>
</div>
</div>
stat-cards.cssHTML · 45 lines
/* ---------- Stat cards ---------- */
/* a row of headline numbers, each with its change against the period before and a sparkline in the chart palette. The cards
aren't buttons, so a pointer over them changes nothing; the change chip says what it is measured against when you point
at it */
.scx{display:flex;flex-direction:column;gap:10px;width:100%}
/* the head: what the numbers are about on the left, on one line with the period switch (owner, 27 Nov: the switch alone
left a bare bar over the cards) */
.scx-h{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-3)}
.scx-t{min-width:0;font-size:14px;line-height:20px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
/* the card is wide in the library, and the four figures take more of its row, so each is bigger and the whole sits balanced */
.card.wide .stage-in:has(>.scx){max-width:960px}
.scx-sg button{font-size:12px;height:26px;padding:0 10px}
.scx-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
@media (max-width:820px){.scx-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
/* phones keep two columns, two rows, with the cards' 16px insets, and the change chip goes under the number when it can't fit
beside it */
@media (max-width:520px){.scx-grid{gap:var(--dm-s-2)}.scx-v{flex-wrap:wrap;row-gap:var(--dm-s-1)}.scx-sp{height:28px}}
.scx-c{padding:var(--dm-s-4);display:flex;flex-direction:column;gap:6px;min-width:0}
.scx-k{display:flex;align-items:center;gap:6px;font-size:12.5px;line-height:18px;color:var(--dm-muted)}
.scx-k .ic{display:grid;color:var(--dm-fg2)}
.scx-v{display:flex;align-items:center;gap:var(--dm-s-2)}
.scx-v b{font-size:14px;line-height:20px;font-weight:500;letter-spacing:-.02em}
.scx-d{font-size:12px;font-weight:500}
.scx-d.tag{display:inline-flex;height:20px;padding:0 6px;cursor:default}
.scx-sr{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
.scx-sp{height:34px;margin-top:var(--dm-s-1)}
.scx-sp svg{width:100%;height:100%;overflow:visible}
.scx-sp path{fill:none;stroke-width:1.75;vector-effect:non-scaling-stroke;stroke-linejoin:round;transition:d .8s var(--dm-ease)}
/* the area under a line, which only Studio draws */
.scx-sp path.ar{display:none;stroke:none}
/* Studio (owner, 17 and 18 Nov): each card's content 16px in from every edge */
:root[data-style="studio"] .scx-c.panel,:root [data-style="studio"] .scx-c.panel,:root [data-style="studio"].scx-c.panel{padding:16px}
/* Studio (owner, 21 Nov: "design something custom because apart from the switcher and the shape of the containers there's no
difference between Soft and Studio"): one panel instead of four cards. The period switch sits in its off-white head strip
under a hairline; under it the figures are cells of one grid, split by half-strength hairlines (the grid's 1px gaps), each
with its label, figure and change chip (a status chip) on the same lines as its neighbours', 16px in. The sparklines keep
the chart palette, as Soft's do (the first in the accent, white in dark through its token, then --dm-c2 to --dm-c4): thin lines
with straight segments and sharp corners, the area under each fading from its line's colour to nothing */
:root[data-style="studio"] .scx,:root [data-style="studio"] .scx,:root [data-style="studio"].scx{gap:0;background:var(--dm-surface);border-radius:var(--dm-r-card);box-shadow:var(--dm-shadow);overflow:hidden}
:root[data-style="studio"] .scx-h,:root [data-style="studio"] .scx-h,:root [data-style="studio"].scx-h{align-items:center;min-height:48px;padding:var(--dm-strip-y) 16px;background:var(--dm-strip);border-bottom:1px solid var(--dm-line)}
:root[data-style="studio"] .scx>.scx-grid,:root [data-style="studio"] .scx>.scx-grid,:root [data-style="studio"].scx>.scx-grid{gap:1px;background:color-mix(in srgb,var(--dm-line) 50%,var(--dm-surface))}
:root[data-style="studio"] .scx>.scx-grid>.scx-c.panel,:root [data-style="studio"] .scx>.scx-grid>.scx-c.panel,:root [data-style="studio"].scx>.scx-grid>.scx-c.panel{background:var(--dm-surface);border-radius:0;box-shadow:none}
:root[data-style="studio"] .scx-sp path.ln,:root [data-style="studio"] .scx-sp path.ln,:root [data-style="studio"].scx-sp path.ln{stroke-width:1.25;stroke-linejoin:miter}
:root[data-style="studio"] .scx-sp path.ar,:root [data-style="studio"] .scx-sp path.ar,:root [data-style="studio"].scx-sp path.ar{display:inline}
stat-cards.jsHTML · 32 lines
DM.def('stat-cards', (r, c) => {
// icon, label, [value, change %] for each period, unit, the sparkline's shape, and whether lower is better: spend falling is
// good news, so its chip is green when it falls and red when it rises
const S = [
['spark','Agent runs',[[412,12],[1730,18],[4980,22]],'',[3,4,4,5,6,5,7,8]],
['users','Active editors',[[318,4],[1130,9],[1620,31]],'',[5,5,6,6,6,7,7,8]],
['clock','Hours saved',[[96,15],[402,21],[1180,26]],'h',[2,3,3,4,5,6,6,8]],
['coins','Agent spend',[[84,-6],[341,-3],[960,8]],'$',[6,5,6,5,4,4,4,3],true]
];
const CMP = ['vs previous 7 days','vs previous 30 days','vs last quarter'];
const grid = $('.scx-grid', r), uid = Math.random().toString(36).slice(2, 7); let per = 1;
// each sparkline is its line and, under it, the area down to the axis, which Studio fills with the line's colour fading to nothing
grid.innerHTML = S.map((s, i) => `<div class="scx-c panel"><span class="scx-k"><span class="ic">${I(s[0],'xs')}</span>${s[1]}</span><div class="scx-v"><b class="num">0</b><span class="scx-d num"></span><span class="scx-sr"></span></div><div class="scx-sp"><svg viewBox="0 0 100 30" preserveAspectRatio="none" style="color:var(--dm-c${i + 1})"><defs><linearGradient id="scx-${uid}-${i}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="currentColor" stop-opacity=".22"/><stop offset="1" stop-color="currentColor" stop-opacity="0"/></linearGradient></defs><path class="ar" style="fill:url(#scx-${uid}-${i})" d="M0 30 L100 30 Z"/><path class="ln" stroke="var(--dm-c${i + 1})" d="M0 30 L100 30"/></svg></div></div>`).join('');
const cards = $$('.scx-c', grid), cur = S.map(() => 0);
const fmt = (s, v) => s[3] === '$' ? '$' + Math.round(v).toLocaleString('en-US') : Math.round(v).toLocaleString('en-US') + s[3];
function draw(p){
per = p; cards.forEach((el, i) => { const s = S[i], [val, ch] = s[2][p];
tween(cur[i], val, 900, v => { cur[i] = v; $('b', el).textContent = fmt(s, v); });
// the chip: green when the change is good news, red when it isn't, with a true minus sign; pointing at it says what it
// is measured against, and screen readers hear it after the number
const good = s[5] ? ch <= 0 : ch >= 0, txt = (ch > 0 ? '+' : ch < 0 ? '\u2212' : '') + Math.abs(ch) + '%';
const d = $('.scx-d', el); d.className = 'tag scx-d num ' + (good ? 'ok' : 'bad') + (ch >= 0 ? ' up' : ' dn'); swap(d, txt); d.dataset.tip = CMP[p];
$('.scx-sr', el).textContent = CMP[p];
const pts = s[4].map((y, k) => { const yy = y + Math.sin(k * 1.7 + p * 2) * (p ? 1 : .5); return `${k === 0 ? 'M' : 'L'}${(k / 7 * 100).toFixed(1)} ${(29 - yy * 3.2).toFixed(1)}`; }).join(' ');
$('path.ln', el).setAttribute('d', pts); $('path.ar', el).setAttribute('d', pts + ' L100 30 L0 30 Z'); });
}
seg($('.scx-sg', r), v => draw(+v));
stagger(cards, 70);
c.later(240, () => draw(1));
if (!REDUCE) cards.forEach((el, i) => $('.scx-sp svg', el).animate([{ clipPath:'inset(-4px 100% -4px 0)' }, { clipPath:'inset(-4px 0% -4px 0)' }], { duration:1000, delay:300 + i * 70, easing:'cubic-bezier(.45,0,.2,1)', fill:'backwards' }));
});
Questions
What people ask about it.
- Can a number show decimals?
- No. The large number is rounded to a whole number and written with thousands separators, like 1,730. Pass a smaller unit, or put the unit in
suffix, if you need finer detail. - How do I compare sparklines across cards?
- Pass
sparkRangeas [bottom, top]. Every card then uses the same scale, so a taller line means a bigger value on every card. - How do I hide the period switch?
- Pass a single entry in
periods, with one value per stat. The switch only shows with two or more periods.
More in Charts and tables
Lightweight charts and tables for dashboards and reports, drawn in plain SVG and HTML.