Menu

Components

Tracker Chart

A row of blocks that tracks something over time, colored by how each moment went: the uptime of a service, the days a habit was kept.

Introduction

Tracker Chart is a row of blocks, one for each day or hour or check, colored by how it went. It is what you see on a status page for the uptime of a service, and it fits the days a habit was kept or the history of builds as well. It reads as a whole at a glance, and as a single moment when you point at a block.

  • Four statuses from the theme: success, warning, danger and neutral for no data. A block can also take a color of its own, for shades of activity.
  • Pointing at a block, or moving to it with the keyboard, shows a card with its label, its status and a line that says more, and dims the others.
  • It has a caption for the ends and the middle, such as 90 days ago, Today and 99.2% uptime, and an optional legend that counts the blocks of each status.
  • Three heights, three shapes and four spacings. The blocks share the width, so it works with 7 blocks or 90.
  • Colors follow the theme in light and dark. The blocks rise into place one after the other, and not for people who prefer reduced motion.
  • The blocks are buttons, each with a name that reads its label, status and description. The whole row is one place in the tab order: move along it with the arrow keys.

Blocks get thin when there are many and the screen is narrow. Show fewer of them there, such as the last 30 days instead of 90. It is a Client Component, so onItemPress must be defined in a client file. It shows what you give it: working out the status of each day is up to you.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add tailwind-variants tailwind-merge clsx

# pnpm
pnpm add tailwind-variants tailwind-merge clsx

# npm
npm install tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports. It also needs the tracker-chart animation from globals.css.

1. Add the styles

src/types/tracker-chart-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for TrackerChart: a row of blocks, one for each moment, colored by
// what happened then. The class names are written out in full so Tailwind can
// find them.
export const trackerChartStyles = tv({
  slots: {
    root: "flex w-full flex-col gap-2",
    plot: "relative w-full",
    track: "flex w-full items-stretch outline-none",
    block:
      "tracker-chart-in min-w-0 flex-1 cursor-default outline-none transition-[opacity,transform] duration-150 ease-out focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-bg motion-reduce:transition-none",
    caption: "flex items-center justify-between gap-3 text-xs text-muted-fg",
    summary: "font-medium text-fg tabular-nums",
    legend: "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-fg",
    legendItem: "inline-flex items-center gap-1.5",
    legendCount: "font-medium text-fg tabular-nums",
    swatch: "size-2.5 shrink-0 rounded-[3px]",
    tooltip:
      "pointer-events-none absolute bottom-full z-10 mb-2 min-w-40 rounded-lg border bg-card px-3 py-2 text-xs text-card-fg shadow-lg",
    tooltipTitle: "m-0 font-medium",
    tooltipStatus: "mt-1 flex items-center gap-2 text-muted-fg",
    tooltipText: "m-0 mt-1 text-muted-fg",
    empty:
      "flex items-center justify-center rounded-md border border-dashed text-sm text-muted-fg",
  },
  variants: {
    size: {
      sm: { track: "h-6" },
      md: { track: "h-9" },
      lg: { track: "h-12" },
    },
    // The corners of the blocks: square, a little round, or a pill.
    shape: {
      square: { block: "rounded-none" },
      rounded: { block: "rounded-[3px]" },
      pill: { block: "rounded-full" },
    },
    gap: {
      none: { track: "gap-0" },
      sm: { track: "gap-px" },
      md: { track: "gap-0.5" },
      lg: { track: "gap-1" },
    },
  },
  defaultVariants: { size: "md", shape: "rounded", gap: "md" },
});

/** The color of a block for each status, from the theme. */
export const trackerStatusColors = {
  success: "var(--success)",
  warning: "var(--warning)",
  danger: "var(--danger)",
  neutral: "var(--muted)",
} as const;

/** What a status is called when nothing else is said. */
export const trackerStatusLabels = {
  success: "Operational",
  warning: "Degraded",
  danger: "Outage",
  neutral: "No data",
} as const;

