Uptime strip

A service health row: status dot, name and uptime percentage over thin day bars coloured operational, degraded, outage or maintenance. Bars show 90, 60 or 30 days depending on the container width. Hover, tap or arrow keys raise the focused bar and its neighbours and open a card with the date, uptime and incidents. Several services stack into a status block with a computed summary, a 30/60/90 range switch that tweens the percentage, a legend, skeleton loading and a compact mode. Outage and maintenance bars carry a pattern so state never relies on colour alone.

DashboardsComponentTailwind v4

Source

"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

export type UptimeIncident = { title: string; minutes: number };
export type UptimeDay = {
  /** ISO date, e.g. "2026-10-12". */
  date: string;
  /** Percentage 0–100, or null when there is no data for the day. */
  uptime: number | null;
  /** Planned work: drawn in the maintenance colour whatever the uptime. */
  maintenance?: boolean;
  incidents?: UptimeIncident[];
};
export type UptimeService = { name: string; days: UptimeDay[] };
export type UptimeRange = 30 | 60 | 90;
export type UptimeThresholds = { degraded: number; down: number };
export type DayState = "operational" | "degraded" | "outage" | "maintenance" | "none";

const DEFAULT_THRESHOLDS: UptimeThresholds = { degraded: 99.5, down: 97 };
const RANGES: UptimeRange[] = [30, 60, 90];

const STATE_LABEL: Record<DayState, string> = {
  operational: "Operational",
  degraded: "Degraded",
  outage: "Outage",
  maintenance: "Maintenance",
  none: "No data",
};

/* Status colours are fixed on purpose: green, amber and red carry meaning that should not change with a theme.
   Maintenance follows the theme's third chart colour. */
const STATE_BAR: Record<DayState, string> = {
  operational: "bg-emerald-500 dark:bg-emerald-400",
  degraded: "bg-amber-400 dark:bg-amber-300",
  outage: "bg-red-500 dark:bg-red-400",
  maintenance: "bg-[var(--chart-3)]",
  none: "bg-muted",
};
const STATE_TEXT: Record<DayState, string> = {
  operational: "text-emerald-700 dark:text-emerald-300",
  degraded: "text-amber-700 dark:text-amber-300",
  outage: "text-red-600 dark:text-red-400",
  maintenance: "text-foreground",
  none: "text-muted-foreground",
};

/* Outage bars carry a notch pattern and maintenance bars a band, so states never rely on colour alone. */
const OUTAGE_NOTCH =
  "repeating-linear-gradient(135deg, transparent 0 3px, color-mix(in oklab, black 32%, transparent) 3px 5px)";
const MAINTENANCE_BAND =
  "repeating-linear-gradient(0deg, transparent 0 4px, color-mix(in oklab, white 35%, transparent) 4px 6px)";

export function dayState(day: UptimeDay | undefined, thresholds: UptimeThresholds = DEFAULT_THRESHOLDS): DayState {
  if (!day) return "none";
  if (day.maintenance) return "maintenance";
  if (day.uptime == null) return "none";
  if (day.uptime < thresholds.down) return "outage";
  if (day.uptime < thresholds.degraded) return "degraded";
  return "operational";
}

export function averageUptime(days: UptimeDay[]) {
  const known = days.filter((day) => day.uptime != null);
  if (!known.length) return null;
  return known.reduce((sum, day) => sum + (day.uptime as number), 0) / known.length;
}

