{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "usage-meter",
  "title": "Usage Meter",
  "description": "Progress meter for storage, seats, and rate limits with thresholds, segmented breakdown, and overage tracking.",
  "dependencies": [],
  "registryDependencies": [
    "badge",
    "utils",
    "@drift-ui/warning-color"
  ],
  "files": [
    {
      "path": "registry/default/ui/usage-meter.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { Badge } from \"@/registry/default/ui/badge\"\nimport { cn } from \"@/registry/default/lib/utils\"\nimport {\n  calculateMeterStatus,\n  calculatePercentage,\n  calculateSegments,\n  formatUsageValue,\n  getUsageAriaValueText,\n  type CalculatedSegment,\n  type UsageMeterSegment,\n  type UsageMeterStatus,\n} from \"@/registry/default/lib/usage-meter-utils\"\n\nexport type { UsageMeterSegment, UsageMeterStatus, CalculatedSegment }\n\nexport interface UsageMeterProps extends React.HTMLAttributes<HTMLDivElement> {\n  value?: number\n  max?: number\n  min?: number\n  unit?: string\n  warningAt?: number\n  dangerAt?: number\n  segments?: UsageMeterSegment[]\n  label?: React.ReactNode\n  description?: React.ReactNode\n  showValue?: boolean\n  showLegend?: boolean\n  showStatusBadge?: boolean\n  size?: \"sm\" | \"md\" | \"lg\"\n  locale?: string\n  decimals?: number\n  formatOptions?: Intl.NumberFormatOptions\n  renderValue?: (\n    value: number,\n    max: number,\n    percentage: number\n  ) => React.ReactNode\n}\n\nconst SIZE_VARIANTS = {\n  sm: \"h-1.5\",\n  md: \"h-2.5\",\n  lg: \"h-4\",\n} as const\n\nconst STATUS_BAR_COLORS: Record<UsageMeterStatus, string> = {\n  normal: \"bg-primary\",\n  warning: \"bg-warning\",\n  danger: \"bg-destructive\",\n}\n\nexport function UsageMeter({\n  value: valueProp,\n  max = 100,\n  min = 0,\n  unit,\n  warningAt = 0.8,\n  dangerAt = 1.0,\n  segments,\n  label,\n  description,\n  showValue = true,\n  showLegend,\n  showStatusBadge = true,\n  size = \"md\",\n  locale = \"en-US\",\n  decimals,\n  formatOptions,\n  renderValue,\n  className,\n  ...props\n}: UsageMeterProps) {\n  const safeMin = Math.max(0, min)\n  const safeMax = Math.max(safeMin, max)\n\n  const hasSegments = Array.isArray(segments) && segments.length > 0\n\n  const totalValue = React.useMemo(() => {\n    if (hasSegments) {\n      const sum = segments.reduce((acc, s) => acc + Math.max(0, s.value), 0)\n      return Math.round(sum * 10000) / 10000\n    }\n    return Math.max(0, valueProp ?? 0)\n  }, [hasSegments, segments, valueProp])\n\n  const calculatedSegments = React.useMemo(() => {\n    if (!hasSegments) return []\n    return calculateSegments(segments, safeMax, undefined, safeMin)\n  }, [hasSegments, segments, safeMax, safeMin])\n\n  const status = React.useMemo(\n    () =>\n      calculateMeterStatus({\n        value: totalValue,\n        max: safeMax,\n        min: safeMin,\n        warningAt,\n        dangerAt,\n      }),\n    [totalValue, safeMax, safeMin, warningAt, dangerAt]\n  )\n\n  const percentage = React.useMemo(\n    () => calculatePercentage(totalValue, safeMax, decimals ?? 1, safeMin),\n    [totalValue, safeMax, decimals, safeMin]\n  )\n\n  const isOverLimit = totalValue > safeMax\n  const overage = isOverLimit\n    ? Math.round((totalValue - safeMax) * 10000) / 10000\n    : 0\n\n  const ariaValueText = React.useMemo(\n    () =>\n      getUsageAriaValueText({\n        value: totalValue,\n        max: safeMax,\n        min: safeMin,\n        unit,\n        locale,\n        decimals,\n        formatOptions,\n      }),\n    [totalValue, safeMax, safeMin, unit, locale, decimals, formatOptions]\n  )\n\n  const formattedCurrent = React.useMemo(\n    () =>\n      formatUsageValue(totalValue, {\n        unit,\n        locale,\n        decimals,\n        formatOptions,\n      }),\n    [totalValue, unit, locale, decimals, formatOptions]\n  )\n\n  const formattedMax = React.useMemo(\n    () =>\n      formatUsageValue(safeMax, {\n        unit,\n        locale,\n        decimals,\n        formatOptions,\n      }),\n    [safeMax, unit, locale, decimals, formatOptions]\n  )\n\n  const formattedOverage = React.useMemo(\n    () =>\n      formatUsageValue(overage, {\n        unit,\n        locale,\n        decimals,\n        formatOptions,\n      }),\n    [overage, unit, locale, decimals, formatOptions]\n  )\n\n  const shouldShowLegend = showLegend ?? hasSegments\n  const generatedId = React.useId()\n  const internalLabelId = `usage-meter-label-${generatedId}`\n  const labelId =\n    props[\"aria-labelledby\"] ?? (label ? internalLabelId : undefined)\n  const descriptionId = description\n    ? `usage-meter-desc-${generatedId}`\n    : undefined\n  const ariaDescribedBy = props[\"aria-describedby\"] ?? descriptionId\n  const ariaLabel = props[\"aria-label\"] ?? (labelId ? undefined : \"Usage\")\n\n  const hasStatusBadge =\n    showStatusBadge && (isOverLimit || (!isOverLimit && status === \"warning\"))\n  const hasHeader = Boolean(label || description || showValue || hasStatusBadge)\n\n  const ariaValueNow = Math.min(safeMax, Math.max(safeMin, totalValue))\n  const limitMarkerPercent =\n    totalValue > safeMin\n      ? Math.round(((safeMax - safeMin) / (totalValue - safeMin)) * 10000) / 100\n      : 0\n\n  return (\n    <div\n      data-slot=\"usage-meter\"\n      className={cn(\"flex w-full flex-col gap-2\", className)}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1\">\n          <div className=\"flex min-w-0 flex-col\">\n            {label && (\n              <span\n                id={internalLabelId}\n                className=\"text-sm font-medium text-foreground\"\n              >\n                {label}\n              </span>\n            )}\n            {description && (\n              <span\n                id={descriptionId}\n                className=\"text-xs text-muted-foreground\"\n              >\n                {description}\n              </span>\n            )}\n          </div>\n\n          <div className=\"flex items-center gap-2\">\n            {showStatusBadge && isOverLimit && (\n              <Badge variant=\"destructive\" className=\"shrink-0 text-xs\">\n                {formattedOverage} over limit\n              </Badge>\n            )}\n            {showStatusBadge && !isOverLimit && status === \"warning\" && (\n              <Badge\n                variant=\"secondary\"\n                className=\"shrink-0 border-warning/40 text-xs text-warning\"\n              >\n                {Math.round(percentage)}% used\n              </Badge>\n            )}\n\n            {showValue && (\n              <span className=\"shrink-0 text-xs text-muted-foreground\">\n                {renderValue ? (\n                  renderValue(totalValue, safeMax, percentage)\n                ) : (\n                  <>\n                    <span className=\"font-semibold text-foreground\">\n                      {formattedCurrent}\n                    </span>{\" \"}\n                    / {formattedMax}\n                  </>\n                )}\n              </span>\n            )}\n          </div>\n        </div>\n      )}\n\n      {/* Meter Track */}\n      <div\n        role=\"meter\"\n        tabIndex={0}\n        aria-label={ariaLabel}\n        aria-labelledby={labelId}\n        aria-describedby={ariaDescribedBy}\n        aria-valuenow={ariaValueNow}\n        aria-valuemin={safeMin}\n        aria-valuemax={safeMax}\n        aria-valuetext={ariaValueText}\n        data-slot=\"usage-meter-track\"\n        data-status={status}\n        className={cn(\n          \"relative flex w-full overflow-hidden rounded-full bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1\",\n          SIZE_VARIANTS[size]\n        )}\n      >\n        {hasSegments ? (\n          // Segmented mode\n          isOverLimit ? (\n            // Over-limit scale: segments scale proportionally to totalValue, with limit line\n            <>\n              {calculatedSegments.map((seg, idx) => {\n                const widthPercent = (seg.value / totalValue) * 100\n                return (\n                  <div\n                    key={seg.id ?? `${seg.label}-${idx}`}\n                    data-slot=\"usage-meter-segment\"\n                    style={{ width: `${widthPercent}%` }}\n                    className={cn(\n                      \"h-full transition-[width] duration-300\",\n                      seg.color\n                    )}\n                    title={`${seg.label}: ${formatUsageValue(seg.value, { unit, locale, decimals, formatOptions })}`}\n                  />\n                )\n              })}\n              {/* Limit Marker Line */}\n              <div\n                data-slot=\"usage-meter-limit-marker\"\n                style={{ left: `${limitMarkerPercent}%` }}\n                className=\"absolute top-0 bottom-0 z-10 w-0.5 -translate-x-1/2 bg-foreground/80 shadow-xs\"\n                title={`Limit: ${formattedMax}`}\n              />\n            </>\n          ) : (\n            // Within limit: segments scale relative to max\n            calculatedSegments.map((seg, idx) => (\n              <div\n                key={seg.id ?? `${seg.label}-${idx}`}\n                data-slot=\"usage-meter-segment\"\n                style={{ width: `${Math.min(100, seg.percentage)}%` }}\n                className={cn(\n                  \"h-full transition-[width] duration-300\",\n                  seg.color\n                )}\n                title={`${seg.label}: ${formatUsageValue(seg.value, { unit, locale, decimals, formatOptions })}`}\n              />\n            ))\n          )\n        ) : (\n          // Single value mode\n          <div\n            data-slot=\"usage-meter-bar\"\n            style={{\n              width: isOverLimit\n                ? \"100%\"\n                : `${Math.min(100, Math.max(0, percentage))}%`,\n            }}\n            className={cn(\n              \"h-full rounded-full transition-[width,background-color] duration-300\",\n              STATUS_BAR_COLORS[status]\n            )}\n          />\n        )}\n      </div>\n\n      {/* Legend for segments */}\n      {shouldShowLegend && calculatedSegments.length > 0 && (\n        <UsageMeterLegend\n          segments={calculatedSegments}\n          unit={unit}\n          locale={locale}\n          decimals={decimals}\n          formatOptions={formatOptions}\n        />\n      )}\n    </div>\n  )\n}\n\nexport interface UsageMeterLegendProps extends React.HTMLAttributes<HTMLUListElement> {\n  segments: CalculatedSegment[]\n  unit?: string\n  locale?: string\n  decimals?: number\n  formatOptions?: Intl.NumberFormatOptions\n}\n\nexport function UsageMeterLegend({\n  segments,\n  unit,\n  locale = \"en-US\",\n  decimals,\n  formatOptions,\n  className,\n  ...props\n}: UsageMeterLegendProps) {\n  return (\n    <ul\n      data-slot=\"usage-meter-legend\"\n      className={cn(\n        \"flex flex-wrap items-center gap-x-4 gap-y-1.5 pt-1 text-xs\",\n        className\n      )}\n      {...props}\n    >\n      {segments.map((seg, idx) => (\n        <li\n          key={seg.id ?? `${seg.label}-${idx}`}\n          className=\"flex items-center gap-1.5 text-muted-foreground\"\n        >\n          <span\n            className={cn(\"size-2 shrink-0 rounded-full\", seg.color)}\n            aria-hidden=\"true\"\n          />\n          <span className=\"font-medium text-foreground\">{seg.label}</span>\n          <span>\n            {formatUsageValue(seg.value, {\n              unit,\n              locale,\n              decimals,\n              formatOptions,\n            })}\n          </span>\n        </li>\n      ))}\n    </ul>\n  )\n}\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/default/lib/usage-meter-utils.ts",
      "content": "export type UsageMeterStatus = \"normal\" | \"warning\" | \"danger\"\n\nexport interface UsageMeterSegment {\n  id?: string\n  label: string\n  value: number\n  color?: string\n}\n\nexport interface CalculatedSegment extends UsageMeterSegment {\n  percentage: number\n  share: number\n  color: string\n}\n\nexport const DEFAULT_SEGMENT_COLORS: readonly string[] = [\n  \"bg-chart-1\",\n  \"bg-chart-2\",\n  \"bg-chart-3\",\n  \"bg-chart-4\",\n  \"bg-chart-5\",\n]\n\nexport interface MeterStatusOptions {\n  value: number\n  max: number\n  min?: number\n  warningAt?: number\n  dangerAt?: number\n}\n\nexport function resolveThreshold(\n  threshold: number | undefined,\n  max: number,\n  defaultRatio: number,\n  min = 0\n): number {\n  const safeMin = Math.max(0, min)\n  const safeMax = Math.max(safeMin, max)\n  const range = safeMax - safeMin\n  if (threshold === undefined) return safeMin + range * defaultRatio\n  return threshold <= 1 && threshold >= 0\n    ? safeMin + range * threshold\n    : threshold\n}\n\nexport function calculateMeterStatus({\n  value,\n  max,\n  min = 0,\n  warningAt = 0.8,\n  dangerAt = 1.0,\n}: MeterStatusOptions): UsageMeterStatus {\n  const safeMin = Math.max(0, min)\n  const safeMax = Math.max(safeMin, max)\n  if (safeMax <= safeMin) return value > safeMin ? \"danger\" : \"normal\"\n  const warningValue = resolveThreshold(warningAt, safeMax, 0.8, safeMin)\n  const dangerValue = resolveThreshold(dangerAt, safeMax, 1.0, safeMin)\n\n  if (value > dangerValue) {\n    return \"danger\"\n  }\n  if (value >= warningValue) {\n    return \"warning\"\n  }\n  return \"normal\"\n}\n\nexport function calculatePercentage(\n  value: number,\n  max: number,\n  decimals = 1,\n  min = 0\n): number {\n  const safeMin = Math.max(0, min)\n  const safeMax = Math.max(safeMin, max)\n  const range = safeMax - safeMin\n  if (range <= 0) return value >= safeMax ? 100 : 0\n  const ratio = ((value - safeMin) / range) * 100\n  const factor = 10 ** decimals\n  return Math.round(ratio * factor) / factor\n}\n\nexport function calculateSegments(\n  segments: readonly UsageMeterSegment[],\n  max: number,\n  colors: readonly string[] = DEFAULT_SEGMENT_COLORS,\n  min = 0\n): CalculatedSegment[] {\n  const safeMin = Math.max(0, min)\n  const safeMax = Math.max(safeMin, max)\n  const range = safeMax - safeMin\n  const palette = colors && colors.length > 0 ? colors : DEFAULT_SEGMENT_COLORS\n  const total = segments.reduce((acc, s) => acc + Math.max(0, s.value), 0)\n\n  return segments.map((seg, idx) => {\n    const val = Math.max(0, seg.value)\n    const percentage =\n      range > 0 ? calculatePercentage(val, safeMax, 2, safeMin) : 0\n    const share = total > 0 ? calculatePercentage(val, total, 2, 0) : 0\n    const color = seg.color ?? palette[idx % palette.length]\n\n    return {\n      ...seg,\n      value: val,\n      percentage,\n      share,\n      color,\n    }\n  })\n}\n\nexport interface FormatUsageOptions {\n  unit?: string\n  locale?: string\n  formatOptions?: Intl.NumberFormatOptions\n  decimals?: number\n}\n\nexport function formatUsageValue(\n  value: number,\n  options: FormatUsageOptions = {}\n): string {\n  const { unit, locale = \"en-US\", formatOptions, decimals } = options\n\n  const opts: Intl.NumberFormatOptions = {\n    ...formatOptions,\n  }\n\n  if (decimals !== undefined && opts.maximumFractionDigits === undefined) {\n    opts.minimumFractionDigits = decimals\n    opts.maximumFractionDigits = decimals\n  }\n\n  const formattedNum = new Intl.NumberFormat(locale, opts).format(value)\n\n  if (!unit) {\n    return formattedNum\n  }\n\n  if (unit === \"%\") {\n    return `${formattedNum}%`\n  }\n\n  return `${formattedNum} ${unit}`\n}\n\nexport interface AriaValueTextOptions {\n  value: number\n  max: number\n  min?: number\n  unit?: string\n  locale?: string\n  formatOptions?: Intl.NumberFormatOptions\n  decimals?: number\n}\n\nexport function getUsageAriaValueText({\n  value,\n  max,\n  min = 0,\n  unit,\n  locale = \"en-US\",\n  formatOptions,\n  decimals,\n}: AriaValueTextOptions): string {\n  const safeMin = Math.max(0, min)\n  const safeMax = Math.max(safeMin, max)\n  const formattedVal = formatUsageValue(value, {\n    unit,\n    locale,\n    decimals,\n    formatOptions,\n  })\n  const formattedMax = formatUsageValue(safeMax, {\n    unit,\n    locale,\n    decimals,\n    formatOptions,\n  })\n  const percentage = calculatePercentage(value, safeMax, 0, safeMin)\n\n  if (value > safeMax) {\n    const overage = value - safeMax\n    const formattedOverage = formatUsageValue(overage, {\n      unit,\n      locale,\n      decimals,\n      formatOptions,\n    })\n    return `${formattedVal} of ${formattedMax}, ${percentage}% (${formattedOverage} over limit)`\n  }\n\n  return `${formattedVal} of ${formattedMax}, ${percentage}%`\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:ui"
}