2. Add the Tracker Chart file

src/components/ui/tracker-chart/tracker-chart.tsxShow code
"use client";

import { type KeyboardEvent, type ReactNode, useRef, useState } from "react";
import { cn } from "@/lib/cn";
import {
  trackerChartStyles,
  trackerStatusColors,
  trackerStatusLabels,
} from "@/types/tracker-chart-styles";

export type TrackerStatus = keyof typeof trackerStatusColors;

export interface TrackerChartItem {
  /** What this block is: a date, a time, a name. Shown in the tooltip and read by screen readers. */
  label?: string;
  /** What happened: `success`, `warning`, `danger` or `neutral` (no data). Sets the color. Defaults to `success`. */
  status?: TrackerStatus;
  /** Any CSS color, to use instead of the color of the status. */
  color?: string;
  /** A line under the status in the tooltip, such as what went wrong. */
  description?: ReactNode;
}

export interface TrackerChartProps {
  /** One item per block, oldest first: a day, an hour, a check. */
  data: TrackerChartItem[];
  /** How tall the blocks are. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /** The corners of the blocks. Defaults to `rounded`. */
  shape?: "square" | "rounded" | "pill";
  /** The space between blocks. Defaults to `md`. */
  gap?: "none" | "sm" | "md" | "lg";
  /** What each status is called in the tooltip and the legend. Set only the ones you want to change. */
  statusLabels?: Partial<Record<TrackerStatus, string>>;
  /** Under the left end of the blocks, such as "90 days ago". */
  startLabel?: ReactNode;
  /** Under the right end of the blocks, such as "Today". */
  endLabel?: ReactNode;
  /** Under the middle of the blocks, such as "99.9% uptime". */
  summary?: ReactNode;
  /** A line under the blocks that counts how many there are of each status. Defaults to `false`. */
  showLegend?: boolean;
  /** The card that shows what a block is when the pointer or the keyboard is on it. Defaults to `true`. */
  showTooltip?: boolean;
  /** Called when a block is pressed, which makes the blocks buttons that do something. */
  onItemPress?: (item: TrackerChartItem, index: number) => void;
  /** What it says with no items. Defaults to "No data". */
  emptyText?: string;
  /** Names the chart for screen readers. Each block has a name of its own. */
  "aria-label": string;
  className?: string;
}

const STATUSES = ["success", "warning", "danger", "neutral"] as const;

/**
 * A row of blocks that tracks something over time, one block for each day or
 * hour or check, colored by how it went: the uptime of a service on a status
 * page, the days a habit was kept, a build history. It reads as a whole at a
 * glance, and as a single moment when you point at a block.
 *
 * It is a client component: the blocks are buttons with one place in the tab
 * order, moved with the arrow keys, Home and End, and the tooltip follows
 * the pointer and the keyboard alike. Colors follow the theme in light and
 * dark, and every block has a name that screen readers read.
 *
 * With many blocks on a narrow screen each gets thin. Show fewer of them there,
 * such as the last 30 days instead of 90.
 *
 * @example
 * <TrackerChart
 *   aria-label="API uptime, last 30 days"
 *   data={[
 *     { label: "Mar 1", status: "success" },
 *     { label: "Mar 2", status: "danger", description: "Database down for 43 minutes" },
 *   ]}
 *   startLabel="30 days ago"
 *   endLabel="Today"
 * />
 */
