GaugeFree

A meter with bands, a target and honest out-of-range handling. Plain SVG: no chart engine.

npx shadcn@latest add https://beautifulcharts.dev/r/gauge.json

Usage

A complete client module. Install the item first, then paste it into your app.

"use client";

import { Gauge } from "@/components/beautiful-charts/themes/instrument/gauge";

// Out-of-range values pin to the end of the arc and keep their true number in the readout.
export function Uptime() {
  return (
    <Gauge
      title="Uptime, last 30 days"
      value={99.62}
      min={98}
      max={100}
      target={99.5}
      bands={[
        { from: 98, to: 99, tone: "bad", label: "below target" },
        { from: 99, to: 99.5, tone: "warn", label: "at risk" },
        { from: 99.5, to: 100, tone: "good", label: "healthy" },
      ]}
      valueFormatter={(v) => `${v.toFixed(2)}%`}
    />
  );
}

Props

  • value*

    number | null

    The reading. A value outside min–max pins to the end of the scale and keeps its true number.

  • min

    number

    Start of the scale (default 0).

  • max

    number

    End of the scale (default 100).

  • bands

    GaugeBand[]

    Coloured ranges along the scale, e.g. good / warn / bad.

  • target

    number | null

    A tick across the scale.

  • variant

    "semi" | "arc"

    "semi" is a half circle; "arc" a 240° arc.

Sourcecomponents/beautiful-charts/themes/instrument/gauge.tsx

Show the source (76 lines)
"use client";

import type { ReactNode } from "react";
import type { Density } from "../../core/contracts";
import { useGaugeModel, type GaugeProps } from "../../core/gauge";
import { ChartState } from "../../core/chart";
import { chartState } from "../../core/state";
import { sectorPath } from "./arcs";
import { InstrumentFrame } from "./frame";

export type InstrumentGaugeProps = GaugeProps & {
  /** Small label above the title. */
  eyebrow?: ReactNode | undefined;
  /** A line or action at the bottom of the card. */
  footer?: ReactNode | undefined;
  /** Card title. A string also names the stat for screen readers. */
  title?: ReactNode | undefined;
  /** A line under the title. */
  description?: ReactNode | undefined;
  /** A word under the number, e.g. "uptime". */
  unit?: ReactNode | undefined;
  /** Show the loading state. */
  loading?: boolean | undefined;
  /** An error message; shows the error state. */
  error?: string | null | undefined;
  /** "comfortable" (default) or "compact". */
  density?: Density | undefined;
  /** Classes on the card. */
  className?: string | undefined;
  /** "theme" (default) or "shadcn" to use your --chart-N colours. */
  palette?: "theme" | "shadcn" | undefined;
};

/** Sample props used when you install the gauge; replace them with your own. */
export const gaugeSample = { value: 99.2, min: 98, max: 100, bands: [{ from: 98, to: 99, tone: "bad" as const, label: "below target" }, { from: 99, to: 99.5, tone: "warn" as const, label: "at risk" }, { from: 99.5, to: 100, tone: "good" as const, label: "healthy" }], target: 99.5 };

/**
 * Gauge, Instrument theme. Plain SVG, no chart engine. It's a meter, not an interactive chart: role="meter"
 * with the true value, and no tab stop. Over- or under-range values are capped in the drawing and said in words.
 */