const dateFormat = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });
const longDateFormat = new Intl.DateTimeFormat("en-GB", { weekday: "short", day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
const parseDate = (iso: string) => new Date(`${iso.slice(0, 10)}T00:00:00Z`);
const pct = (value: number | null) => (value == null ? "—" : `${value.toFixed(value >= 99.995 ? 0 : 2)}%`);
const duration = (minutes: number) => (minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60 ? `${minutes % 60} min` : ""}`.trim());

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}

/** Next animation frame, with a timer fallback for pages that are not painting (background tabs, headless capture). */
function nextFrame(callback: (now: number) => void) {
  let done = false;
  const run = () => {
    if (done) return;
    done = true;
    cancelAnimationFrame(frame);
    clearTimeout(timer);
    callback(performance.now());
  };
  const frame = requestAnimationFrame(run);
  const timer = setTimeout(run, 34);
  return () => {
    done = true;
    cancelAnimationFrame(frame);
    clearTimeout(timer);
  };
}

/** Tweens a number towards its target over a short ease-out, or jumps when motion is reduced. */
function useCountTween(target: number | null, ms = 450) {
  const [value, setValue] = React.useState(target);
  const fromRef = React.useRef(target);
  React.useEffect(() => {
    if (target == null || fromRef.current == null || prefersReducedMotion()) {
      fromRef.current = target;
      setValue(target);
      return;
    }
    const from = fromRef.current;
    const start = performance.now();
    let cancel = () => {};
    const step = (now: number) => {
      const t = Math.min(1, (now - start) / ms);
      const eased = 1 - (1 - t) ** 3;
      const next = from + (target - from) * eased;
      fromRef.current = next;
      setValue(next);
      if (t < 1) cancel = nextFrame(step);
    };
    cancel = nextFrame(step);
    return () => cancel();
  }, [target, ms]);
  return value;
}

/* Bars older than 30 or 60 days only appear when the container is wide enough. */
function ageClass(age: number) {
  if (age >= 60) return "hidden @2xl:block";
  if (age >= 30) return "hidden @lg:block";
  return "block";
}

export type UptimeStripProps = {
  service: UptimeService;
  range?: UptimeRange;
  thresholds?: UptimeThresholds;
  /** Hides the header and axis: just the bars. */
  compact?: boolean;
  loading?: boolean;
  /** Opens the tooltip for this date on mount (for linking straight to an incident). */
  defaultOpenDate?: string;
  className?: string;
};

export function UptimeStrip({
  service,
  range = 90,
  thresholds = DEFAULT_THRESHOLDS,
  compact = false,
  loading = false,
  defaultOpenDate,
  className,
}: UptimeStripProps) {
  const uid = React.useId();
  const tooltipId = `${uid}-tip`;
  const days = React.useMemo(() => {
    const sorted = [...service.days].sort((a, b) => a.date.localeCompare(b.date));
    return sorted.slice(-range);
  }, [service.days, range]);

  const [cursor, setCursor] = React.useState(() => {
    const index = defaultOpenDate ? days.findIndex((day) => day.date === defaultOpenDate) : -1;
    return index >= 0 ? index : days.length - 1;
  });
  const [open, setOpen] = React.useState(() => Boolean(defaultOpenDate && days.some((day) => day.date === defaultOpenDate)));
  const [tipLeft, setTipLeft] = React.useState<number | null>(null);
  const rowRef = React.useRef<HTMLDivElement>(null);
  const barRefs = React.useRef<(HTMLDivElement | null)[]>([]);
  const wrapRef = React.useRef<HTMLDivElement>(null);

  const safeCursor = Math.min(Math.max(cursor, 0), days.length - 1);
  React.useEffect(() => setCursor((index) => Math.min(index, days.length - 1)), [days.length]);

  const average = useCountTween(averageUptime(days));
  const current = dayState(days[days.length - 1], thresholds);

  // Place the tooltip over the active bar, kept inside the strip.
  React.useLayoutEffect(() => {
    if (!open) return;
    const bar = barRefs.current[safeCursor];
    const wrap = wrapRef.current;
    if (!bar || !wrap || bar.offsetParent === null) return setTipLeft(null);
    const barBox = bar.getBoundingClientRect();
    const wrapBox = wrap.getBoundingClientRect();
    setTipLeft(barBox.left - wrapBox.left + barBox.width / 2);
  }, [open, safeCursor, days]);

  const visible = (index: number) => {
    const bar = barRefs.current[index];
    return Boolean(bar && bar.offsetParent !== null);
  };

  const moveTo = (index: number, direction: 1 | -1) => {
    let next = index;
    while (next >= 0 && next < days.length && !visible(next)) next += direction;
    if (next < 0 || next >= days.length) return;
    setCursor(next);
    setOpen(true);
    barRefs.current[next]?.focus();
  };

  const firstVisible = () => {
    for (let index = 0; index < days.length; index++) if (visible(index)) return index;
    return 0;
  };

  const onKeyDown = (event: React.KeyboardEvent) => {
    const keys: Record<string, () => void> = {
      ArrowRight: () => moveTo(safeCursor + 1, 1),
      ArrowLeft: () => moveTo(safeCursor - 1, -1),
      Home: () => moveTo(firstVisible(), 1),
      End: () => moveTo(days.length - 1, -1),
      Escape: () => setOpen(false),
    };
    const action = keys[event.key];
    if (!action) return;
    event.preventDefault();
    action();
  };

  const active = days[safeCursor];
  const activeState = dayState(active, thresholds);

  return (
    <div className={cn("@container min-w-0", className)}>
      {!compact && (
        <div className="mb-2 flex items-center gap-4 [&>*:last-child]:ml-auto">
          <div className="flex min-w-0 items-center gap-2">
            <StatusDot state={loading ? "none" : current} />
            <span className="truncate text-sm font-medium text-foreground">{service.name}</span>
            <span className={cn("hidden text-xs @sm:inline", STATE_TEXT[current])}>{loading ? "" : STATE_LABEL[current]}</span>
          </div>
          <span className="shrink-0 text-sm font-semibold tabular-nums text-foreground">
            {loading ? <span className="inline-block h-4 w-14 rounded bg-muted motion-safe:animate-pulse" /> : pct(average)}
            <span className="sr-only"> uptime over {range} days</span>
          </span>
        </div>
      )}

      <div ref={wrapRef} className="relative">
        {loading ? (
          <div aria-busy="true" aria-label={`Loading ${service.name} uptime`} className="flex h-8 items-end gap-[2px]">
            {Array.from({ length: range }, (_, index) => (
              <div
                key={index}
                className={cn("h-full flex-1 rounded-[2px] bg-muted motion-safe:animate-pulse", ageClass(range - 1 - index))}
                style={{ animationDelay: `${(index % 12) * 60}ms` }}
              />
            ))}
          </div>
        ) : (
          <div
            ref={rowRef}
            role="grid"
            aria-label={`${service.name}, daily uptime for the last ${range} days`}
            aria-readonly="true"
            onKeyDown={onKeyDown}
            onMouseLeave={() => setOpen(false)}
            onBlur={(event) => {
              if (!event.currentTarget.contains(event.relatedTarget as Node)) setOpen(false);
            }}
          >
            <div role="row" className="flex h-8 items-end gap-[2px]">
              {days.map((day, index) => {
                const state = dayState(day, thresholds);
                const age = days.length - 1 - index;
                const distance = open ? Math.abs(index - safeCursor) : 9;
                const scale = distance === 0 ? 1.15 : distance === 1 ? 1.07 : 1;
                const incidents = day.incidents?.length ?? 0;
                return (
                  <div
                    key={day.date}
                    ref={(node) => {
                      barRefs.current[index] = node;
                    }}
                    role="gridcell"
                    tabIndex={index === safeCursor ? 0 : -1}
                    aria-selected={open && index === safeCursor ? true : undefined}
                    aria-describedby={open && index === safeCursor ? tooltipId : undefined}
                    aria-label={`${dateFormat.format(parseDate(day.date))}, ${day.uptime == null ? "no data" : `${pct(day.uptime)} uptime`}${
                      state === "maintenance" ? ", maintenance" : ""
                    }${incidents ? `, ${incidents} incident${incidents > 1 ? "s" : ""}` : ""}`}
                    onMouseEnter={() => {
                      setCursor(index);
                      setOpen(true);
                    }}
                    onFocus={() => {
                      setCursor(index);
                      setOpen(true);
                    }}
                    onClick={() => {
                      setCursor(index);
                      setOpen(true);
                    }}
                    className={cn(
                      "relative h-full min-w-0 flex-1 origin-bottom cursor-default rounded-[2px] outline-none",
                      "motion-safe:transition-transform motion-safe:duration-150 motion-safe:ease-out",
                      "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
                      STATE_BAR[state],
                      ageClass(age),
                    )}
                    style={{
                      transform: `scaleY(${scale})`,
                      backgroundImage: state === "outage" ? OUTAGE_NOTCH : state === "maintenance" ? MAINTENANCE_BAND : undefined,
                    }}
                  />
                );
              })}
            </div>
          </div>
        )}

        {!loading && open && active && tipLeft != null && (
          <div
            id={tooltipId}
            role="tooltip"
            className="pointer-events-none absolute top-full z-20 mt-3 w-56 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg shadow-black/5 dark:shadow-black/40"
            style={{
              left: `clamp(0px, ${tipLeft}px - 7rem, calc(100% - 14rem))`,
            }}
          >
            <div className="flex items-center justify-between gap-2">
              <span className="text-xs font-medium">{longDateFormat.format(parseDate(active.date))}</span>
              <span className={cn("flex items-center gap-1.5 text-xs", STATE_TEXT[activeState])}>
                <StatusDot state={activeState} small />
                {STATE_LABEL[activeState]}
              </span>
            </div>
            <div className="mt-1.5 text-lg font-semibold tabular-nums leading-none">
              {pct(active.uptime)}
              <span className="ml-1 text-xs font-normal text-muted-foreground">uptime</span>
            </div>
            {active.incidents?.length ? (
              <ul className="mt-2.5 space-y-1.5 border-t border-border pt-2.5">
                {active.incidents.map((incident) => (
                  <li key={incident.title} className="flex items-start justify-between gap-3 text-xs">
                    <span className="min-w-0 text-foreground">{incident.title}</span>
                    <span className="shrink-0 text-muted-foreground tabular-nums">{duration(incident.minutes)}</span>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="mt-2 text-xs text-muted-foreground">No incidents recorded</p>
            )}
          </div>
        )}
      </div>

      {!compact && (
        <div aria-hidden="true" className="mt-2 flex items-center justify-between text-[11px] text-muted-foreground">
          <span>
            <span className={range > 60 ? "hidden @2xl:inline" : range > 30 ? "hidden @lg:inline" : "inline"}>{range} days ago</span>
            {range > 30 && (
              <span className={range > 60 ? "inline @lg:hidden" : "inline @lg:hidden"}>30 days ago</span>
            )}
            {range > 60 && <span className="hidden @lg:inline @2xl:hidden">60 days ago</span>}
          </span>
          <span className="mx-3 h-px flex-1 bg-border" />
          <span>Today</span>
        </div>
      )}
    </div>
  );
}

function StatusDot({ state, small = false }: { state: DayState; small?: boolean }) {
  return (
    <span aria-hidden="true" className={cn("relative inline-flex shrink-0", small ? "size-1.5" : "size-2.5")}>
      {state === "outage" && !small && (
        <span className="absolute inset-0 rounded-full bg-red-500/60 motion-safe:animate-ping dark:bg-red-400/60" />
      )}
      <span className={cn("relative inline-flex size-full rounded-full", STATE_BAR[state])} />
    </span>
  );
}

export type UptimeStatusProps = {
  services: UptimeService[];
  range?: UptimeRange;
  defaultRange?: UptimeRange;
  onRangeChange?: (range: UptimeRange) => void;
  thresholds?: UptimeThresholds;
  compact?: boolean;
  loading?: boolean;
  title?: string;
  /** Per service name, a date whose tooltip opens on mount. */
  defaultOpenDates?: Record<string, string>;
  className?: string;
};

const SUMMARY: Record<Exclude<DayState, "none"> | "none", { text: string; tone: DayState }> = {
  operational: { text: "All systems operational", tone: "operational" },
  degraded: { text: "Degraded performance", tone: "degraded" },
  outage: { text: "Partial outage", tone: "outage" },
  maintenance: { text: "Scheduled maintenance", tone: "maintenance" },
  none: { text: "Status unknown", tone: "none" },
};

/** A status-page block: several services stacked under a grouped summary, with a shared range switch and legend. */
export function UptimeStatus({
  services,
  range: rangeProp,
  defaultRange = 90,
  onRangeChange,
  thresholds = DEFAULT_THRESHOLDS,
  compact = false,
  loading = false,
  title = "System status",
  defaultOpenDates,
  className,
}: UptimeStatusProps) {
  const [innerRange, setInnerRange] = React.useState<UptimeRange>(defaultRange);
  const range = rangeProp ?? innerRange;
  const setRange = (next: UptimeRange) => {
    if (rangeProp == null) setInnerRange(next);
    onRangeChange?.(next);
  };

  const states = services.map((service) => {
    const days = [...service.days].sort((a, b) => a.date.localeCompare(b.date));
    return dayState(days[days.length - 1], thresholds);
  });
  const worst: DayState = states.includes("outage")
    ? "outage"
    : states.includes("degraded")
      ? "degraded"
      : states.includes("maintenance")
        ? "maintenance"
        : states.length && states.every((state) => state === "operational")
          ? "operational"
          : "none";
  const affected = states.filter((state) => state !== "operational").length;
  const summary = SUMMARY[worst];

  const radios = React.useRef<(HTMLButtonElement | null)[]>([]);
  const onRadioKey = (event: React.KeyboardEvent, index: number) => {
    const delta = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
    if (!delta) return;
    event.preventDefault();
    const next = (index + delta + RANGES.length) % RANGES.length;
    setRange(RANGES[next]);
    radios.current[next]?.focus();
  };

  return (
    <section aria-label={title} className={cn("@container rounded-xl border border-border bg-card text-card-foreground", className)}>
      <header className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3.5 @md:px-5">
        <div className="flex min-w-0 items-center gap-2.5" role="status">
          <StatusDot state={loading ? "none" : summary.tone} />
          <div className="min-w-0">
            <p className="text-sm font-semibold text-foreground">{loading ? "Checking status…" : summary.text}</p>
            {!loading && affected > 0 && (
              <p className="text-xs text-muted-foreground">
                {affected} of {services.length} services affected
              </p>
            )}
          </div>
        </div>
        <div role="radiogroup" aria-label="Range" className="inline-flex rounded-lg bg-muted p-0.5">
          {RANGES.map((option, index) => (
            <button
              key={option}
              ref={(node) => {
                radios.current[index] = node;
              }}
              type="button"
              role="radio"
              aria-checked={range === option}
              tabIndex={range === option ? 0 : -1}
              onClick={() => setRange(option)}
              onKeyDown={(event) => onRadioKey(event, index)}
              className={cn(
                "rounded-md px-2.5 py-1 text-xs font-medium tabular-nums outline-none motion-safe:transition-colors",
                "focus-visible:ring-2 focus-visible:ring-ring",
                range === option ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground",
              )}
            >
              {option}d
            </button>
          ))}
        </div>
      </header>

      <ul className="divide-y divide-border">
        {services.map((service) => (
          <li key={service.name} className="px-4 pb-3.5 pt-4 @md:px-5">
            <UptimeStrip
              service={service}
              range={range}
              thresholds={thresholds}
              compact={compact}
              loading={loading}
              defaultOpenDate={defaultOpenDates?.[service.name]}
            />
          </li>
        ))}
      </ul>

      <footer className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-t border-border px-4 py-3 text-xs text-muted-foreground @md:px-5">
        {(["operational", "degraded", "outage", "maintenance"] as const).map((state) => (
          <span key={state} className="inline-flex items-center gap-1.5">
            <span
              aria-hidden="true"
              className={cn("inline-block h-3 w-1.5 rounded-[2px]", STATE_BAR[state])}
              style={{ backgroundImage: state === "outage" ? OUTAGE_NOTCH : state === "maintenance" ? MAINTENANCE_BAND : undefined }}
            />
            {STATE_LABEL[state]}
          </span>
        ))}
      </footer>
    </section>
  );
}