export function TrackerChart({
  data,
  size,
  shape,
  gap,
  statusLabels,
  startLabel,
  endLabel,
  summary,
  showLegend = false,
  showTooltip = true,
  onItemPress,
  emptyText = "No data",
  "aria-label": ariaLabel,
  className,
}: TrackerChartProps) {
  const styles = trackerChartStyles({ size, shape, gap });
  const plot = useRef<HTMLDivElement>(null);
  const track = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState<number | null>(null);
  const [tabStop, setTabStop] = useState(0);
  const [tip, setTip] = useState<{
    left: number;
    align: "start" | "center" | "end";
  } | null>(null);
  const names = { ...trackerStatusLabels, ...statusLabels };

  if (data.length === 0) {
    return (
      <div className={cn(styles.empty(), "h-20", className)}>{emptyText}</div>
    );
  }

  const statusOf = (item: TrackerChartItem) => item.status ?? "success";

  function show(index: number) {
    const button = track.current?.children[index] as HTMLElement | undefined;
    const box = plot.current;
    if (!button || !box) return;
    const center = button.offsetLeft + button.offsetWidth / 2;
    const ratio = center / (box.clientWidth || 1);
    setActive(index);
    setTip({
      left: center,
      align: ratio < 0.2 ? "start" : ratio > 0.8 ? "end" : "center",
    });
  }

  function hide() {
    setActive(null);
    setTip(null);
  }

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    const last = data.length - 1;
    const keys: Record<string, number> = {
      ArrowRight: Math.min(tabStop + 1, last),
      ArrowLeft: Math.max(tabStop - 1, 0),
      Home: 0,
      End: last,
    };
    const next = keys[event.key];
    if (next === undefined) return;
    event.preventDefault();
    setTabStop(next);
    (track.current?.children[next] as HTMLElement | undefined)?.focus();
  }

  const counts = STATUSES.map((status) => ({
    status,
    count: data.filter((item) => statusOf(item) === status).length,
  })).filter((entry) => entry.count > 0);
  const current = active === null ? null : data[active];
  const currentStatus = current ? statusOf(current) : null;

  return (
    <div className={cn(styles.root(), className)}>
      <div ref={plot} className={styles.plot()}>
        {/* biome-ignore lint/a11y/useSemanticElements: a group of buttons, moved with the arrow keys */}
        <div
          ref={track}
          role="group"
          aria-label={ariaLabel}
          className={styles.track()}
          onKeyDown={onKeyDown}
          onPointerLeave={hide}
        >
          {data.map((item, i) => {
            const status = statusOf(item);
            const name = [
              item.label,
              names[status],
              typeof item.description === "string" ? item.description : null,
            ]
              .filter(Boolean)
              .join(": ");
            return (
              <button
                // biome-ignore lint/suspicious/noArrayIndexKey: the blocks are the positions
                key={i}
                type="button"
                aria-label={name}
                tabIndex={i === tabStop ? 0 : -1}
                className={styles.block()}
                style={{
                  background: item.color ?? trackerStatusColors[status],
                  animationDelay: `${Math.min(i * 8, 400)}ms`,
                  opacity: active !== null && active !== i ? 0.55 : 1,
                  cursor: onItemPress ? "pointer" : "default",
                }}
                onPointerEnter={() => show(i)}
                onFocus={() => {
                  setTabStop(i);
                  show(i);
                }}
                onBlur={hide}
                onClick={() => onItemPress?.(item, i)}
              />
            );
          })}
        </div>

        {showTooltip && current && currentStatus && tip ? (
          <div
            className={styles.tooltip()}
            style={{
              left: tip.left,
              transform: `translateX(${tip.align === "start" ? "-12px" : tip.align === "end" ? "calc(-100% + 12px)" : "-50%"})`,
            }}
          >
            {current.label ? (
              <p className={styles.tooltipTitle()}>{current.label}</p>
            ) : null}
            <p className={styles.tooltipStatus()}>
              <span
                aria-hidden="true"
                className={styles.swatch()}
                style={{
                  background:
                    current.color ?? trackerStatusColors[currentStatus],
                }}
              />
              {names[currentStatus]}
            </p>
            {current.description ? (
              <p className={styles.tooltipText()}>{current.description}</p>
            ) : null}
          </div>
        ) : null}
      </div>

      {startLabel || endLabel || summary ? (
        <div className={styles.caption()}>
          <span>{startLabel}</span>
          {summary ? <span className={styles.summary()}>{summary}</span> : null}
          <span>{endLabel}</span>
        </div>
      ) : null}

      {showLegend ? (
        <div className={styles.legend()}>
          {counts.map(({ status, count }) => (
            <span key={status} className={styles.legendItem()}>
              <span
                aria-hidden="true"
                className={styles.swatch()}
                style={{ background: trackerStatusColors[status] }}
              />
              {names[status]}
              <span className={styles.legendCount()}>{count}</span>
            </span>
          ))}
        </div>
      ) : null}
    </div>
  );
}

