{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gauge",
  "title": "Gauge",
  "description": "Primitives for gauges and scores: a semicircle or three-quarter arc gauge built as a meter, with labelled bands, a target tick and an animated fill, band labels as coloured words, plus band, weighted score and NPS helpers.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/format.json",
    "https://www.dashboardblocks.com/r/radix/status-label.json",
    "https://www.dashboardblocks.com/r/radix/use-reveal.json",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/chart.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/gauge.tsx",
      "content": "'use client'\n\nimport {\n  BlockStateText,\n  SkeletonText,\n  useBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport { useChartId } from '@/registry/components/dashboardblocks/chart'\nimport {\n  StatusLabel,\n  type StatusTone,\n  statusToneClasses,\n} from '@/registry/components/dashboardblocks/status-label'\nimport { useReveal } from '@/registry/hooks/use-reveal'\nimport { formatNumber } from '@/registry/lib/dashboardblocks/format'\nimport type { ReactNode } from 'react'\n\nimport { cn } from '@/lib/utils'\n\ntype GaugeTone = 'positive' | 'caution' | 'critical' | 'neutral'\n\ninterface GaugeToneConfig {\n  color: string\n  stroke: string\n  swatch: string\n  text: string\n  tone: StatusTone\n}\n\nconst gaugeToneConfig: Record<GaugeTone, GaugeToneConfig> = {\n  caution: {\n    color: 'var(--color-orange-500)',\n    stroke: 'stroke-orange-500',\n    swatch: 'bg-orange-500',\n    text: statusToneClasses.warning,\n    tone: 'warning',\n  },\n  critical: {\n    color: 'var(--color-red-600)',\n    stroke: 'stroke-red-600',\n    swatch: 'bg-red-600',\n    text: statusToneClasses.bad,\n    tone: 'bad',\n  },\n  neutral: {\n    color: 'var(--color-muted-foreground)',\n    stroke: 'stroke-muted-foreground',\n    swatch: 'bg-muted-foreground',\n    text: statusToneClasses.neutral,\n    tone: 'neutral',\n  },\n  positive: {\n    color: 'var(--color-emerald-600)',\n    stroke: 'stroke-emerald-600',\n    swatch: 'bg-emerald-600',\n    text: statusToneClasses.good,\n    tone: 'good',\n  },\n}\n\ninterface GaugeBand {\n  from: number\n  label: string\n  to: number\n  tone: GaugeTone\n}\n\n/** Where `value` sits between `min` and `max`, clamped to 0–1. */\nfunction getGaugeShare(value: number, min: number, max: number) {\n  const range = max - min\n  if (range <= 0) return 0\n  return Math.min(1, Math.max(0, (value - min) / range))\n}\n\nfunction getGaugeBand(value: number, bands: GaugeBand[]) {\n  if (bands.length === 0) return undefined\n  const found = bands.find(\n    (band, index) =>\n      value >= band.from &&\n      (value < band.to || (index === bands.length - 1 && value <= band.to)),\n  )\n  if (found) return found\n  return value < bands[0].from ? bands[0] : bands[bands.length - 1]\n}\n\nfunction getWeightedScore(items: { score: number; weight: number }[]) {\n  const total = items.reduce((sum, item) => sum + item.weight, 0)\n  if (total <= 0) return 0\n  return items.reduce((sum, item) => sum + item.score * item.weight, 0) / total\n}\n\ninterface NpsResponses {\n  /** Scores 0–6. */\n  detractors: number\n  /** Scores 7–8. */\n  passives: number\n  /** Scores 9–10. */\n  promoters: number\n}\n\n/** Net Promoter Score: the share of promoters minus the share of detractors, −100 to 100. */\nfunction getNps({ detractors, passives, promoters }: NpsResponses) {\n  const total = detractors + passives + promoters\n  if (total === 0) {\n    return { detractors: 0, passives: 0, promoters: 0, score: 0, total }\n  }\n  const shares = {\n    detractors: detractors / total,\n    passives: passives / total,\n    promoters: promoters / total,\n  }\n  return {\n    ...shares,\n    score: Math.round((shares.promoters - shares.detractors) * 100),\n    total,\n  }\n}\n\nconst CENTER = 50\nconst TARGET_MARKER_OVERHANG = 4\nconst BAND_GAP = 1.5\nconst SCALE_WIDTH = 3\nconst HALO = 1.5\nconst SURFACE = 'var(--gauge-surface, var(--color-card))'\n\nconst round = (value: number) => Math.round(value * 100) / 100\n\nfunction polar(angle: number, radius: number) {\n  const radians = (angle * Math.PI) / 180\n  return {\n    x: round(CENTER + radius * Math.sin(radians)),\n    y: round(CENTER - radius * Math.cos(radians)),\n  }\n}\n\nfunction arcPath(startAngle: number, endAngle: number, radius: number) {\n  const start = polar(startAngle, radius)\n  const end = polar(endAngle, radius)\n  const largeArc = endAngle - startAngle > 180 ? 1 : 0\n  return `M ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArc} 1 ${end.x} ${end.y}`\n}\n\ninterface GaugeProps {\n  animated?: boolean\n  /** Labelled ranges on the scale, in order from `min` to `max`. */\n  bands?: GaugeBand[]\n  children?: ReactNode\n  className?: string\n  /** Ignored when `colorByBand` is set, `var(--color-chart-2)` by default. */\n  color?: string\n  colorByBand?: boolean\n  formatScale?: (value: number) => string\n  /** @default 'fill' */\n  indicator?: 'fill' | 'marker'\n  label: string\n  /** @default 100 */\n  max?: number\n  /** @default 0 */\n  min?: number\n  origin?: number\n  /** An earlier value, drawn as a faint tick across the scale. */\n  previous?: number\n  /** @default 180 */\n  sweep?: 180 | 270\n  target?: number\n  /** In hundredths of the gauge's width, 10 by default. */\n  thickness?: number\n  value: number\n  valueText?: string\n}\n\nfunction Gauge({\n  animated = true,\n  bands = [],\n  children,\n  className,\n  color = 'var(--color-chart-2)',\n  colorByBand = false,\n  formatScale,\n  indicator = 'fill',\n  label,\n  max = 100,\n  min = 0,\n  origin = min,\n  previous,\n  sweep = 180,\n  target,\n  thickness = 10,\n  value,\n  valueText,\n}: GaugeProps) {\n  const { ref, revealed } = useReveal(animated)\n  const state = useBlockState()\n\n  const radius = CENTER - TARGET_MARKER_OVERHANG - thickness / 2\n  const startAngle = -sweep / 2\n  const endAngle = sweep / 2\n  const angleOf = (at: number) => startAngle + getGaugeShare(at, min, max) * sweep\n  const end = polar(endAngle, radius)\n  const height = round(Math.max(end.y, CENTER) + thickness / 2 + TARGET_MARKER_OVERHANG)\n  const track = arcPath(startAngle, endAngle, radius)\n\n  const band = getGaugeBand(value, bands)\n  const tint = colorByBand && band ? gaugeToneConfig[band.tone].color : color\n  const knobColor =\n    indicator === 'marker' && band ? gaugeToneConfig[band.tone].color : tint\n  const gradientId = useChartId()\n  const gradientFrom = polar(angleOf(origin), radius)\n  const gradientTo = polar(angleOf(value), radius)\n  const gradient =\n    Math.hypot(gradientTo.x - gradientFrom.x, gradientTo.y - gradientFrom.y) > 4\n  const valueShare = getGaugeShare(value, min, max)\n  const originShare = getGaugeShare(origin, min, max)\n  const shown = revealed ? valueShare : originShare\n  const fillStart = Math.min(originShare, shown) * 100\n  const fillLength = Math.abs(shown - originShare) * 100\n  const cap = (thickness / 2 / ((radius * sweep * Math.PI) / 180)) * 100\n  const startInset = fillStart > 0 ? cap : 0\n  const endInset = fillStart + fillLength < 100 ? cap : 0\n  const dashStart = fillStart + startInset\n  const dashLength = Math.max(0, fillLength - startInset - endInset)\n\n  const bandRadius =\n    indicator === 'marker' ? radius : radius - thickness / 2 - 2.5 - SCALE_WIDTH / 2\n  const bandWidth = indicator === 'marker' ? thickness : SCALE_WIDTH\n  const gapAngle = (BAND_GAP / bandRadius) * (180 / Math.PI)\n\n  const previousTick =\n    previous !== undefined &&\n    previous >= min &&\n    previous <= max &&\n    !(indicator === 'marker' && Math.abs(previous - value) < (max - min) * 0.04)\n      ? {\n          inner: polar(angleOf(previous), radius - thickness / 2 - 2.5),\n          outer: polar(angleOf(previous), radius + thickness / 2 + 2.5),\n        }\n      : undefined\n\n  const motion =\n    'duration-1000 ease-[cubic-bezier(0.33,1,0.68,1)] motion-reduce:transition-none'\n  const scaleEnd = polar(startAngle, radius)\n  const scaleInset = `${scaleEnd.x}%`\n\n  return (\n    <div\n      ref={ref}\n      role={state ? undefined : 'meter'}\n      aria-label={state ? undefined : label}\n      aria-valuemax={state ? undefined : max}\n      aria-valuemin={state ? undefined : min}\n      aria-valuenow={state ? undefined : value}\n      aria-valuetext={state ? undefined : valueText}\n      className={cn('relative shrink-0', className)}\n    >\n      <div className='relative'>\n        <svg\n          aria-hidden\n          viewBox={`0 0 100 ${height}`}\n          className={cn(\n            'block h-auto w-full overflow-visible',\n            state === 'loading' && 'animate-pulse motion-reduce:animate-none',\n          )}\n          fill='none'\n        >\n          {gradient && (\n            <defs>\n              <linearGradient\n                id={gradientId}\n                gradientUnits='userSpaceOnUse'\n                x1={gradientFrom.x}\n                x2={gradientTo.x}\n                y1={gradientFrom.y}\n                y2={gradientTo.y}\n              >\n                <stop\n                  offset='0'\n                  stopColor={`color-mix(in oklab, ${tint} 40%, ${SURFACE})`}\n                />\n                <stop offset='1' stopColor={tint} />\n              </linearGradient>\n            </defs>\n          )}\n          {(state || indicator === 'fill' || bands.length === 0) && (\n            <path\n              d={track}\n              className={state ? 'stroke-muted' : undefined}\n              style={\n                state\n                  ? undefined\n                  : { stroke: `color-mix(in oklab, ${tint} 14%, transparent)` }\n              }\n              strokeLinecap='round'\n              strokeWidth={state ? thickness : thickness + HALO * 2}\n            />\n          )}\n          {!state &&\n            bands.map((item, index) => {\n              const first = index === 0\n              const last = index === bands.length - 1\n              const from = angleOf(item.from) + (first ? 0 : gapAngle / 2)\n              const to = angleOf(item.to) - (last ? 0 : gapAngle / 2)\n              if (to <= from) return null\n              const toneColor = gaugeToneConfig[item.tone].color\n              const stroke =\n                indicator === 'marker' && item !== band\n                  ? `color-mix(in oklab, ${toneColor} 30%, ${SURFACE})`\n                  : toneColor\n              const ends = [\n                first && polar(from, bandRadius),\n                last && polar(to, bandRadius),\n              ]\n              return (\n                <g key={item.label}>\n                  <path\n                    d={arcPath(from, to, bandRadius)}\n                    stroke={stroke}\n                    strokeWidth={bandWidth}\n                  />\n                  {ends.map(\n                    (point, end) =>\n                      point && (\n                        <circle\n                          key={end}\n                          cx={point.x}\n                          cy={point.y}\n                          fill={stroke}\n                          r={bandWidth / 2}\n                        />\n                      ),\n                  )}\n                </g>\n              )\n            })}\n          {!state && indicator === 'fill' && (\n            <path\n              d={track}\n              pathLength={100}\n              className={cn('transition-[stroke-dasharray,stroke-dashoffset]', motion)}\n              style={{ stroke: gradient ? `url(#${gradientId})` : tint }}\n              strokeDasharray={`${round(dashLength)} ${round(200 - dashLength)}`}\n              strokeDashoffset={round(200 - dashStart)}\n              strokeLinecap='round'\n              strokeOpacity={fillLength > 0 ? 1 : 0}\n              strokeWidth={thickness}\n            />\n          )}\n          {!state && target !== undefined && target >= min && target <= max && (\n            <g strokeLinecap='round'>\n              {[\n                { stroke: SURFACE, width: 5 },\n                { stroke: 'var(--color-foreground)', width: 2 },\n              ].map((line) => {\n                const angle = angleOf(target)\n                const inner = polar(angle, radius - thickness / 2 - 2.5)\n                const outer = polar(angle, radius + thickness / 2 + 2.5)\n                return (\n                  <line\n                    key={line.width}\n                    stroke={line.stroke}\n                    strokeWidth={line.width}\n                    x1={inner.x}\n                    x2={outer.x}\n                    y1={inner.y}\n                    y2={outer.y}\n                  />\n                )\n              })}\n            </g>\n          )}\n          {!state && previousTick && (\n            <line\n              className='stroke-muted-foreground'\n              strokeLinecap='round'\n              strokeOpacity={0.6}\n              strokeWidth={1.5}\n              x1={previousTick.inner.x}\n              x2={previousTick.outer.x}\n              y1={previousTick.inner.y}\n              y2={previousTick.outer.y}\n            />\n          )}\n          {!state && (indicator === 'marker' || valueShare !== originShare) && (\n            <g\n              className={cn('drop-shadow-sm transition-transform', motion)}\n              style={{\n                transform: `rotate(${round(startAngle + shown * sweep)}deg)`,\n                transformOrigin: `${CENTER}px ${CENTER}px`,\n              }}\n            >\n              <circle\n                cx={CENTER}\n                cy={CENTER - radius}\n                fill={`color-mix(in oklab, ${knobColor} 80%, var(--color-foreground))`}\n                r={thickness / 2 + 1}\n                stroke={SURFACE}\n                strokeWidth={2}\n              />\n            </g>\n          )}\n        </svg>\n        {children && (\n          <div\n            aria-hidden={state ? undefined : true}\n            className={cn(\n              'absolute inset-x-0 flex flex-col items-center text-center',\n              sweep === 180 ? 'bottom-0 justify-end' : '-translate-y-1/2',\n            )}\n            style={sweep === 180 ? undefined : { top: `${(CENTER / height) * 100}%` }}\n          >\n            {children}\n          </div>\n        )}\n      </div>\n      {formatScale && (\n        <div\n          aria-hidden\n          className='text-muted-foreground mt-1 flex justify-between text-xs tabular-nums'\n          style={{ paddingInline: sweep === 180 ? 0 : scaleInset }}\n        >\n          <span>{formatScale(min)}</span>\n          <span>{formatScale(max)}</span>\n        </div>\n      )}\n    </div>\n  )\n}\n\ninterface GaugeValueProps {\n  children: ReactNode\n  className?: string\n}\n\nfunction GaugeValue({ children, className }: GaugeValueProps) {\n  const state = useBlockState()\n\n  return (\n    <span\n      data-slot='gauge-value'\n      className={cn('font-light tracking-tight tabular-nums', className)}\n    >\n      {state === 'loading' ? (\n        <SkeletonText className='w-[2.5em]' />\n      ) : state ? (\n        <BlockStateText className='text-xl' variant='short' />\n      ) : (\n        children\n      )}\n    </span>\n  )\n}\n\nfunction GaugeToneLabel({\n  className,\n  label,\n  tone,\n}: {\n  className?: string\n  label: string\n  tone: GaugeTone\n}) {\n  return (\n    <StatusLabel className={className} tone={gaugeToneConfig[tone].tone}>\n      {label}\n    </StatusLabel>\n  )\n}\n\nfunction GaugeLegend({\n  bands,\n  className,\n  format = (value) => formatNumber(value),\n}: {\n  bands: GaugeBand[]\n  className?: string\n  format?: (value: number) => string\n}) {\n  const state = useBlockState()\n  if (state === 'empty' || state === 'error') return null\n\n  return (\n    <ul\n      className={cn(\n        'text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-xs',\n        className,\n      )}\n    >\n      {bands.map((band) => (\n        <li key={band.label} className='flex items-center gap-1.5'>\n          <span\n            aria-hidden\n            className={cn('size-2.5 rounded-full', gaugeToneConfig[band.tone].swatch)}\n          />\n          <span className='text-foreground font-medium'>{band.label}</span>\n          <span className='tabular-nums'>\n            {format(band.from)}–{format(band.to)}\n          </span>\n        </li>\n      ))}\n    </ul>\n  )\n}\n\nfunction GaugeTargetKey({\n  className,\n  label = 'Target',\n}: {\n  className?: string\n  label?: string\n}) {\n  const state = useBlockState()\n  if (state === 'empty' || state === 'error') return null\n\n  return (\n    <span\n      className={cn(\n        'text-muted-foreground inline-flex items-center gap-1.5 text-xs',\n        className,\n      )}\n    >\n      <span aria-hidden className='bg-foreground h-3 w-0.5 rounded-full' />\n      {label}\n    </span>\n  )\n}\n\nfunction GaugePreviousKey({\n  className,\n  label,\n}: {\n  className?: string\n  label: ReactNode\n}) {\n  const state = useBlockState()\n  if (state === 'empty' || state === 'error') return null\n\n  return (\n    <span\n      className={cn(\n        'text-muted-foreground inline-flex items-center gap-1.5 text-xs',\n        className,\n      )}\n    >\n      <span aria-hidden className='bg-muted-foreground/60 h-3 w-0.5 rounded-full' />\n      {label}\n    </span>\n  )\n}\n\nexport {\n  Gauge,\n  GaugeLegend,\n  GaugePreviousKey,\n  GaugeTargetKey,\n  GaugeToneLabel,\n  GaugeValue,\n  gaugeToneConfig,\n  getGaugeBand,\n  getGaugeShare,\n  getNps,\n  getWeightedScore,\n}\n\nexport type {\n  GaugeBand,\n  GaugeProps,\n  GaugeTone,\n  GaugeToneConfig,\n  GaugeValueProps,\n  NpsResponses,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/gauge.tsx"
    }
  ],
  "type": "registry:component"
}
