All files / src/components/detail MeterBar.tsx

100% Statements 5/5
100% Branches 12/12
100% Functions 2/2
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78                                      104x                                         306x   104x               147x                                                      
import React from "react";
 
/**
 * A horizontal meter: how much of something is used. One component for
 * every bar that says "this much of that" — a budget's spend against its
 * cap, a month's tokens against all time, a plan's usage against its limit —
 * which were three hand-drawn copies before.
 *
 * The fill's colour is a meaning (`MeterTone`), spelled out once as whole
 * class names because Tailwind cannot see interpolated ones.
 */
export type MeterTone =
  | "ok"
  | "warning"
  | "danger"
  | "info"
  | "accent"
  | "muted";
 
const FILL: Record<MeterTone, string> = {
  ok: "bg-emerald-400",
  warning: "bg-amber-400",
  danger: "bg-red-400",
  info: "bg-blue-400",
  accent: "bg-violet-400",
  muted: "bg-emerald-400 opacity-30",
};
 
export interface MeterBarProps {
  /** How much is used, 0–1. Above 1 draws full; null draws empty. */
  share: number | null;
  tone: MeterTone;
  loading?: boolean;
  /** Where a projection lands, 0–1 — drawn as a tick on the track. */
  marker?: number | null;
  /** What the bar measures, for a screen reader. */
  label?: string;
  className?: string;
}
 
const clamp = (value: number) => Math.max(0, Math.min(value, 1));
 
const MeterBar: React.FC<MeterBarProps> = ({
  share,
  tone,
  loading = false,
  marker = null,
  label,
  className = "",
}) => (
  <div
    className={`relative h-1.5 rounded-full bg-gray-100 dark:bg-gray-700 overflow-hidden ${className}`}
    role="meter"
    aria-label={label}
    aria-valuemin={0}
    aria-valuemax={100}
    aria-valuenow={share === null ? undefined : Math.round(clamp(share) * 100)}
  >
    {loading ? (
      <div className="h-full w-1/3 rounded-full bg-gray-200 dark:bg-gray-600 animate-pulse" />
    ) : (
      <div
        className={`h-full rounded-full transition-all duration-700 ${FILL[tone]}`}
        style={{ width: `${share === null ? 0 : clamp(share) * 100}%` }}
      />
    )}
    {!loading && marker !== null && (
      <div
        aria-hidden
        className="absolute top-0 h-full w-0.5 bg-gray-500 dark:bg-gray-300"
        style={{ left: `calc(${clamp(marker) * 100}% - 1px)` }}
      />
    )}
  </div>
);
 
export default MeterBar;