3. Use it

import { TrackerChart } from "@/components/ui/tracker-chart/tracker-chart";

Anatomy

A row of blocks, with a tooltip over it, a caption and a legend under it.

<TrackerChart
  aria-label="API uptime, last 90 days"
  data={[
    { label: "Mar 1", status: "success" },
    { label: "Mar 2", status: "danger", description: "Database down for 43 minutes" },
    ...
  ]}
  startLabel="90 days ago"
  endLabel="Today"
  summary="99.2% uptime"
/>
PartRendered asNotes
BlockbuttonOne per item, colored by its status. It has a name for screen readers, and one place in the tab order for the whole row.
TooltipdivA card with the label, the status and the description of the block under the pointer or the keyboard.
CaptiondivThe start label, the summary and the end label under the blocks.
LegendspanThe statuses in use, with how many blocks each has. Off unless showLegend.

Examples

Usage

Point at a block to see its day, or move along the blocks with the arrow keys.

90 days ago98.9% uptimeToday

The data

One item for each block, oldest first. A block with no status is a success.

const uptime = [
  { label: "Mar 1", status: "success", description: "No incidents" },
  { label: "Mar 2", status: "danger", description: "Database down for 43 minutes" },
  { label: "Mar 3", status: "warning", description: "Slow responses" },
  { label: "Mar 4", status: "neutral", description: "The monitor was paused" },
];

Sizes

Small, medium and large heights.

Shapes and spacing

Square, rounded or pill blocks, and the space between them from none to large.

Colors

A block takes the color of its status. Give color to use another, such as shades of one color for how much was done.

60 days agoToday

Legend

showLegend counts the blocks of each status in use.

90 days agoToday
Operational84Degraded3Outage2No data1

Status names

statusLabels changes what each status is called, in the tooltip, the legend and the names for screen readers.

Up56Slow2Down1Paused1

Pressing a block

With onItemPress the blocks do something when pressed, such as open the report of that day.

30 days agoToday

Press a block to open its report.

Few blocks

With a few blocks they grow wide. A large size and a wide gap suit a week.

7 days agoToday

No data

With no items it says so.

No checks yet

Keyboard

The row is one place in the tab order, so tabbing through a page does not stop at every block.

KeyAction
TabMoves to the row, on the block you were last on, and shows its card.
Arrow Right, Arrow LeftMoves to the next or the previous block.
Home, EndMoves to the first or the last block.
Enter, SpacePresses the block, with onItemPress.

Component API

TrackerChart takes the props below, and each item of data takes the second table.

PropTypeDefault
dataTrackerChartItem[]-
aria-labelstring-
size"sm" | "md" | "lg""md"
shape"square" | "rounded" | "pill""rounded"
gap"none" | "sm" | "md" | "lg""md"
statusLabelsPartial<Record<status, string>>Operational, Degraded, Outage, No data
startLabelReactNode-
endLabelReactNode-
summaryReactNode-
showLegendbooleanfalse
showTooltipbooleantrue
onItemPress(item, index) => void-
emptyTextstring"No data"
classNamestring-

TrackerChartItem

PropTypeDefault
labelstring-
status"success" | "warning" | "danger" | "neutral""success"
colorstringthe color of the status
descriptionReactNode-