export function Gauge(props: InstrumentGaugeProps) {
  const m = useGaugeModel(props);
  const state = chartState({ loading: props.loading, error: props.error ?? m.invalid, hasData: m.value !== null });
  const W = 240, semi = m.variant === "semi";
  // Angles run clockwise from 3 o'clock. Semi: 9 o'clock over the top to 3. Arc: 240°, open at the bottom.
  const sweep = semi ? Math.PI : (Math.PI * 4) / 3;
  const a0 = semi ? Math.PI : Math.PI * (5 / 6), a = (t: number) => a0 + sweep * t;
  const cx = W / 2, r1 = W / 2 - 14, r0 = r1 - 16, cy = semi ? r1 + 14 : r1 + 16, H = semi ? cy + 34 : cy + r1 * 0.62 + 16;
  // The gauge renders on the server too. Trig results can differ in the last digit between Node and the
  // browser, so every coordinate is rounded; otherwise hydration would find mismatched attributes.
  const round = (n: number) => Math.round(n * 100) / 100;
  const at = (r: number, angle: number) => [round(cx + r * Math.cos(angle)), round(cy + r * Math.sin(angle))] as const;
  return (
    <InstrumentFrame palette={props.palette} state={state} emptyState={<ChartState state="empty" message="No value yet."><span data-slot="kpi-empty" aria-hidden="true">—</span></ChartState>} series={[]} density={props.density} className={props.className} label={typeof props.title === "string" ? `${props.title}: ${m.valueText}` : m.valueText}
      eyebrow={props.eyebrow} title={props.title} description={props.description} footer={props.footer} legend={false} legendItems={[]} onToggle={() => {}} table={false} error={props.error ?? m.invalid} k={m.k}>
      <div data-slot="gauge" role="meter" aria-valuemin={m.min} aria-valuemax={m.max} aria-valuenow={m.value ?? undefined} aria-valuetext={m.valueText} aria-label={typeof props.title === "string" ? props.title : "Gauge"}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxWidth: 360, display: "block", margin: "0 auto" }} aria-hidden="true">
          <path className={"bc-track"} d={sectorPath(cx, cy, r0, r1, a(0), a(1), 6)} />
          {m.bands.map((band, i) => <path key={i} className={"bc-gauge-band"} data-tone={band.tone} d={sectorPath(cx, cy, r1 + 3, r1 + 6, a(Math.max(0, m.t(band.from))), a(Math.min(1, m.t(band.to))), 0)} />)}
          {m.fraction !== null && m.fraction > 0.002 ? <g className={"bc-mark bc-segment"} style={{ color: `var(--bc-gauge-${m.band?.tone ?? "neutral"}, var(--bc-palette-1))` }}>
            <path className={"bc-body bc-ring-in"} d={sectorPath(cx, cy, r0, r1, a(0), a(m.fraction), 6)} style={{ transformBox: "view-box", transformOrigin: `${cx}px ${cy}px`, fill: "currentColor", fillOpacity: "var(--i-body-active)" }} />
            <path className={"bc-edge bc-ring-in"} d={sectorPath(cx, cy, r1 - 3, r1, a(0), a(m.fraction), 1.5)} style={{ transformBox: "view-box", transformOrigin: `${cx}px ${cy}px` }} />
          </g> : null}
          {/* Out of range: a dot just past the end the value went beyond; the note below gives the true value. */}
          {m.outside ? <circle className={"bc-gauge-outside"} cx={at(r1 + 9, a(m.outside === "over" ? 1 : 0))[0]} cy={at(r1 + 9, a(m.outside === "over" ? 1 : 0))[1]} r={3.5} /> : null}
          {m.target !== null ? <path className={"bc-goal"} d={`M${at(r0 - 3, a(Math.max(0, Math.min(1, m.t(m.target))))).join(",")}L${at(r1 + 3, a(Math.max(0, Math.min(1, m.t(m.target))))).join(",")}`} /> : null}
          {m.ticks.map((tick) => { const [x, y] = at(r0 - 12, a(m.t(tick))); return <text key={tick} className={"bc-axis-text"} x={x} y={y + 3.5} textAnchor="middle">{m.f.compact(tick, 2)}</text>; })}
          <text className={"bc-gauge-value"} x={cx} y={semi ? cy - 6 : cy + 8} textAnchor="middle">{m.format(m.value)}</text>
          {props.unit || m.band?.label ? <text className={"bc-donut-unit"} x={cx} y={semi ? cy + 14 : cy + 28} textAnchor="middle">{[typeof props.unit === "string" ? props.unit : "", m.band?.label ?? ""].filter(Boolean).join(" · ")}</text> : null}
        </svg>
        {m.outside ? <p data-slot="partial-note">{m.outside === "over" ? `The value, ${m.format(m.value)}, is over the ${m.format(m.max)} maximum; the gauge shows it full.` : `The value, ${m.format(m.value)}, is under the ${m.format(m.min)} minimum; the gauge shows it empty.`}</p> : null}
      </div>
    </InstrumentFrame>
  );
}

Details

The other 12 gauge props
  • valueFormatter

    (value: number) => string

    Formats the reading and scale labels.

  • motion

    MotionPreference

    "full" (default), "subtle" or "off". Reduced-motion settings always win.

  • eyebrow

    ReactNode

    Small label above the title.

  • footer

    ReactNode

    A line or action at the bottom of the card.

  • title

    ReactNode

    Card title. A string also names the stat for screen readers.

  • description

    ReactNode

    A line under the title.

  • unit

    ReactNode

    A word under the number, e.g. "uptime".

  • loading

    boolean

    Show the loading state.

  • error

    string | null

    An error message; shows the error state.

  • density

    Density

    "comfortable" (default) or "compact".

  • className

    string

    Classes on the card.

  • palette

    "theme" | "shadcn"

    "theme" (default) or "shadcn" to use your --chart-N colours.

Props every chart shares (2): locale, timeZone
  • locale

    string

    BCP 47 locale. Defaults to "en-US" so server and client render the same text.

  • timeZone

    string

    IANA time zone for dates. Defaults to "UTC" so server and client agree.

Pointer
Not interactive.
Keyboard
Not focusable: there's nothing to move between.
Screen readers
A meter (role="meter") with its range, value and band read as text, for example "99.20%, healthy".
Motion
The value rolls in and the marker settles on it. With reduced motion it appears settled at once.