Line Chart with Range Switch
Single-series line chart in a card whose header holds a headline value, a signed delta and a range switch that drives all three. Use it for one primary metric such as revenue or active users.
How it differs. The range control sits in the header and drives the headline, the delta, the plot and a stat strip together, so chart and stat tile are one component with a dashed previous-period line.
Install
pnpm dlx shadcn@latest add @hazine/line-chart-range-switchAdds 2 files, 3 shadcn primitives (button, card, chart), 1 Hazine item (@hazine/use-controllable-state), and 2 packages (lucide-react, recharts).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/line-chart-range-switch.tsx, 298 lines
"use client"
import * as React from "react"
import { ChartLine, CircleAlert } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { useControllableState } from "@/hooks/use-controllable-state"
import {
DEFAULT_FORMAT,
DEFAULT_LABELS,
LineChartRangeSwitchPlot,
LineChartRangeSwitchStats,
PLOT_BOX,
SKELETON,
TREND_ICONS,
buildModel,
type LineChartAggregate,
type LineChartRange,
type LineChartRangeSwitchLabels,
} from "./line-chart-range-switch.plot"
export type {
LineChartAggregate,
LineChartMoment,
LineChartPoint,
LineChartRange,
LineChartRangeSwitchLabels,
LineChartSummary,
} from "./line-chart-range-switch.plot"
const segmentClass = cn(
"relative inline-flex h-7 min-w-10 cursor-pointer items-center justify-center rounded-sm px-2 text-sm font-medium tabular-nums transition-colors duration-100",
"has-[input:not(:checked)]:hover:bg-muted/50 has-[input:not(:checked)]:active:bg-muted has-[:checked]:bg-primary has-[:checked]:text-primary-foreground",
"has-[:disabled]:pointer-events-none has-[:disabled]:opacity-50",
// The default recipe, not the inset one: inside a filled segment an inset
// outline only reads as the fill shrinking.
"has-[:focus-visible]:z-10 has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-foreground"
)
export interface LineChartRangeSwitchProps
extends Omit<React.ComponentProps<typeof Card>, "title" | "defaultValue"> {
/** Name of the metric. It labels the card, the tooltip and the data table. */
title: string
ranges: LineChartRange[]
/** `value` of the selected range. */
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
/** How points become the headline: their total, the latest point or their mean. */
aggregate?: LineChartAggregate
locale?: string
/** Passed to Intl.NumberFormat for every figure. */
formatOptions?: Intl.NumberFormatOptions
/** Shows skeletons while the selected range is fetched. The switch stays usable. */
loading?: boolean
/** What went wrong and what to do, shown in place of the plot. */
error?: string
onRetry?: () => void
/** Replaces the default message when the selected range has no points. */
empty?: React.ReactNode
labels?: Partial<LineChartRangeSwitchLabels>
}
export function LineChartRangeSwitch({
title,
ranges,
value: valueProp,
defaultValue,
onValueChange,
aggregate = "sum",
locale = "en-US",
formatOptions = DEFAULT_FORMAT,
loading = false,
error,
onRetry,
empty,
labels: labelsProp,
className,
...props
}: LineChartRangeSwitchProps) {
const titleId = React.useId()
const groupName = React.useId()
const labels = { ...DEFAULT_LABELS, ...labelsProp }
const [value, setValue] = useControllableState({
value: valueProp,
defaultValue:
defaultValue ?? ranges.find((range) => !range.disabled)?.value ?? "",
onChange: onValueChange,
})
const active =
ranges.find((range) => range.value === value) ??
ranges.find((range) => !range.disabled) ??
ranges[0]
const failed = Boolean(error) && !loading
const settled = !loading && !error
const model =
active && settled
? buildModel(active, { title, aggregate, locale, formatOptions, labels })
: null
const TrendIcon = model?.trend ? TREND_ICONS[model.trend.direction] : null
// The strip keeps its column count while a range loads.
const statCount = ranges.some((range) => range.previous !== undefined) ? 4 : 3
const rangesRef = React.useRef<HTMLFieldSetElement>(null)
const retried = React.useRef(false)
React.useEffect(() => {
if (failed || !retried.current) return
retried.current = false
// Try again leaves with the message. Focus lands on the selected range
// unless the user has already moved it elsewhere.
const group = rangesRef.current
if (group && group.ownerDocument.activeElement === group.ownerDocument.body) {
group.querySelector<HTMLInputElement>("input:checked")?.focus()
}
}, [failed])
function handleRetry() {
retried.current = true
onRetry?.()
}
return (
<Card
aria-busy={loading || undefined}
{...props}
data-slot="line-chart-range-switch"
className={cn("@container", (loading || model) && "pb-0", className)}
>
<CardHeader>
<div className="flex min-w-0 flex-col gap-3 @md:flex-row @md:items-start @md:justify-between">
<div className="min-w-0">
<p id={titleId} className="text-sm text-pretty text-muted-foreground">
{title}
</p>
<div
data-slot="line-chart-range-switch-headline"
aria-live="polite"
aria-atomic="true"
className="mt-1 flex min-h-9 flex-wrap items-baseline gap-x-3 gap-y-1"
>
{loading && (
<>
<span className="sr-only">
{labels.loading} {title}, {active?.name}
</span>
<span aria-hidden="true" className={cn(SKELETON, "h-9 w-40")} />
</>
)}
{!loading && (
<p
title={model?.headline}
className={cn(
"max-w-full truncate text-3xl font-semibold tracking-tight tabular-nums",
!model && "text-muted-foreground"
)}
>
{/* bdi keeps a leading sign or symbol in front of the digits in RTL. */}
{model ? (
<bdi>{model.headline}</bdi>
) : error ? (
labels.unavailable
) : (
labels.noData
)}
</p>
)}
{model?.trend && TrendIcon && (
<p className="flex flex-wrap items-center gap-x-1.5 text-sm">
<span className="inline-flex items-center gap-1.5 font-medium tabular-nums">
<TrendIcon aria-hidden="true" className="size-3.5" />
<span className="sr-only">{labels[model.trend.direction]}</span>
<bdi>{model.trend.text}</bdi>
</span>
<span className="text-xs text-muted-foreground">
{model.trend.baseline}
</span>
</p>
)}
</div>
</div>
<fieldset
ref={rangesRef}
data-slot="line-chart-range-switch-ranges"
className="min-w-0 shrink-0"
>
<legend className="sr-only">{labels.range}</legend>
<div className="inline-flex flex-wrap gap-0.5 rounded-md border border-foreground/50 p-0.5">
{ranges.map((range) => (
<label key={range.value} className={segmentClass}>
<input
type="radio"
name={groupName}
value={range.value}
checked={range.value === active?.value}
disabled={range.disabled}
onChange={() => setValue(range.value)}
className="sr-only"
/>
{range.label}
<span className="sr-only">, {range.name}</span>
</label>
))}
</div>
</fieldset>
</div>
</CardHeader>
<CardContent>
<figure aria-labelledby={titleId}>
{model && (
<>
<figcaption className="sr-only">
{labels.summary(model.summary)}
</figcaption>
<LineChartRangeSwitchPlot
model={model}
title={title}
label={labels.plot(model.summary)}
locale={locale}
formatOptions={formatOptions}
/>
{/* A table ignores the size limits of sr-only, so a wrapper carries them. */}
<div className="sr-only">
<table>
<caption>
{title}, {active?.name}
</caption>
<thead>
<tr>
<th scope="col">{labels.date}</th>
<th scope="col">{title}</th>
</tr>
</thead>
<tbody>
{model.rows.map((row) => (
<tr key={row.date}>
<th scope="row">{row.label}</th>
<td>{row.text}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)}
{loading && (
<div aria-hidden="true" className={cn(SKELETON, PLOT_BOX)} />
)}
{settled && !model && (
<div
data-slot="line-chart-range-switch-empty"
className={cn(
PLOT_BOX,
"flex flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-border px-4 text-center"
)}
>
{empty ?? (
<>
<ChartLine
aria-hidden="true"
strokeWidth={1.5}
className="mb-2 size-6 text-muted-foreground"
/>
<p className="text-sm font-medium">{labels.empty}</p>
<p className="text-sm text-muted-foreground">{labels.emptyHint}</p>
</>
)}
</div>
)}
{/* Always mounted, so the message is announced when it arrives. */}
<div role="alert">
{failed && (
<div
className={cn(
PLOT_BOX,
"flex flex-col items-center justify-center gap-3 px-4 text-center"
)}
>
<p className="flex items-start gap-1.5 text-start text-sm text-destructive">
<CircleAlert aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
{error}
</p>
{onRetry && (
<Button type="button" variant="outline" size="sm" onClick={handleRetry}>
{labels.retry}
</Button>
)}
</div>
)}
</div>
</figure>
</CardContent>
{(loading || model) && <LineChartRangeSwitchStats cells={model?.cells ?? null} placeholders={statCount} />}
</Card>
)
}
components/hazine/line-chart-range-switch.plot.tsx, 382 lines
"use client"
import { Minus, TrendingDown, TrendingUp } from "lucide-react"
import {
CartesianGrid,
Line,
LineChart,
ReferenceLine,
XAxis,
YAxis,
} from "recharts"
import { cn } from "@/lib/utils"
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig,
} from "@/components/ui/chart"
export interface LineChartPoint {
/** ISO date, for example "2026-10-31". Monthly buckets use the first day. */
date: string
value: number
}
export interface LineChartRange {
value: string
/** Short text on the switch, for example "30D". */
label: string
/** Spoken, lower-case name used inside sentences, for example "last 30 days". */
name: string
/** Empty while the range is not loaded or holds no data. */
points: LineChartPoint[]
/** The same aggregate over the period before this one. Drives the delta and the dashed line. */
previous?: number
/** Stated next to the delta, for example "vs previous 30 days". */
baseline?: string
/** How a point's date is written. Defaults to short month and day. */
dateFormat?: Intl.DateTimeFormatOptions
disabled?: boolean
}
export type LineChartAggregate = "sum" | "last" | "average"
export interface LineChartMoment {
value: string
date: string
}
/** Formatted pieces handed to the sentence builders in `labels`. */
export interface LineChartSummary {
title: string
range: string
value: string
/** Direction word, signed percentage and baseline, when a comparison exists. */
trend?: string
first: LineChartMoment
last: LineChartMoment
highest: LineChartMoment
lowest: LineChartMoment
}
export interface LineChartRangeSwitchLabels {
range: string
up: string
down: string
flat: string
baseline: string
average: string
previousAverage: string
previousLast: string
highest: string
lowest: string
date: string
noData: string
/** Stands in for the headline when loading failed. */
unavailable: string
loading: string
empty: string
emptyHint: string
retry: string
/** The hidden caption of the figure. */
summary: (summary: LineChartSummary) => string
/** The accessible name of the plot. */
plot: (summary: LineChartSummary) => string
}
export const DEFAULT_LABELS: LineChartRangeSwitchLabels = {
range: "Time range",
up: "Up",
down: "Down",
flat: "No change",
baseline: "vs previous period",
average: "Average",
previousAverage: "Previous average",
previousLast: "Previous period end",
highest: "Highest",
lowest: "Lowest",
date: "Date",
noData: "No data",
unavailable: "Unavailable",
loading: "Loading",
empty: "Nothing recorded in this range",
emptyHint: "Pick a longer range to see earlier activity.",
retry: "Try again",
summary: (s) =>
`${s.title}, ${s.range}: ${s.value}. ${s.trend ? `${s.trend}. ` : ""}Highest ${s.highest.value} (${s.highest.date}), lowest ${s.lowest.value} (${s.lowest.date}).`,
plot: (s) =>
`Line chart. ${s.title} went from ${s.first.value} (${s.first.date}) to ${s.last.value} (${s.last.date}).`,
}
export const DEFAULT_FORMAT: Intl.NumberFormatOptions = { maximumFractionDigits: 1 }
const DEFAULT_DATE_FORMAT: Intl.DateTimeFormatOptions = {
month: "short",
day: "numeric",
}
export const TREND_ICONS = { up: TrendingUp, down: TrendingDown, flat: Minus }
export const PLOT_BOX = "h-56 w-full @2xl:h-64"
export const SKELETON = "rounded-md bg-muted motion-safe:animate-pulse"
const FOCUS_WITHIN =
"has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-foreground"
interface Row extends LineChartPoint {
label: string
text: string
}
export interface Model {
rows: Row[]
headline: string
trend: { direction: keyof typeof TREND_ICONS; text: string; baseline: string } | null
/** Level of the dashed comparison line, in the unit of a single point. */
baselineLevel: number | undefined
cells: { key: string; label: string; value: string; note?: string; dashed?: boolean }[]
summary: LineChartSummary
}
interface ModelOptions {
title: string
aggregate: LineChartAggregate
locale: string
formatOptions: Intl.NumberFormatOptions
labels: LineChartRangeSwitchLabels
}
export function buildModel(range: LineChartRange, options: ModelOptions): Model | null {
const { title, aggregate, locale, formatOptions, labels } = options
if (range.points.length === 0) return null
const number = new Intl.NumberFormat(locale, formatOptions)
const percent = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 })
// Date-only strings are UTC midnight, so they are formatted in UTC as well.
const day = new Intl.DateTimeFormat(locale, {
timeZone: "UTC",
...(range.dateFormat ?? DEFAULT_DATE_FORMAT),
})
const rows = range.points.map((point) => ({
...point,
label: day.format(new Date(point.date)),
text: number.format(point.value),
}))
const first = rows[0]
const last = rows[rows.length - 1]
const highest = rows.reduce((best, row) => (row.value > best.value ? row : best))
const lowest = rows.reduce((best, row) => (row.value < best.value ? row : best))
const total = rows.reduce((sum, row) => sum + row.value, 0)
const average = total / rows.length
const amount =
aggregate === "sum" ? total : aggregate === "last" ? last.value : average
const { previous } = range
let trend: Model["trend"] = null
if (previous !== undefined && previous !== 0) {
const change =
Math.round(((amount - previous) / Math.abs(previous)) * 1000) / 10
const direction = change > 0 ? "up" : change < 0 ? "down" : "flat"
const sign = change > 0 ? "+" : change < 0 ? "−" : ""
trend = {
direction,
text: `${sign}${percent.format(Math.abs(change))}%`,
baseline: range.baseline ?? labels.baseline,
}
}
// A total is compared point by point, so its line sits at the previous average.
const baselineLevel =
previous === undefined
? undefined
: aggregate === "sum"
? previous / rows.length
: previous
const moment = (row: Row) => ({ value: row.text, date: row.label })
const cells: Model["cells"] = [
{ key: "average", label: labels.average, value: number.format(average) },
{ key: "highest", label: labels.highest, value: highest.text, note: highest.label },
{ key: "lowest", label: labels.lowest, value: lowest.text, note: lowest.label },
]
if (baselineLevel !== undefined) {
cells.splice(1, 0, {
key: "previous",
label: aggregate === "last" ? labels.previousLast : labels.previousAverage,
value: number.format(baselineLevel),
dashed: true,
})
}
return {
rows,
headline: number.format(amount),
trend,
baselineLevel,
cells,
summary: {
title,
range: range.name,
value: number.format(amount),
trend: trend
? `${labels[trend.direction]} ${trend.text} ${trend.baseline}`
: undefined,
first: moment(first),
last: moment(last),
highest: moment(highest),
lowest: moment(lowest),
},
}
}
interface PlotProps {
model: Model
title: string
label: string
locale: string
formatOptions: Intl.NumberFormatOptions
}
export function LineChartRangeSwitchPlot({ model, title, label, locale, formatOptions }: PlotProps) {
const number = new Intl.NumberFormat(locale, formatOptions)
const axis = new Intl.NumberFormat(locale, {
...formatOptions,
notation: "compact",
minimumFractionDigits: 0,
maximumFractionDigits: 2,
})
// Set on the tick itself: left to the chart library the text keeps a fixed
// grey that is too dim on a dark card.
const tick = { fill: "var(--muted-foreground)" }
const config = {
value: { label: title, color: "var(--chart-1)" },
} satisfies ChartConfig
return (
// The chart surface takes focus for the arrow keys and the host primitive
// hides its outline, so the wrapper draws the focus indicator. Time runs
// start to end as left to right in every locale, and the axis text is
// anchored for that, so the plot is laid out left to right.
<div
dir="ltr"
data-slot="line-chart-range-switch-plot"
className={cn("rounded-md", FOCUS_WITHIN)}
>
<ChartContainer config={config} className={cn("aspect-auto", PLOT_BOX)}>
<LineChart
data={model.rows}
role="img"
aria-label={label}
margin={{ top: 8, right: 8, bottom: 0, left: 0 }}
>
<CartesianGrid vertical={false} />
<XAxis
dataKey="label"
tickLine={false}
axisLine={false}
tickMargin={8}
minTickGap={24}
tick={tick}
interval="preserveStartEnd"
/>
<YAxis
width="auto"
tickLine={false}
axisLine={false}
tickMargin={8}
tickCount={4}
tick={tick}
domain={["auto", "auto"]}
tickFormatter={(tick: number) => axis.format(tick)}
/>
<ChartTooltip
content={
<ChartTooltipContent
formatter={(value) => (
<div className="flex flex-1 items-center justify-between gap-4">
<span className="text-muted-foreground">{title}</span>
<span className="font-medium text-foreground tabular-nums">
{number.format(Number(value))}
</span>
</div>
)}
/>
}
/>
{model.baselineLevel !== undefined && (
<ReferenceLine
y={model.baselineLevel}
stroke="var(--muted-foreground)"
strokeDasharray="4 4"
ifOverflow="extendDomain"
/>
)}
<Line
dataKey="value"
name={title}
type="linear"
stroke="var(--color-value)"
strokeWidth={2}
dot={model.rows.length === 1}
activeDot={{ r: 4 }}
isAnimationActive={false}
/>
</LineChart>
</ChartContainer>
</div>
)
}
interface StatsProps {
/** Null while loading. */
cells: Model["cells"] | null
/** How many skeleton cells stand in while loading. */
placeholders: number
}
export function LineChartRangeSwitchStats({ cells, placeholders }: StatsProps) {
const columns = cells?.length ?? placeholders
return (
<dl
data-slot="line-chart-range-switch-stats"
aria-hidden={cells ? undefined : "true"}
className={cn(
"grid gap-px border-t border-border bg-border bg-clip-padding",
columns === 4 ? "grid-cols-2 @xl:grid-cols-4" : "@sm:grid-cols-3"
)}
>
{(cells ?? Array.from({ length: placeholders }, () => null)).map((cell, index) => (
<div key={cell?.key ?? index} className="min-w-0 bg-card px-4 py-3">
{cell ? (
<>
<dt className="flex items-center gap-1.5 text-xs text-muted-foreground">
{cell.dashed && (
<span
aria-hidden="true"
className="w-4 shrink-0 border-t border-dashed border-muted-foreground"
/>
)}
<span className="min-w-0 text-pretty">{cell.label}</span>
</dt>
<dd className="mt-1 flex flex-wrap items-baseline gap-x-1.5 text-sm font-medium tabular-nums">
<bdi className="truncate" title={cell.value}>
{cell.value}
</bdi>
{cell.note && (
<span className="text-xs font-normal text-muted-foreground">
{cell.note}
</span>
)}
</dd>
</>
) : (
<>
<dt className={cn(SKELETON, "h-3 w-16")} />
<dd className={cn(SKELETON, "mt-2 h-4 w-20")} />
</>
)}
</div>
))}
</dl>
)
}
The demo in the preview, 301 lines
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import {
LineChartRangeSwitch,
type LineChartPoint,
type LineChartRange,
} from "@/components/hazine/line-chart-range-switch"
const DAY_MS = 86_400_000
const DAY_COUNT = 730
// Two full years that end on Oct 31, 2026, so twelve whole months equal 365 days.
const FIRST_DAY = Date.UTC(2024, 10, 1)
const USD: Intl.NumberFormatOptions = {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
}
// Integer arithmetic only, so the server and every browser produce the same series.
function settledOn(index: number) {
const weekday = new Date(FIRST_DAY + index * DAY_MS).getUTCDay()
const growth = 2400 + Math.floor((index * 13) / 5)
const season = 300 - Math.abs((index % 365) - 182) * 2
const noise = (((index * 7919 + 104729) % 613) - 306) * 2
const amount = growth + season + noise
return weekday === 0 || weekday === 6 ? Math.round(amount * 0.7) : amount
}
const DAYS: LineChartPoint[] = Array.from({ length: DAY_COUNT }, (_, index) => ({
date: new Date(FIRST_DAY + index * DAY_MS).toISOString().slice(0, 10),
value: settledOn(index),
}))
function total(points: LineChartPoint[]) {
return points.reduce((sum, point) => sum + point.value, 0)
}
// `skip` leaves out the newest days, for a range whose latest days hold nothing.
function lastDays(count: number, skip = 0) {
return {
points: DAYS.slice(DAY_COUNT - count, DAY_COUNT - skip),
previous: total(DAYS.slice(DAY_COUNT - 2 * count, DAY_COUNT - count)),
}
}
function lastTwelveMonths(skip = 0) {
const months = new Map<string, number>()
for (const point of DAYS.slice(DAY_COUNT - 365, DAY_COUNT - skip)) {
const month = point.date.slice(0, 7)
months.set(month, (months.get(month) ?? 0) + point.value)
}
return {
points: Array.from(months, ([month, value]) => ({ date: `${month}-01`, value })),
previous: total(DAYS.slice(0, 365)),
}
}
const REVENUE_RANGES: LineChartRange[] = [
{ value: "7d", label: "7D", name: "last 7 days", baseline: "vs previous 7 days", ...lastDays(7) },
{ value: "30d", label: "30D", name: "last 30 days", baseline: "vs previous 30 days", ...lastDays(30) },
{ value: "90d", label: "90D", name: "last 90 days", baseline: "vs previous 90 days", ...lastDays(90) },
{
value: "12m",
label: "12M",
name: "last 12 months",
baseline: "vs previous 12 months",
dateFormat: { month: "short", year: "numeric" },
...lastTwelveMonths(),
},
]
function Frame({ children, narrow }: { children: React.ReactNode; narrow?: boolean }) {
// The measure sits one level inside the full-width root, so a canvas that
// sizes the root of a demo cannot stretch the chart.
return (
<div className="w-full">
<div className={cn("mx-auto", narrow ? "max-w-sm" : "max-w-2xl")}>{children}</div>
</div>
)
}
export default function LineChartRangeSwitchDemo() {
return (
<Frame>
<LineChartRangeSwitch
title="Net revenue"
ranges={REVENUE_RANGES}
defaultValue="30d"
formatOptions={USD}
/>
</Frame>
)
}
// Each range arrives on demand, the way a dashboard fetches it from an API.
function RefetchScenario() {
const [value, setValue] = React.useState("30d")
const [loaded, setLoaded] = React.useState(["30d"])
const timer = React.useRef<number | null>(null)
React.useEffect(
() => () => {
if (timer.current !== null) window.clearTimeout(timer.current)
},
[]
)
function handleValueChange(next: string) {
setValue(next)
if (timer.current !== null) window.clearTimeout(timer.current)
timer.current = window.setTimeout(() => {
setLoaded((current) => (current.includes(next) ? current : [...current, next]))
}, 700)
}
return (
<Frame>
<LineChartRangeSwitch
title="Net revenue"
ranges={REVENUE_RANGES.map((range) =>
loaded.includes(range.value)
? range
: { ...range, points: [], previous: undefined }
)}
value={value}
onValueChange={handleValueChange}
loading={!loaded.includes(value)}
formatOptions={USD}
/>
</Frame>
)
}
function LoadingScenario() {
return (
<Frame>
<LineChartRangeSwitch
title="Net revenue"
ranges={REVENUE_RANGES}
defaultValue="90d"
formatOptions={USD}
loading
/>
</Frame>
)
}
// Nothing settled in the newest 7 days, so the longer ranges stop a week early too.
function EmptyScenario() {
const ranges = REVENUE_RANGES.map((range) => {
if (range.value === "7d") return { ...range, points: [], previous: undefined }
if (range.value === "12m") return { ...range, ...lastTwelveMonths(7) }
return { ...range, ...lastDays(range.points.length, 7) }
})
return (
<Frame>
<LineChartRangeSwitch
title="Net revenue"
ranges={ranges}
defaultValue="7d"
formatOptions={USD}
labels={{
empty: "No payouts settled in the last 7 days",
emptyHint: "Settled payouts are plotted here. Pick a longer range to see earlier ones.",
}}
/>
</Frame>
)
}
function ErrorScenario() {
const [failed, setFailed] = React.useState(true)
return (
<Frame>
<LineChartRangeSwitch
title="Net revenue"
ranges={REVENUE_RANGES}
defaultValue="30d"
formatOptions={USD}
error={
failed
? "Revenue for this range could not be loaded. Check your connection, then try again."
: undefined
}
onRetry={() => setFailed(false)}
/>
</Frame>
)
}
function DisabledScenario() {
const ranges = REVENUE_RANGES.map((range) =>
range.value === "90d" || range.value === "12m"
? { ...range, points: [], previous: undefined, disabled: true }
: range
)
return (
<Frame>
<LineChartRangeSwitch
title="Net revenue"
ranges={ranges}
defaultValue="30d"
formatOptions={USD}
/>
<p className="mt-3 text-sm text-muted-foreground">
<span className="font-medium text-foreground">
This workspace has 61 days of history.
</span>{" "}
90D unlocks after 90 days and 12M after a full year.
</p>
</Frame>
)
}
// A level, not a flow: the headline is the latest point and it is compared with
// the count at the end of the period before. 90 days has no earlier count.
function LastValueScenario() {
const members = DAYS.slice(-90).map((point, index) => ({
date: point.date,
value: 1840 + index * 6 + (((index * 31) % 17) - 8),
}))
const countBefore = (days: number) => members[members.length - 1 - days]?.value
return (
<Frame>
<LineChartRangeSwitch
title="Active members"
aggregate="last"
ranges={[
{
value: "7d",
label: "7D",
name: "last 7 days",
baseline: "vs 7 days earlier",
points: members.slice(-7),
previous: countBefore(7),
},
{
value: "30d",
label: "30D",
name: "last 30 days",
baseline: "vs 30 days earlier",
points: members.slice(-30),
previous: countBefore(30),
},
{ value: "90d", label: "90D", name: "last 90 days", points: members },
]}
defaultValue="30d"
/>
</Frame>
)
}
function OverflowScenario() {
const scaled = DAYS.map((point) => ({
date: point.date,
value: point.value * 284000 + 0.37,
}))
const lastScaled = (count: number) => ({
points: scaled.slice(-count),
previous: total(scaled.slice(-2 * count, -count)),
})
return (
<Frame narrow>
<LineChartRangeSwitch
title="Gross merchandise value across every storefront, marketplace and wholesale channel"
defaultValue="24m"
formatOptions={{ style: "currency", currency: "USD" }}
ranges={[
{ value: "7d", label: "7D", name: "last 7 days", ...lastScaled(7) },
{ value: "30d", label: "30D", name: "last 30 days", ...lastScaled(30) },
{ value: "90d", label: "90D", name: "last 90 days", ...lastScaled(90) },
{ value: "6m", label: "6M", name: "last 6 months", ...lastScaled(182) },
{ value: "12m", label: "12M", name: "last 12 months", ...lastScaled(365) },
{
value: "24m",
label: "24M",
name: "last 24 months",
baseline: "vs the 24 months before the current fiscal reporting window",
dateFormat: { month: "short", day: "numeric", year: "numeric" },
points: scaled,
previous: total(scaled) * 0.29,
},
]}
/>
</Frame>
)
}
export const scenarios = {
refetch: RefetchScenario,
loading: LoadingScenario,
empty: EmptyScenario,
error: ErrorScenario,
disabled: DisabledScenario,
"last-value": LastValueScenario,
overflow: OverflowScenario,
}
Props13
- titlerequired
- string
- Name of the metric. It labels the card, the tooltip and the data table.
- rangesrequired
- LineChartRange[]
- value
- string
- `value` of the selected range.
- defaultValue
- string
- onValueChange
- (value: string) => void
- aggregate
- LineChartAggregate = "sum"
- How points become the headline: their total, the latest point or their mean.
- locale
- string = "en-US"
- formatOptions
- Intl.NumberFormatOptions = DEFAULT_FORMAT
- Passed to Intl.NumberFormat for every figure.
- loading
- boolean = false
- Shows skeletons while the selected range is fetched. The switch stays usable.
- error
- string
- What went wrong and what to do, shown in place of the plot.
- onRetry
- () => void
- empty
- React.ReactNode
- Replaces the default message when the selected range has no points.
- labels
- Partial<LineChartRangeSwitchLabels>
- Overrides for the text the component writes itself, including the two sentence builders for the hidden caption and the plot name.
Also accepts every prop of Omit<React.ComponentProps<typeof Card>, "title" | "defaultValue">.
Accessibility
- Pattern
- Chart with text alternative, Radio Group (APG, opens in a new tab)
- Keyboard
Keyboard support for Line Chart with Range Switch Key Effect Tab Moves to the selected range, then to the plot, or to Try again when loading failed Arrow keys on the range Selects the previous or next available range and updates the headline, the delta, the plot and the stat strip Space on the range Selects the focused range Arrow Left, Arrow Right on the plot Moves the tooltip to the previous or next point Enter or Space on Try again Asks for the range again. When the message leaves, focus moves to the selected range - Screen reader
A figure with a hidden caption that states the total, the change and the extremes. The range is a group of native radios in a fieldset, the headline is a polite live region, the plot is an image named by its finding, and a hidden table lists every point.
- Announces: {value}, {Up or Down} {delta} {baseline}
- Announces: Loading {title}, {range}
- Announces: {error}
- Reduced motion
- The line is never animated. The loading skeleton stops pulsing.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies6
- button
- card
- chart
- @hazine/use-controllable-state
- lucide-react
- recharts
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.