{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "kpi",
  "title": "KPI",
  "description": "A key number as a card, with its change and the picture that says what it means: a trend against the period before, progress to a target with its pace, a score in bands, a breakdown, a live count or a strip of days. A new period rolls every number from where it was and moves every picture to its new shape.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/animated-number.json",
    "https://kinoui.com/r/badge.json",
    "https://kinoui.com/r/bar-chart.json",
    "https://kinoui.com/r/card.json",
    "https://kinoui.com/r/chart.json",
    "https://kinoui.com/r/chart-root.json",
    "https://kinoui.com/r/chart-math.json",
    "https://kinoui.com/r/live.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/placeholder.json",
    "https://kinoui.com/r/skeleton.json",
    "https://kinoui.com/r/sparkline.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/track.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/kpi.tsx",
      "content": "'use client'\n\nimport { AnimatedNumber } from '@/registry/components/kino/animated-number'\nimport { Badge } from '@/registry/components/kino/badge'\nimport { Bar, BarChart, type BarChartProps } from '@/registry/components/kino/bar-chart'\nimport {\n  Card,\n  CardAction,\n  CardContent,\n  CardHeader,\n  CardTitle,\n} from '@/registry/components/kino/card'\nimport { ChartTooltip } from '@/registry/components/kino/chart'\nimport {\n  Skeleton,\n  SkeletonContent,\n  SkeletonText,\n} from '@/registry/components/kino/skeleton'\nimport { Sparkline, type SparklineProps } from '@/registry/components/kino/sparkline'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport type { ChartDatum } from '@/registry/lib/chart-math'\nimport { swatchClassName } from '@/registry/lib/chart-root'\nimport { LivePulse } from '@/registry/lib/live'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { placeholderFillClassName } from '@/registry/lib/placeholder'\nimport { Swap, SwapText } from '@/registry/lib/swap'\nimport {\n  slidingFillClassName,\n  slidingFillStyle,\n  slidingMarkClassName,\n  trackClassName,\n  trackDirClassName,\n  valuePercent,\n} from '@/registry/lib/track'\nimport {\n  Meter as MeterPrimitive,\n  MeterTrack as MeterTrackPrimitive,\n} from '@ui-sdk/react/meter'\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useId,\n  useMemo,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A key number on a card, and what it means: its value, how it moved since\n * the period before, and the picture its use needs. Every KPI shares the\n * card, the label, the value and the change; the picture is the variant,\n * each a part of its own: a trend over the period (with the period before\n * dashed behind it), progress to a goal or a limit with the pace it should\n * keep, a score in its bands, the parts of a whole, or a strip of days.\n *\n * Each part answers a new value in place, so the move explains the change:\n * the digits roll from the old value, the arrow turns to the new direction,\n * the trend reshapes, a fill or a marker glides to its new place, and the\n * parts of a whole make room for each other. Nothing moves on first paint.\n */\n\n/** Which way of moving is good news: higher for revenue, lower for churn, neither for a count of sessions. */\ntype KpiBetter = 'higher' | 'lower' | 'neither'\n\n/**\n * How a change is measured: as a share of the value before (`percent`), as\n * the difference itself (`amount`), or, for a value that is a rate such as\n * 2.1%, the difference in percentage points (`points`), since a rate going\n * from 2.1% to 1.8% fell 0.3 points, not 14%.\n */\ntype KpiChangeKind = 'percent' | 'amount' | 'points'\n\n/** Which way the value moved: up, down, not at all, or none to tell, with nothing before it. */\ntype KpiDirection = 'up' | 'down' | 'flat' | 'none'\n\n/** Whether a move or a state is good news, worth a look, bad news, or neither. */\ntype KpiTone = 'positive' | 'warning' | 'negative' | 'neutral'\n\ninterface KpiMessages {\n  up: string\n  down: string\n  flat: string\n  none: string\n  noData: string\n  /** A change in percentage points, already written as a number. */\n  points: (size: string) => string\n  /** The share of the goal reached, or of the limit used, already written as a percentage. */\n  ofTarget: (share: string, target: string) => string\n  achieved: string\n  onTrack: string\n  behind: string\n  /** What is left before the goal, already written. */\n  toGo: (left: string) => string\n  /** What is left before the limit, already written. */\n  left: (left: string) => string\n  /** How far past the limit it is, already written. */\n  over: (by: string) => string\n  overPace: string\n  live: string\n  /** What the last value of a live trend says in the tooltip: it is still coming in. */\n  soFar: string\n}\n\nconst kpiMessages: KpiMessages = {\n  up: 'Up',\n  down: 'Down',\n  flat: 'No change',\n  none: 'New',\n  noData: 'No data',\n  points: (size) => `${size} pts`,\n  ofTarget: (share, target) => `${share} of ${target}`,\n  achieved: 'Achieved',\n  onTrack: 'On track',\n  behind: 'Behind pace',\n  toGo: (left) => `${left} to go`,\n  left: (left) => `${left} left`,\n  over: (by) => `Over by ${by}`,\n  overPace: 'Over pace',\n  live: 'Live',\n  soFar: 'so far',\n}\n\ninterface KpiContextValue {\n  value: number | null\n  previous: number | null\n  locale: Intl.LocalesArgument\n  format: Intl.NumberFormatOptions | undefined\n  better: KpiBetter\n  loading: boolean\n  labelId: string\n  messages: KpiMessages\n}\n\nconst KpiContext = createContext<KpiContextValue | null>(null)\n\nfunction useKpi() {\n  const kpi = use(KpiContext)\n  if (!kpi) throw new Error('KPI parts go inside a `Kpi`.')\n  return kpi\n}\n\n/** The decimals a change is written with below 10%, where a tenth still matters. */\nconst CHANGE_DECIMALS = 1\n\n/**\n * The size of the change from `previous` to `value`, measured as `kind`\n * says, which way it went, and whether that is good news. A change too small\n * to show at the decimals it is written with is flat, so a badge never reads\n * \"0.0%\" in red or \"$0\" in green. With nothing to compare with (no value\n * before, or a zero before a share), the size is null and the direction `none`.\n */\nfunction kpiChange(\n  value: number | null,\n  previous: number | null,\n  kind: KpiChangeKind,\n  better: KpiBetter,\n  /** The decimals an amount is written with, from the KPI's format. */\n  amountDecimals = 2,\n) {\n  const exact =\n    value === null || previous === null\n      ? null\n      : kind === 'percent'\n        ? previous === 0\n          ? null\n          : (value - previous) / Math.abs(previous)\n        : kind === 'points'\n          ? (value - previous) * 100\n          : value - previous\n  const decimals =\n    exact === null\n      ? 0\n      : kind === 'percent'\n        ? Math.abs(exact) < 0.1\n          ? 3\n          : 2\n        : kind === 'amount'\n          ? amountDecimals\n          : // Points are written to a tenth, and to a hundredth below a tenth (pointsFormat).\n            Math.abs(exact) < 0.1\n            ? 2\n            : CHANGE_DECIMALS\n  const size =\n    exact === null\n      ? null\n      : (Math.sign(exact) * Math.round(Math.abs(exact) * 10 ** decimals)) / 10 ** decimals\n  const direction: KpiDirection =\n    size === null ? 'none' : size > 0 ? 'up' : size < 0 ? 'down' : 'flat'\n  const tone: KpiTone =\n    better === 'neither' || direction === 'flat' || direction === 'none'\n      ? 'neutral'\n      : (direction === 'up') === (better === 'higher')\n        ? 'positive'\n        : 'negative'\n  return { size, direction, tone }\n}\n\n/** How a share is written: with its decimal below 10%, whole from 10% up, as 18% and 250% read. */\nfunction shareFormat(share: number): Intl.NumberFormatOptions {\n  const decimals = Math.abs(share) < 0.1 && share !== 0 ? CHANGE_DECIMALS : 0\n  return {\n    style: 'percent',\n    minimumFractionDigits: decimals,\n    maximumFractionDigits: decimals,\n  }\n}\n\n/** How a change's size is written, as the badge writes it: a share, the difference in the KPI's format, or points. */\nfunction changeFormat(\n  kind: KpiChangeKind,\n  size: number,\n  format?: Intl.NumberFormatOptions,\n): Intl.NumberFormatOptions {\n  return kind === 'points'\n    ? pointsFormat(size)\n    : kind === 'amount'\n      ? amountFormat(format)\n      : shareFormat(size)\n}\n\n/** The KPI's own format, written as a difference: the same unit and currency, with no sign, since the arrow says it. */\nfunction amountFormat(\n  format: Intl.NumberFormatOptions | undefined,\n): Intl.NumberFormatOptions {\n  return { ...format, signDisplay: 'never' }\n}\n\nfunction Kpi({\n  value,\n  previous = null,\n  locale,\n  format,\n  better = 'higher',\n  loading = false,\n  messages,\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof Card>, 'children'> & {\n  /** The number now, or null with no data for the period. */\n  value: number | null\n  /** The number the period before, which the change and the trend compare with. */\n  previous?: number | null\n  /** The locale the numbers are written in. Give one, so the page's server and browser agree. */\n  locale?: Intl.LocalesArgument\n  /** How the value is written: a currency, a percentage, a unit, compact. */\n  format?: Intl.NumberFormatOptions\n  /** Which way of moving is good news. */\n  better?: KpiBetter\n  /** Shows each part's placeholder while the number loads. */\n  loading?: boolean\n  /** The words it says, for another language. */\n  messages?: Partial<KpiMessages>\n  children?: ReactNode\n}) {\n  const labelId = useId()\n  return (\n    <KpiContext\n      value={{\n        value,\n        previous,\n        locale,\n        format,\n        better,\n        loading,\n        labelId,\n        messages: { ...kpiMessages, ...messages },\n      }}\n    >\n      <Card\n        data-slot='kpi'\n        aria-busy={loading || undefined}\n        className={className}\n        {...props}\n      >\n        {children}\n      </Card>\n    </KpiContext>\n  )\n}\n\n/** The label and an action at its end, such as a period picker. */\nfunction KpiHeader({ className, ...props }: ComponentProps<typeof CardHeader>) {\n  return (\n    <CardHeader\n      data-slot='kpi-header'\n      className={cn('items-center', className)}\n      {...props}\n    />\n  )\n}\n\n/** What the number is: the card's title, which names the meters and charts below it. */\nfunction KpiLabel({ className, ...props }: ComponentProps<typeof CardTitle>) {\n  const { labelId } = useKpi()\n  return (\n    <CardTitle\n      data-slot='kpi-label'\n      className={cn('text-muted-foreground text-sm font-medium', className)}\n      {...props}\n      // The meters and charts below are named by it, so its id is the KPI's own.\n      id={labelId}\n    />\n  )\n}\n\n/** An action at the label's end, in the label's row, so it never makes the header taller. */\nfunction KpiAction({ className, ...props }: ComponentProps<typeof CardAction>) {\n  return (\n    <CardAction\n      data-slot='kpi-action'\n      className={cn('row-span-1 -my-2 self-center', className)}\n      {...props}\n    />\n  )\n}\n\n/**\n * The figure and the picture under it. It takes the card's spare height and\n * the picture sits at its foot, so in a row of KPIs the numbers line up at\n * the top and the pictures at the bottom.\n */\nfunction KpiContent({ className, ...props }: ComponentProps<typeof CardContent>) {\n  return (\n    <CardContent\n      data-slot='kpi-content'\n      className={cn(\n        'flex flex-1 flex-col gap-4 *:not-first:data-[slot^=kpi-]:mt-auto',\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\nfunction KpiFigure({ className, ...props }: ComponentProps<'div'>) {\n  return (\n    <div\n      data-slot='kpi-figure'\n      className={cn('flex flex-col items-start gap-2', className)}\n      {...props}\n    />\n  )\n}\n\n// The colour comes from around it; the size stays the same across a row of KPIs.\nconst kpiValueVariants = cva('leading-none font-medium tracking-tight tabular-nums', {\n  variants: {\n    size: {\n      sm: 'text-xl',\n      default: 'text-3xl',\n      lg: 'text-5xl',\n    },\n  },\n  defaultVariants: { size: 'default' },\n})\n\n/** The number, rolling each digit that changes to its new one. */\nfunction KpiValue({\n  className,\n  size,\n  ...props\n}: Omit<ComponentProps<'span'>, 'children'> & VariantProps<typeof kpiValueVariants>) {\n  const { value, locale, format, loading, messages } = useKpi()\n  return (\n    <SkeletonContent\n      loading={loading}\n      placeholder={<SkeletonText className={cn(kpiValueVariants({ size }), 'w-32')} />}\n      className={cn(kpiValueVariants({ size }), className)}\n    >\n      {value === null ? (\n        <span data-slot='kpi-value' className='text-muted-foreground' {...props}>\n          <span aria-hidden>—</span>\n          <span className='sr-only'>{messages.noData}</span>\n        </span>\n      ) : (\n        <AnimatedNumber\n          data-slot='kpi-value'\n          value={value}\n          locale={locale}\n          format={format}\n          {...props}\n        />\n      )}\n    </SkeletonContent>\n  )\n}\n\n/** The arrow's turn from pointing up and on: no change points on, down points down and on. */\n/** Mirrored in right to left, the arrow turns the other way to still point down or on. */\nconst ARROW_TURN: Record<KpiDirection, string> = {\n  up: 'rotate-0',\n  flat: 'rotate-45 rtl:-rotate-45',\n  down: 'rotate-90 rtl:-rotate-90',\n  none: 'rotate-45 rtl:-rotate-45',\n}\n\nconst BADGE_OF: Record<KpiTone, 'success' | 'warning' | 'destructive' | 'secondary'> = {\n  positive: 'success',\n  warning: 'warning',\n  negative: 'destructive',\n  neutral: 'secondary',\n}\n\n/**\n * The change since the period before, as a badge: an arrow that turns to\n * the new direction and the size of the change, rolling, in green when it is\n * good news and red when it isn't. Its children say what it compares with,\n * such as \"vs October\", and read as one sentence with it.\n */\nfunction KpiChange({\n  kind = 'percent',\n  className,\n  children,\n  ...props\n}: ComponentProps<'div'> & {\n  /** How the change is measured: a share, the difference, or percentage points for a rate. */\n  kind?: KpiChangeKind\n}) {\n  const { value, previous, locale, format, better, loading, messages } = useKpi()\n  const { size, direction, tone } = kpiChange(\n    value,\n    previous,\n    kind,\n    better,\n    numberFormatter(locale, amountFormat(format)).resolvedOptions().maximumFractionDigits,\n  )\n  const magnitude = size === null ? null : Math.abs(size)\n  // With no value, or none before to compare with, there is no change to show.\n  if ((value === null || previous === null) && !loading) return null\n  return (\n    <div\n      data-slot='kpi-change'\n      data-direction={direction}\n      data-tone={tone}\n      className={cn('flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm', className)}\n      {...props}\n    >\n      <SkeletonContent\n        loading={loading}\n        placeholder={<Skeleton className='h-5 w-14 rounded-(--control-radius-xs)' />}\n        className='shrink-0'\n      >\n        <Badge variant={BADGE_OF[tone]} className='gap-0.5 ps-1'>\n          <IconPlaceholder\n            lucide='ArrowUpRightIcon'\n            tabler='IconArrowUpRight'\n            hugeicons='ArrowUpRight01Icon'\n            phosphor='ArrowUpRightIcon'\n            remixicon='RiArrowRightUpLine'\n            aria-hidden\n            className={cn(\n              // Up and on is up and to the reading end, so right to left mirrors it.\n              'transition-[rotate] duration-(--motion-morph-duration) ease-(--motion-morph-easing) motion-reduce:transition-none rtl:-scale-x-100',\n              ARROW_TURN[direction],\n            )}\n          />\n          {/* With nothing before, the badge's own word says it: \"New\". */}\n          {direction !== 'none' && (\n            <span className='sr-only'>{messages[direction]} </span>\n          )}\n          {/* From a number to \"New\" and back, the words crossfade and the badge's width glides. */}\n          <ChangeMagnitudeContext value={{ magnitude, kind }}>\n            <Swap>\n              {magnitude === null ? (\n                <span key='none'>{messages.none}</span>\n              ) : (\n                <ChangeMagnitude key='amount' />\n              )}\n            </Swap>\n          </ChangeMagnitudeContext>\n        </Badge>\n      </SkeletonContent>\n      {children ? (\n        <span className='text-muted-foreground min-w-0'> {children}</span>\n      ) : null}\n    </div>\n  )\n}\n\nconst ChangeMagnitudeContext = createContext<{\n  magnitude: number | null\n  kind: KpiChangeKind\n}>({ magnitude: null, kind: 'percent' })\n\n/**\n * The change's size. It takes no props, so the Swap around it sees the same\n * content as the number changes, and the number rolls instead.\n */\nfunction ChangeMagnitude() {\n  const { magnitude, kind } = use(ChangeMagnitudeContext)\n  const { locale, format } = useKpi()\n  if (magnitude === null) return null\n  if (kind === 'points') return <PointsNumber size={magnitude} />\n  return (\n    <AnimatedNumber\n      value={magnitude}\n      locale={locale}\n      format={kind === 'amount' ? amountFormat(format) : shareFormat(magnitude)}\n    />\n  )\n}\n\n/**\n * How a change in points is written: to a tenth, as a rate's 2.6 pts, and to\n * a hundredth below a tenth, where an uptime's 0.03 pts still matters.\n */\nfunction pointsFormat(size: number): Intl.NumberFormatOptions {\n  const decimals = Math.abs(size) < 0.1 && size !== 0 ? 2 : CHANGE_DECIMALS\n  return { minimumFractionDigits: decimals, maximumFractionDigits: decimals }\n}\n\n/** A change in percentage points: the number rolls, the word after it stays. */\nfunction PointsNumber({ size }: { size: number }) {\n  const { locale, messages } = useKpi()\n  const [before, after] = messages.points('\\u0000').split('\\u0000')\n  // Isolated, so right to left keeps the number before its word: \"0.01 pts\".\n  return (\n    <bdi>\n      {before}\n      <AnimatedNumber value={size} locale={locale} format={pointsFormat(size)} />\n      {after}\n    </bdi>\n  )\n}\n\n/**\n * A line of small print at the foot, such as when the number was last\n * updated: at the card's bottom, so the footnotes of a row of KPIs line up.\n */\nfunction KpiFooter({ className, ...props }: ComponentProps<'p'>) {\n  return (\n    <p\n      data-slot='kpi-footer'\n      className={cn(\n        'text-muted-foreground mt-auto px-(--surface-padding) text-xs',\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n/** A live number's sign that it is live: a dot that breathes beside \"Live\". */\nfunction KpiLive({ className, children, ...props }: ComponentProps<'span'>) {\n  const { messages } = useKpi()\n  return (\n    <span\n      data-slot='kpi-live'\n      className={cn(\n        'text-success-foreground inline-flex items-center gap-1.5 text-xs font-medium',\n        className,\n      )}\n      {...props}\n    >\n      <LivePulse className='text-success size-2' />\n      {children ?? messages.live}\n    </span>\n  )\n}\n\ntype KpiTrendProps = Omit<\n  SparklineProps,\n  | 'label'\n  | 'locale'\n  | 'format'\n  | 'loading'\n  | 'config'\n  | 'dashed'\n  | 'forecastFrom'\n  | 'ordered'\n> & {\n  /** Names the trend, such as \"Revenue each day in November\". */\n  label: string\n  /** The key of each row's value in the period before, drawn dashed behind it, to compare with. */\n  compareKey?: string\n  /** The key of each row's value. */\n  dataKey: string\n  /** The value's name in the tooltip. */\n  dataLabel?: string\n  /** The period before's name in the tooltip. */\n  compareLabel?: string\n  /**\n   * Marks the last value as still coming in, such as the minute now running:\n   * dashed, and \"so far\" in the tooltip. The trend is a line then, since an\n   * area can't dash its last stretch.\n   */\n  partial?: boolean\n}\n\n/**\n * The value over its period, as a sparkline under the number, with the\n * period before dashed behind it to compare with. The day under the pointer\n * or the keys reads in a tooltip, never in place of the value. A new period\n * moves every point from where it was.\n */\nfunction KpiTrend({\n  dataKey,\n  dataLabel,\n  compareKey,\n  compareLabel,\n  partial = false,\n  variant = partial ? 'line' : 'area',\n  endDot = true,\n  className,\n  children,\n  messages,\n  ...props\n}: KpiTrendProps) {\n  const kpi = useKpi()\n  const last = props.data.at(-1)\n  return (\n    <Sparkline\n      data-slot='kpi-trend'\n      variant={variant}\n      endDot={endDot}\n      locale={kpi.locale}\n      format={kpi.format}\n      loading={kpi.loading}\n      config={{\n        ...(compareKey\n          ? {\n              [compareKey]: {\n                label: compareLabel ?? compareKey,\n                color: 'var(--muted-foreground)',\n              },\n            }\n          : {}),\n        [dataKey]: { label: dataLabel ?? dataKey },\n      }}\n      dashed={compareKey ? [compareKey] : []}\n      forecastFrom={partial && last ? String(last[props.index]) : undefined}\n      messages={{ forecast: kpi.messages.soFar, ...messages }}\n      ordered\n      fit\n      className={cn('h-16', className)}\n      {...props}\n    >\n      {/* Under the plot, so it never covers the number it explains. */}\n      {children ?? <ChartTooltip side='bottom' />}\n    </Sparkline>\n  )\n}\n\n/** The status of a value against its target, and what it says. */\nfunction targetStatus(\n  value: number,\n  target: number,\n  kind: 'goal' | 'limit',\n  pace: number | undefined,\n): {\n  status: 'achieved' | 'onTrack' | 'behind' | 'left' | 'overPace' | 'over' | 'toGo'\n  tone: KpiTone\n} {\n  // Where it ends at the pace it has kept so far.\n  const projected = pace && pace > 0 ? value / pace : null\n  if (kind === 'goal') {\n    if (value >= target) return { status: 'achieved', tone: 'positive' }\n    if (projected === null) return { status: 'toGo', tone: 'neutral' }\n    return projected >= target\n      ? { status: 'onTrack', tone: 'positive' }\n      : { status: 'behind', tone: 'warning' }\n  }\n  if (value > target) return { status: 'over', tone: 'negative' }\n  if (projected !== null && projected > target)\n    return { status: 'overPace', tone: 'warning' }\n  return { status: 'left', tone: 'positive' }\n}\n\nconst TONE_TEXT: Record<KpiTone, string> = {\n  positive: 'text-success-foreground',\n  warning: 'text-warning-foreground',\n  negative: 'text-destructive',\n  neutral: 'text-muted-foreground',\n}\n\n/** A tone's fill stepped back toward the track's colour, for the bands the value isn't in. */\nconst TONE_FILL_DIM: Record<KpiTone, string> = {\n  positive: 'bg-[color-mix(in_oklch,var(--success)_30%,var(--muted))]',\n  warning: 'bg-[color-mix(in_oklch,var(--warning)_30%,var(--muted))]',\n  negative: 'bg-[color-mix(in_oklch,var(--destructive)_30%,var(--muted))]',\n  neutral: 'bg-muted',\n}\n\nconst TONE_FILL: Record<KpiTone, string> = {\n  positive: 'bg-success',\n  warning: 'bg-warning',\n  negative: 'bg-destructive',\n  neutral: 'bg-muted-foreground/50',\n}\n\n/**\n * Progress to a target, as a bullet graph: a bar filled to the value, a\n * notch at the target, and a pale fill to where an even pace puts the value\n * now, which shows past the value's fill when it is behind, so \"behind\"\n * reads before the numbers do. A goal is good to\n * pass, such as a quota; a limit is not, such as a budget, whose fill turns\n * red past it. Past the target the scale grows, so the notch glides back to\n * make room. It is a meter, named by the KPI's label, that says its share,\n * its status and what is left.\n */\nfunction KpiTarget({\n  target,\n  kind = 'goal',\n  pace,\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  /** The goal to reach, or the limit to stay under. */\n  target: number\n  /** Whether passing the target is good news (a goal) or bad news (a limit). */\n  kind?: 'goal' | 'limit'\n  /** How much of the period has gone, from 0 to 1: where an even pace puts the value now. */\n  pace?: number\n}) {\n  const { value, locale, format, loading, labelId, messages } = useKpi()\n  const now = value ?? 0\n  const max = Math.max(target, now)\n  const filled = valuePercent(now, 0, max)\n  const notch = valuePercent(target, 0, max)\n  // With no value there is no status to give: the bar stays empty and says so.\n  const empty = value === null\n  const { status, tone } = empty\n    ? ({ status: 'noData', tone: 'neutral' } as const)\n    : targetStatus(now, target, kind, pace)\n  // A period that has ended has no pace left to keep.\n  const showsPace = !loading && !empty && pace !== undefined && pace < 1\n  const pacePercent = valuePercent(target * Math.min(1, pace ?? 0), 0, max)\n  const write = numberFormatter(locale, format)\n  const share = target > 0 ? now / target : 0\n  const shareText = numberFormatter(locale, shareFormat(share)).format(share)\n  const left = write.format(Math.abs(target - now))\n  const statusText =\n    status === 'noData'\n      ? messages.noData\n      : status === 'achieved'\n        ? messages.achieved\n        : status === 'onTrack'\n          ? messages.onTrack\n          : status === 'behind'\n            ? messages.behind\n            : status === 'toGo'\n              ? messages.toGo(left)\n              : status === 'over'\n                ? messages.over(left)\n                : status === 'overPace'\n                  ? messages.overPace\n                  : messages.left(left)\n  const ofText = messages.ofTarget(shareText, write.format(target))\n  return (\n    <div\n      data-slot='kpi-target'\n      data-kind={kind}\n      data-status={status}\n      className={cn('flex flex-col gap-2', trackDirClassName, className)}\n      {...props}\n    >\n      <MeterPrimitive\n        value={now}\n        min={0}\n        max={max}\n        aria-labelledby={labelId}\n        getValueLabel={() => (empty ? statusText : `${ofText}, ${statusText}`)}\n        // Room above and below the bar for the target's notch.\n        className='relative py-1'\n      >\n        <MeterTrackPrimitive\n          className={cn(\n            trackClassName,\n            'overflow-hidden',\n            loading && placeholderFillClassName,\n          )}\n        >\n          {showsPace && (\n            // The stretch an even pace has reached and the value hasn't: a\n            // pale fill, which the value's own fill covers when it is ahead.\n            <span\n              aria-hidden\n              style={slidingFillStyle(pacePercent)}\n              className={cn(\n                slidingFillClassName,\n                'bg-foreground/15 forced-colors:bg-[GrayText]!',\n              )}\n            />\n          )}\n          {!loading && !empty && (\n            <span\n              aria-hidden\n              data-slot='kpi-target-fill'\n              style={slidingFillStyle(filled)}\n              className={cn(\n                slidingFillClassName,\n                tone === 'neutral' ? 'bg-primary' : TONE_FILL[tone],\n              )}\n            />\n          )}\n          {showsPace && (\n            // Where an even pace puts the value now: a gap cut through the\n            // bar, so it shows on the fill as well as past it.\n            <span\n              aria-hidden\n              data-slot='kpi-target-pace'\n              style={slidingFillStyle(pacePercent)}\n              className={slidingMarkClassName}\n            >\n              <span className='bg-card -me-px h-full w-0.5 forced-colors:bg-[Canvas]' />\n            </span>\n          )}\n        </MeterTrackPrimitive>\n        {!loading && (\n          <>\n            {/* The target: a notch cut through the bar, standing past it above and below. */}\n            <span\n              aria-hidden\n              style={slidingFillStyle(notch)}\n              className={slidingMarkClassName}\n            >\n              {/* Ringed in the card's colour, so it cuts through a fill that has passed it. */}\n              <span className='bg-foreground ring-card -me-px h-full w-0.5 rounded-full ring-2 forced-colors:bg-[CanvasText]' />\n            </span>\n          </>\n        )}\n      </MeterPrimitive>\n      <div className='flex min-w-0 flex-wrap items-center justify-between gap-x-3 gap-y-0.5 text-xs'>\n        {loading ? (\n          <SkeletonText className='w-28' />\n        ) : empty ? null : (\n          <span className='text-muted-foreground tabular-nums'>{ofText}</span>\n        )}\n        {loading ? null : (\n          <span\n            data-slot='kpi-target-status'\n            className={cn(\n              'flex font-medium tabular-nums transition-colors duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)',\n              TONE_TEXT[tone],\n            )}\n          >\n            <SwapText text={statusText} />\n          </span>\n        )}\n      </div>\n    </div>\n  )\n}\n\ninterface KpiBand {\n  /** Where the band ends; the last band runs to the scale's end and needs none. */\n  to?: number\n  label: string\n  tone: KpiTone\n}\n\n/** Each band's start and end, from `min` to `max`, and the one `value` sits in. */\nfunction bandsOf(\n  bands: readonly KpiBand[],\n  min: number,\n  max: number,\n  value: number | null,\n) {\n  let start = min\n  const laid = bands.map((band, index) => {\n    const end = index === bands.length - 1 ? max : Math.min(max, band.to ?? max)\n    const span = { ...band, start, end }\n    start = end\n    return span\n  })\n  const at =\n    value === null\n      ? -1\n      : laid.findIndex((band, index) => value < band.end || index === laid.length - 1)\n  return { laid, at }\n}\n\n/**\n * A score on its scale of bands, such as a page's load time: Good, Needs\n * improvement, Poor. The bar is split into its bands, in their colours, the\n * one the value is in at full strength; a marker sits at the value and\n * glides to a new one, and the band's name under the bar says which it is\n * in, in words as well as in colour, swapping as the marker crosses into\n * another. It is a meter that says the value and its band.\n */\nfunction KpiScore({\n  bands,\n  min = 0,\n  max,\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  /** The bands from the scale's start, each ending where the next begins. */\n  bands: readonly KpiBand[]\n  min?: number\n  max: number\n}) {\n  const { value, locale, format, loading, labelId, messages } = useKpi()\n  const { laid, at } = bandsOf(bands, min, max, value)\n  const write = numberFormatter(locale, format)\n  const current = laid[at]\n  return (\n    <div\n      data-slot='kpi-score'\n      className={cn('flex flex-col gap-2', trackDirClassName, className)}\n      {...props}\n    >\n      {/* The band it is in, in words: they change as the marker crosses into another. */}\n      <div aria-hidden className='flex text-xs'>\n        {loading ? (\n          <SkeletonText className='w-16' />\n        ) : current ? (\n          <span\n            data-slot='kpi-score-band'\n            className={cn(\n              'flex font-medium transition-colors duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)',\n              TONE_TEXT[current.tone],\n            )}\n          >\n            <SwapText text={current.label} />\n          </span>\n        ) : null}\n      </div>\n      <MeterPrimitive\n        value={Math.min(max, Math.max(min, value ?? min))}\n        min={min}\n        max={max}\n        aria-labelledby={labelId}\n        getValueLabel={() =>\n          value === null || !current\n            ? messages.noData\n            : `${write.format(value)}, ${current.label}`\n        }\n        className='relative py-1'\n      >\n        <MeterTrackPrimitive\n          className={cn(\n            trackClassName,\n            'flex gap-0.5 bg-transparent forced-colors:outline-0',\n          )}\n        >\n          {laid.map((band, index) => (\n            <span\n              key={band.label}\n              aria-hidden\n              style={{ flexGrow: band.end - band.start }}\n              className={cn(\n                'h-full basis-0 transition-colors duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) first:rounded-s-full last:rounded-e-full forced-colors:bg-[GrayText]!',\n                loading\n                  ? placeholderFillClassName\n                  : index === at\n                    ? TONE_FILL[band.tone]\n                    : TONE_FILL_DIM[band.tone],\n                index === at && 'forced-colors:bg-[Highlight]!',\n              )}\n            />\n          ))}\n        </MeterTrackPrimitive>\n        {!loading && value !== null && (\n          <span\n            aria-hidden\n            data-slot='kpi-score-marker'\n            style={slidingFillStyle(valuePercent(value, min, max))}\n            className={cn(slidingMarkClassName, 'items-center')}\n          >\n            {/* The marker: a ring in the card's colour around the value's place. */}\n            <span className='bg-foreground ring-card -me-1.5 size-3 rounded-full ring-2 forced-colors:bg-[CanvasText]' />\n          </span>\n        )}\n      </MeterPrimitive>\n      {/* Where each band ends, under the joins, so how close the value is to the next reads. */}\n      <div\n        aria-hidden\n        className='text-muted-foreground relative h-4 text-xs tabular-nums'\n      >\n        {laid.slice(0, -1).map((band) => (\n          <span\n            key={band.label}\n            style={{ insetInlineStart: `${valuePercent(band.end, min, max)}%` }}\n            className='absolute top-0 -translate-x-1/2 whitespace-nowrap rtl:translate-x-1/2'\n          >\n            {loading ? null : write.format(band.end)}\n          </span>\n        ))}\n      </div>\n    </div>\n  )\n}\n\ninterface KpiPart {\n  key: string\n  label: string\n  value: number\n  /** Its colour, from the status colours; the charts' colours in turn by default. */\n  tone?: KpiTone\n}\n\n/** Where each part ends along the bar, as a percentage of the whole, from the start. */\nfunction partEnds(parts: readonly KpiPart[]): number[] {\n  const total = parts.reduce((sum, part) => sum + Math.max(0, part.value), 0)\n  let reached = 0\n  return parts.map((part) => {\n    reached += Math.max(0, part.value)\n    return total > 0 ? (reached / total) * 100 : 0\n  })\n}\n\n/**\n * Each value's share of their total, rounded to `decimals` of a percent so\n * that they still add up to the whole: the shares that lost most to rounding\n * get the units left over, as a legend's 87%, 8% and 5% must make 100%.\n */\nfunction sharesOf(values: readonly number[], decimals: number): number[] {\n  const kept = values.map((value) => Math.max(0, value))\n  const total = kept.reduce((sum, value) => sum + value, 0)\n  if (total === 0) return kept.map(() => 0)\n  // The units a share is counted in: a percent, or a tenth of one with a decimal.\n  const units = 100 * 10 ** decimals\n  const exact = kept.map((value) => (value / total) * units)\n  const floors = exact.map(Math.floor)\n  let left = units - floors.reduce((sum, value) => sum + value, 0)\n  const order = exact\n    .map((value, index) => ({ index, lost: value - Math.floor(value) }))\n    .toSorted((a, b) => b.lost - a.lost)\n  for (const { index } of order) {\n    if (left <= 0) break\n    floors[index] = (floors[index] ?? 0) + 1\n    left -= 1\n  }\n  return floors.map((value) => value / units)\n}\n\n/** The charts' colours, in turn, for parts with no tone. */\nconst CHART_FILL = ['bg-chart-1', 'bg-chart-2', 'bg-chart-3', 'bg-chart-4', 'bg-chart-5']\n\nfunction partColor(part: KpiPart, index: number) {\n  return part.tone ? TONE_FILL[part.tone] : CHART_FILL[index % CHART_FILL.length]\n}\n\n/**\n * A whole and its parts, such as the tickets that met their deadline and the\n * ones that missed it: one bar split into the parts, and a legend with each\n * part's count and share. Each part is a fill from the bar's start to its\n * end, laid over the ones after it, so a new count slides every end along\n * on the compositor and the parts make room for each other.\n */\nfunction KpiBreakdown({\n  parts,\n  partFormat,\n  className,\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  parts: readonly KpiPart[]\n  /** How each part's own count is written, such as a currency for revenue by plan. */\n  partFormat?: Intl.NumberFormatOptions\n}) {\n  const { locale, format, loading } = useKpi()\n  const ends = partEnds(parts)\n  // Shares written as the value is when it is a share too, so a 93.8% value reads 93.8% beside its part.\n  const shareOf: Intl.NumberFormatOptions =\n    format?.style === 'percent' ? format : { style: 'percent', maximumFractionDigits: 0 }\n  const shares = sharesOf(\n    parts.map((part) => part.value),\n    numberFormatter(locale, shareOf).resolvedOptions().maximumFractionDigits ?? 0,\n  )\n  return (\n    <div\n      data-slot='kpi-breakdown'\n      className={cn('flex flex-col gap-3', trackDirClassName, className)}\n      {...props}\n    >\n      <div\n        aria-hidden\n        className={cn(\n          trackClassName,\n          'isolate overflow-hidden',\n          loading && placeholderFillClassName,\n        )}\n      >\n        {!loading &&\n          parts.map((part, index) => (\n            <span\n              key={part.key}\n              style={{\n                ...slidingFillStyle(ends[index] ?? 0),\n                zIndex: parts.length - index,\n              }}\n              className={cn(\n                slidingFillClassName,\n                // The gap before the next part, in the card's colour.\n                'border-card rounded-none border-e-2 last:border-e-0 forced-colors:border-[Canvas]',\n                partColor(part, index),\n              )}\n            />\n          ))}\n      </div>\n      <ul className='text-muted-foreground flex flex-col gap-1 text-xs'>\n        {parts.map((part, index) => (\n          <li key={part.key} className='flex min-w-0 items-center gap-2'>\n            <span\n              aria-hidden\n              className={cn(\n                swatchClassName,\n                'forced-colors:bg-[CanvasText]!',\n                partColor(part, index),\n              )}\n            />\n            <span className='min-w-0 flex-1 wrap-break-word'>{part.label}</span>\n            {loading ? (\n              <SkeletonText className='w-16' />\n            ) : (\n              <>\n                <AnimatedNumber\n                  value={part.value}\n                  locale={locale}\n                  format={partFormat}\n                  className='text-muted-foreground'\n                />\n                <AnimatedNumber\n                  value={shares[index] ?? 0}\n                  locale={locale}\n                  format={shareOf}\n                  className='text-foreground min-w-10 text-end font-medium'\n                />\n              </>\n            )}\n          </li>\n        ))}\n      </ul>\n    </div>\n  )\n}\n\n/** A day's state in a strip of days. */\ntype KpiDayState = 'up' | 'degraded' | 'down' | 'none'\n\ninterface KpiHistoryMessages {\n  /** Heads the data table's column of states. */\n  state: string\n  up: string\n  degraded: string\n  down: string\n  none: string\n}\n\nconst kpiHistoryMessages: KpiHistoryMessages = {\n  state: 'Status',\n  up: 'Operational',\n  degraded: 'Degraded',\n  down: 'Outage',\n  none: 'No data',\n}\n\n/** The colour of each day's state. */\nconst DAY_COLOR: Record<KpiDayState, string> = {\n  up: 'var(--success)',\n  degraded: 'var(--warning)',\n  down: 'var(--destructive)',\n  none: 'var(--muted)',\n}\n\n/** The strip's rows: every day a full bar, coloured by its state. */\nfunction historyRows(\n  days: readonly { date: string; state: KpiDayState }[],\n): ChartDatum[] {\n  return days.map(({ date, state }) => ({ date, day: 1, state }))\n}\n\n/**\n * The state of each day in a period, as a strip of bars, a bar a day, such\n * as a service's uptime: green when all was well, amber when it was slow,\n * red when it was down. It is the Bar chart, so the day under the pointer\n * stays bright while the rest step back and its state reads in a tooltip,\n * and the strip is a slider the keys step through, day by day, each day\n * read as its state.\n */\nfunction KpiHistory({\n  days,\n  messages,\n  categoryFormat = String,\n  className,\n  ...props\n}: Omit<\n  BarChartProps,\n  | 'data'\n  | 'index'\n  | 'config'\n  | 'stack'\n  | 'domain'\n  | 'locale'\n  | 'loading'\n  | 'describe'\n  | 'children'\n> & {\n  days: readonly { date: string; state: KpiDayState }[]\n  messages?: Partial<KpiHistoryMessages>\n}) {\n  const { locale, loading } = useKpi()\n  const words = { ...kpiHistoryMessages, ...messages }\n  const stateText = (datum: ChartDatum) => words[(datum.state as KpiDayState) ?? 'none']\n  const rows = useMemo(() => historyRows(days), [days])\n  if (loading) {\n    // A strip of days has no shape to hint at, so it waits as one flat bar.\n    return <Skeleton data-slot='kpi-history' className={cn('h-9 w-full', className)} />\n  }\n  return (\n    <BarChart\n      data-slot='kpi-history'\n      ordered\n      categoryGap={0.3}\n      categoryFormat={categoryFormat}\n      {...props}\n      data={rows}\n      index='date'\n      locale={locale}\n      domain={[0, 1]}\n      describe={{ name: words.state, text: stateText }}\n      config={{ day: { label: words.state, color: DAY_COLOR.up } }}\n      className={cn('h-9 grid-cols-[0_minmax(0,1fr)_0] py-0', className)}\n    >\n      <Bar\n        dataKey='day'\n        color={(datum) => DAY_COLOR[(datum.state as KpiDayState) ?? 'none']}\n      />\n      <ChartTooltip side='bottom'>\n        {({ category: { value, datum } }) => (\n          <div className='grid gap-0.5'>\n            <div className='font-medium'>{categoryFormat(value)}</div>\n            {datum && (\n              <div className='text-background/75 forced-colors:text-[CanvasText]'>\n                {stateText(datum)}\n              </div>\n            )}\n          </div>\n        )}\n      </ChartTooltip>\n    </BarChart>\n  )\n}\n\nexport {\n  bandsOf,\n  changeFormat,\n  Kpi,\n  KpiAction,\n  type KpiBand,\n  type KpiBetter,\n  KpiBreakdown,\n  KpiChange,\n  type KpiChangeKind,\n  kpiChange,\n  KpiContent,\n  type KpiDayState,\n  KpiFigure,\n  KpiFooter,\n  KpiHeader,\n  KpiHistory,\n  KpiLabel,\n  KpiLive,\n  type KpiPart,\n  KpiScore,\n  KpiTarget,\n  type KpiTone,\n  KpiTrend,\n  KpiValue,\n  partEnds,\n  pointsFormat,\n  sharesOf,\n  targetStatus,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/kpi.tsx"
    }
  ],
  "type": "registry:component"
}