{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "latency-histogram",
  "type": "registry:component",
  "title": "Latency histogram",
  "description": "A request latency distribution with percentile markers, a shaded SLO tail, a comparison series, and brushing to measure any range.",
  "categories": [
    "charts"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/latency-histogram.tsx",
      "type": "registry:component",
      "target": "components/overtrue/latency-histogram.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconX as X } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LatencyScale = \"linear\" | \"log\";\n\nexport type LatencyRange = [min: number, max: number];\n\nexport interface LatencyBucket {\n  /** Inclusive lower edge. */\n  start: number;\n  /** Exclusive upper edge. */\n  end: number;\n  count: number;\n}\n\n/** One bar as drawn, passed to `renderTooltip`. */\nexport interface LatencyHistogramBucket extends LatencyBucket {\n  index: number;\n  /** Share of all requests in this bucket, 0–1. */\n  share: number;\n  /** Share of requests at or below this bucket's upper edge, 0–1. */\n  cumulative: number;\n  /** Raw comparison count in the same range, when `compare` is set. */\n  compare?: number;\n  /** Comparison share of its own total, 0–1. */\n  compareShare?: number;\n  /** The catch-all bar for values past the linear domain. */\n  overflow: boolean;\n  /** Whether the bucket lies past `threshold`. */\n  overThreshold: boolean;\n}\n\nexport interface LatencyHistogramColors {\n  bar: string;\n  compare: string;\n  threshold: string;\n  marker: string;\n  selection: string;\n}\n\nexport interface LatencyHistogramProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"color\"\n> {\n  /** Raw samples. Bucketed for you, with exact percentiles. */\n  values?: number[];\n  /** Pre-bucketed counts, used when `values` is not given. Percentiles are interpolated. */\n  buckets?: LatencyBucket[];\n  /** A comparison distribution, e.g. yesterday. Scaled to the main total so shapes compare. */\n  compare?: number[] | LatencyBucket[];\n  /** Name of the comparison in the legend and tooltip. */\n  compareLabel?: string;\n  /** Name of the main series in the legend. */\n  seriesLabel?: string;\n  /** Draw the comparison as a stepped line or as outlined bars. */\n  compareStyle?: \"step\" | \"outline\";\n  /** Percentiles to mark, as numbers such as 50 or 99.9. */\n  percentiles?: number[];\n  /** Latency objective. The slow tail past it is shaded and measured. */\n  threshold?: number;\n  thresholdLabel?: string;\n  /** X scale. Pass with `onScaleChange` to control the built-in toggle. */\n  scale?: LatencyScale;\n  defaultScale?: LatencyScale;\n  onScaleChange?: (scale: LatencyScale) => void;\n  /** Show the linear/log toggle. Defaults to true. */\n  showScaleToggle?: boolean;\n  /** Brushed range. Pass `null` for none; leave undefined to let the component manage it. */\n  range?: LatencyRange | null;\n  defaultRange?: LatencyRange | null;\n  onRangeChange?: (range: LatencyRange | null) => void;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, before the scale toggle. */\n  actions?: React.ReactNode;\n  /** Unit of the values. Defaults to \"ms\"; ms readouts switch to seconds from 1,000. */\n  unit?: string;\n  /** Formats latencies in readouts, markers, and ticks. */\n  valueFormatter?: (value: number) => string;\n  /** Target number of bars. Defaults to 40. */\n  bucketCount?: number;\n  /** Fix the latency domain. Linear charts otherwise end near p99.5 and gather the rest in an overflow bar. */\n  domain?: LatencyRange;\n  /** Plot height in pixels. Defaults to a third of the plot width, between 140 and 220. */\n  height?: number;\n  /** Override any series color with a CSS color. */\n  colors?: Partial<LatencyHistogramColors>;\n  /** Replaces the hover tooltip content. */\n  renderTooltip?: (bucket: LatencyHistogramBucket) => React.ReactNode;\n  /** Show the percentile summary above the plot. Defaults to true. */\n  showSummary?: boolean;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nconst tidy = (value: number) => +value.toPrecision(12);\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst whole = new Intl.NumberFormat(\"en-US\");\n\nfunction makeFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  const join = (text: string, u: string) =>\n    u ? `${text}${tight ? \"\" : \" \"}${u}` : text;\n  return (value: number) => {\n    if (!Number.isFinite(value)) return \"—\";\n    const a = Math.abs(value);\n    if (unit === \"ms\" && a >= 1000)\n      return `${tidy(+(value / 1000).toFixed(a >= 10_000 ? 1 : 2))}s`;\n    const digits = a >= 100 || a === 0 ? 0 : a >= 10 ? 1 : a >= 1 ? 2 : 3;\n    return join(String(tidy(+value.toFixed(digits))), unit);\n  };\n}\n\nfunction makeTickFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  return (value: number) => {\n    if (value === 0) return \"0\";\n    if (unit === \"ms\" && Math.abs(value) >= 1000)\n      return `${tidy(value / 1000)}s`;\n    return `${tidy(value)}${tight ? \"\" : \" \"}${unit}`;\n  };\n}\n\nfunction percentLabel(share: number) {\n  const pct = share * 100;\n  if (pct === 0) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  if (pct > 99.9 && pct < 100) return \">99.9%\";\n  return `${pct >= 10 ? pct.toFixed(1) : pct.toFixed(2)}%`;\n}\n\nfunction niceStep(raw: number) {\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Round down or up to the nearest 1, 2, or 5 times a power of ten. */\nfunction nice125(value: number, up: boolean) {\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const r = value / magnitude;\n  const steps = [1, 2, 5, 10];\n  if (up) return (steps.find((s) => s >= r - 1e-9) ?? 10) * magnitude;\n  return ([...steps].reverse().find((s) => s <= r + 1e-9) ?? 1) * magnitude;\n}\n\nfunction lowerBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] < value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\nfunction upperBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] <= value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Bar extends LatencyBucket {\n  overflow: boolean;\n  /** Left and right edges as 0–1 positions. */\n  x0: number;\n  x1: number;\n}\n\ninterface Distribution {\n  sorted: Float64Array | null;\n  buckets: LatencyBucket[] | null;\n  total: number;\n  min: number;\n  max: number;\n  mean: number;\n}\n\nfunction distributionOf(\n  values?: number[],\n  buckets?: LatencyBucket[],\n): Distribution {\n  if (values) {\n    const clean = values.filter((value) => Number.isFinite(value));\n    const sorted = Float64Array.from(clean).sort();\n    let sum = 0;\n    for (const value of sorted) sum += value;\n    return {\n      sorted,\n      buckets: null,\n      total: sorted.length,\n      min: sorted.length ? sorted[0] : 0,\n      max: sorted.length ? sorted[sorted.length - 1] : 0,\n      mean: sorted.length ? sum / sorted.length : 0,\n    };\n  }\n  const list = (buckets ?? [])\n    .filter(\n      (b) =>\n        Number.isFinite(b.start) && Number.isFinite(b.end) && b.end > b.start,\n    )\n    .sort((a, b) => a.start - b.start);\n  let total = 0;\n  let sum = 0;\n  for (const b of list) {\n    total += Math.max(0, b.count);\n    sum += (Math.max(0, b.count) * (b.start + b.end)) / 2;\n  }\n  return {\n    sorted: null,\n    buckets: list,\n    total,\n    min: list.length ? list[0].start : 0,\n    max: list.length ? list[list.length - 1].end : 0,\n    mean: total ? sum / total : 0,\n  };\n}\n\n/** Nearest-rank percentile from samples; interpolated inside buckets otherwise. */\nfunction quantile(d: Distribution, p: number) {\n  if (!d.total) return 0;\n  if (d.sorted)\n    return d.sorted[\n      Math.min(d.total - 1, Math.max(0, Math.ceil(p * d.total) - 1))\n    ];\n  const target = p * d.total;\n  let cumulative = 0;\n  for (const b of d.buckets!) {\n    if (cumulative + b.count >= target && b.count > 0)\n      return b.start + ((target - cumulative) / b.count) * (b.end - b.start);\n    cumulative += b.count;\n  }\n  return d.max;\n}\n\n/** Requests with a value in [a, b]. Partial buckets count in proportion. */\nfunction countBetween(d: Distribution, a: number, b: number) {\n  if (d.sorted) return upperBound(d.sorted, b) - lowerBound(d.sorted, a);\n  let count = 0;\n  for (const bucket of d.buckets!) {\n    const overlap = Math.min(b, bucket.end) - Math.max(a, bucket.start);\n    if (overlap > 0)\n      count += (bucket.count * overlap) / (bucket.end - bucket.start);\n  }\n  return count;\n}\n\nfunction countAbove(d: Distribution, value: number) {\n  if (d.sorted) return d.total - upperBound(d.sorted, value);\n  return countBetween(d, value, Infinity);\n}\n\ninterface Layout {\n  bars: Bar[];\n  lo: number;\n  hi: number;\n  /** Largest value covered, including the overflow bar. */\n  top: number;\n  pos: (value: number) => number;\n  inv: (x: number) => number;\n}\n\nfunction layoutOf(\n  d: Distribution,\n  scale: LatencyScale,\n  bucketCount: number,\n  reach: number,\n  domain?: LatencyRange,\n): Layout {\n  const count = Math.max(4, Math.round(bucketCount));\n  // Pre-bucketed data keeps its own edges.\n  if (d.buckets) {\n    const list = d.buckets;\n    const first = list[0]?.start ?? 0;\n    const last = list[list.length - 1]?.end ?? 1;\n    if (scale === \"log\") {\n      const positive =\n        list.find((b) => b.start > 0)?.start ?? list[0]?.end ?? 1;\n      const lo = first > 0 ? first : positive / 2;\n      const span = Math.log(last / lo) || 1;\n      const pos = (v: number) =>\n        Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n      const inv = (x: number) => lo * Math.exp(x * span);\n      return {\n        bars: list.map((b) => ({\n          ...b,\n          overflow: false,\n          x0: pos(b.start),\n          x1: pos(b.end),\n        })),\n        lo,\n        hi: last,\n        top: last,\n        pos,\n        inv,\n      };\n    }\n    const span = last - first || 1;\n    const pos = (v: number) => Math.min(1, Math.max(0, (v - first) / span));\n    const inv = (x: number) => first + x * span;\n    return {\n      bars: list.map((b) => ({\n        ...b,\n        overflow: false,\n        x0: pos(b.start),\n        x1: pos(b.end),\n      })),\n      lo: first,\n      hi: last,\n      top: last,\n      pos,\n      inv,\n    };\n  }\n\n  const sorted = d.sorted!;\n  if (scale === \"log\") {\n    const positive = sorted[lowerBound(sorted, Number.MIN_VALUE)] ?? 1;\n    const lo =\n      domain?.[0] && domain[0] > 0\n        ? domain[0]\n        : nice125(Math.max(positive, 1e-9), false);\n    const hi = Math.max(\n      domain?.[1] ?? nice125(Math.max(d.max, lo * 10), true),\n      lo * 1.0001,\n    );\n    const span = Math.log(hi / lo);\n    const step = span / count;\n    const bars: Bar[] = Array.from({ length: count }, (_, i) => ({\n      start: lo * Math.exp(i * step),\n      end: lo * Math.exp((i + 1) * step),\n      count: 0,\n      overflow: false,\n      x0: i / count,\n      x1: (i + 1) / count,\n    }));\n    for (const v of sorted) {\n      const i = v <= lo ? 0 : Math.floor(Math.log(v / lo) / step);\n      bars[Math.min(count - 1, Math.max(0, i))].count += 1;\n    }\n    const pos = (v: number) =>\n      Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n    return { bars, lo, hi, top: hi, pos, inv: (x) => lo * Math.exp(x * span) };\n  }\n\n  const lo = domain?.[0] ?? (d.min >= 0 ? 0 : -niceStep(-d.min));\n  const wanted = domain?.[1] ?? Math.max(reach, lo + 1e-9);\n  const step = niceStep((wanted - lo) / count);\n  const n = Math.max(1, Math.ceil((wanted - lo) / step - 1e-9));\n  const hi = lo + n * step;\n  const overflowCount = d.total - upperBound(sorted, hi);\n  const units = overflowCount > 0 ? n + 1.7 : n;\n  const bars: Bar[] = Array.from({ length: n }, (_, i) => ({\n    start: tidy(lo + i * step),\n    end: tidy(lo + (i + 1) * step),\n    count: 0,\n    overflow: false,\n    x0: i / units,\n    x1: (i + 1) / units,\n  }));\n  for (\n    let k = lowerBound(sorted, lo), end = upperBound(sorted, hi);\n    k < end;\n    k++\n  )\n    bars[Math.min(n - 1, Math.floor((sorted[k] - lo) / step))].count += 1;\n  // Values below a fixed domain fold into the first bar.\n  bars[0].count += lowerBound(sorted, lo);\n  const top = Math.max(hi, d.max);\n  if (overflowCount > 0)\n    bars.push({\n      start: hi,\n      end: top,\n      count: overflowCount,\n      overflow: true,\n      x0: (n + 0.7) / units,\n      x1: 1,\n    });\n  const mainEnd = n / units;\n  const overflowStart = (n + 0.7) / units;\n  const pos = (v: number) => {\n    if (v <= hi) return Math.max(0, ((v - lo) / (hi - lo)) * mainEnd);\n    if (overflowCount <= 0 || top <= hi) return mainEnd;\n    return Math.min(\n      1,\n      overflowStart + ((v - hi) / (top - hi)) * (1 - overflowStart),\n    );\n  };\n  const inv = (x: number) => {\n    if (x <= mainEnd) return lo + (x / mainEnd) * (hi - lo);\n    if (x < overflowStart || overflowCount <= 0) return hi;\n    return hi + ((x - overflowStart) / (1 - overflowStart)) * (top - hi);\n  };\n  return { bars, lo, hi, top, pos, inv };\n}\n\n/** Bin a comparison into the main bars' edges. */\nfunction binCompare(compare: number[] | LatencyBucket[], bars: Bar[]) {\n  const counts = new Array<number>(bars.length).fill(0);\n  if (!bars.length) return { counts, total: 0 };\n  const find = (v: number) => {\n    let lo = 0;\n    let hi = bars.length - 1;\n    while (lo < hi) {\n      const mid = (lo + hi + 1) >> 1;\n      if (bars[mid].start <= v) lo = mid;\n      else hi = mid - 1;\n    }\n    return lo;\n  };\n  let total = 0;\n  for (const item of compare as (number | LatencyBucket)[]) {\n    if (typeof item === \"number\") {\n      if (!Number.isFinite(item)) continue;\n      counts[find(item)] += 1;\n      total += 1;\n    } else if (Number.isFinite(item.count)) {\n      counts[find((item.start + item.end) / 2)] += item.count;\n      total += item.count;\n    }\n  }\n  return { counts, total };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [controlled ? value : inner, set] as const;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\nconst percentileName = (p: number) => `p${tidy(p)}`;\n\n/* ------------------------------------------------------------------------ */\n/* LatencyHistogram                                                          */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A latency distribution: bucketed requests with percentile markers, an SLO tail,\n * an optional comparison, and brushing to measure any range.\n */\nexport function LatencyHistogram({\n  values,\n  buckets,\n  compare,\n  compareLabel = \"Previous\",\n  seriesLabel = \"Current\",\n  compareStyle = \"step\",\n  percentiles = [50, 90, 95, 99],\n  threshold,\n  thresholdLabel = \"SLO\",\n  scale: scaleProp,\n  defaultScale = \"linear\",\n  onScaleChange,\n  showScaleToggle = true,\n  range: rangeProp,\n  defaultRange = null,\n  onRangeChange,\n  title,\n  description,\n  actions,\n  unit = \"ms\",\n  valueFormatter,\n  bucketCount = 40,\n  domain,\n  height,\n  colors: colorsProp,\n  renderTooltip,\n  showSummary = true,\n  className,\n  ...props\n}: LatencyHistogramProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const format = React.useMemo(\n    () => valueFormatter ?? makeFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const formatTick = React.useMemo(\n    () => valueFormatter ?? makeTickFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const colors: LatencyHistogramColors = {\n    bar: \"var(--color-chart-1)\",\n    compare: \"var(--color-muted-foreground)\",\n    threshold: \"var(--color-destructive)\",\n    marker: \"var(--color-foreground)\",\n    selection: \"var(--color-primary)\",\n    ...colorsProp,\n  };\n  const [scale, setScale] = useControllable(\n    scaleProp,\n    defaultScale,\n    onScaleChange,\n  );\n  const [range, setRange] = useControllable<LatencyRange | null>(\n    rangeProp,\n    defaultRange,\n    onRangeChange,\n  );\n  const hasThreshold = threshold != null && Number.isFinite(threshold);\n\n  const dist = React.useMemo(\n    () => distributionOf(values, buckets),\n    [values, buckets],\n  );\n  const sortedPercentiles = React.useMemo(\n    () =>\n      [...new Set(percentiles.filter((p) => p > 0 && p < 100))].sort(\n        (a, b) => a - b,\n      ),\n    [percentiles],\n  );\n  const empty = dist.total === 0;\n  const marks = React.useMemo(\n    () =>\n      dist.total === 0\n        ? []\n        : sortedPercentiles.map((p) => ({ p, value: quantile(dist, p / 100) })),\n    [dist, sortedPercentiles],\n  );\n\n  // Linear charts end just past the slow tail (and the SLO); the rest lands in an overflow bar.\n  const reach = Math.max(\n    quantile(dist, 0.995),\n    (marks[marks.length - 1]?.value ?? 0) * 1.04,\n    hasThreshold ? threshold! * 1.12 : 0,\n  );\n  const layout = React.useMemo(\n    () => layoutOf(dist, scale, bucketCount, reach, domain),\n    [dist, scale, bucketCount, reach, domain],\n  );\n  const { bars, pos, inv } = layout;\n\n  const comparison = React.useMemo(() => {\n    if (!compare?.length) return null;\n    const { counts, total } = binCompare(compare, bars);\n    const percentilesOf = (() => {\n      if (typeof compare[0] === \"number\") {\n        const d = distributionOf(compare as number[]);\n        return sortedPercentiles.map((p) => quantile(d, p / 100));\n      }\n      const d = distributionOf(undefined, compare as LatencyBucket[]);\n      return sortedPercentiles.map((p) => quantile(d, p / 100));\n    })();\n    const factor = total ? dist.total / total : 0;\n    return {\n      counts,\n      total,\n      scaled: counts.map((c) => c * factor),\n      percentiles: percentilesOf,\n    };\n  }, [compare, bars, dist.total, sortedPercentiles]);\n\n  const maxCount = Math.max(\n    1,\n    ...bars.map((b) => b.count),\n    ...(comparison?.scaled ?? [0]),\n  );\n  // The tallest bar fills the plot; gridlines sit at round counts below it.\n  const yMax = maxCount * 1.06;\n  const yStep = niceStep(maxCount / 3.2);\n  const yTicks = Array.from(\n    { length: Math.floor(yMax / yStep + 1e-9) + 1 },\n    (_, i) => tidy(i * yStep),\n  );\n\n  const over = hasThreshold ? countAbove(dist, threshold!) : 0;\n  const overShare = dist.total ? over / dist.total : 0;\n  const thresholdX = hasThreshold ? pos(threshold!) : 1;\n\n  const cumulative = React.useMemo(() => {\n    let running = 0;\n    return bars.map((b) => (running += b.count) / (dist.total || 1));\n  }, [bars, dist.total]);\n\n  const bucketAt = (index: number): LatencyHistogramBucket => {\n    const b = bars[index];\n    return {\n      index,\n      start: b.start,\n      end: b.end,\n      count: b.count,\n      share: dist.total ? b.count / dist.total : 0,\n      cumulative: cumulative[index] ?? 0,\n      compare: comparison ? comparison.counts[index] : undefined,\n      compareShare: comparison?.total\n        ? comparison.counts[index] / comparison.total\n        : undefined,\n      overflow: b.overflow,\n      overThreshold: hasThreshold && b.start >= threshold!,\n    };\n  };\n\n  /* -------------------------------------------------------------- layout */\n\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(el.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const W = width || 560;\n\n  // Percentile chips stack into lanes only when they would collide.\n  // With the summary on show, crowded chips drop their values, which the summary repeats.\n  const chips = React.useMemo(() => {\n    const place = (withValue: boolean) => {\n      const lanes: number[] = [];\n      return marks.map((mark) => {\n        const text = withValue\n          ? `${percentileName(mark.p)} ${format(mark.value)}`\n          : percentileName(mark.p);\n        const w = text.length * 6.1 + 14;\n        const x = pos(mark.value) * W;\n        const left = Math.min(Math.max(0, x - w / 2), Math.max(0, W - w));\n        let lane = lanes.findIndex((right) => right + 4 <= left);\n        if (lane < 0) lane = lanes.push(0) - 1;\n        lanes[lane] = left + w;\n        return { ...mark, x, left, lane, w, withValue };\n      });\n    };\n    const full = place(true);\n    if (!showSummary || full.every((chip) => chip.lane === 0)) return full;\n    return place(false);\n  }, [marks, pos, W, format, showSummary]);\n  const laneCount = Math.max(1, ...chips.map((chip) => chip.lane + 1));\n  const chipTop = laneCount * 20 + 6;\n  // Without a fixed height the plot follows the card width, shorter on narrow cards.\n  const H = Math.max(\n    80,\n    height ?? Math.round(Math.min(220, Math.max(140, W * 0.34))),\n  );\n  const barsHeight = H - chipTop;\n\n  const xTicks = React.useMemo(() => {\n    const ticks: number[] = [];\n    if (empty) return ticks;\n    if (scale === \"log\" || dist.buckets) {\n      if (scale === \"log\") {\n        const lo = layout.lo;\n        const hi = layout.hi;\n        const candidates: number[] = [];\n        for (\n          let e = Math.floor(Math.log10(lo));\n          e <= Math.ceil(Math.log10(hi));\n          e++\n        )\n          for (const m of [1, 2, 5]) {\n            const v = tidy(m * 10 ** e);\n            if (v >= lo * 0.999 && v <= hi * 1.001) candidates.push(v);\n          }\n        // Thin out 2s and then 5s until labels have room.\n        for (const keep of [[1, 2, 5], [1, 5], [1]]) {\n          const list = candidates.filter((v) =>\n            keep.includes(\n              Math.round(v / 10 ** Math.floor(Math.log10(v) + 1e-9)),\n            ),\n          );\n          let ok = true;\n          for (let i = 1; i < list.length; i++)\n            if ((pos(list[i]) - pos(list[i - 1])) * W < 44) ok = false;\n          if (ok || keep.length === 1) return list;\n        }\n      }\n    }\n    const lo = layout.lo;\n    const hi = layout.hi;\n    const step = niceStep((hi - lo) / Math.max(2, Math.floor(W / 76)));\n    for (\n      let v = Math.ceil(lo / step - 1e-9) * step;\n      v <= hi + step * 1e-6;\n      v += step\n    )\n      ticks.push(tidy(v));\n    return ticks;\n  }, [scale, dist.buckets, layout, pos, W, empty]);\n\n  /* ----------------------------------------------------------- animation */\n\n  // Bars grow in on mount and whenever the bucket layout changes; data updates tween.\n  // Keyed on scale and bar count only, so live data with a drifting tail tweens instead of regrowing.\n  const structure = `${scale}:${bars.length}`;\n  const [grown, setGrown] = React.useState<string | null>(null);\n  const [intro, setIntro] = React.useState(true);\n  React.useEffect(() => {\n    if (reduced) {\n      setGrown(structure);\n      setIntro(false);\n      return;\n    }\n    setIntro(true);\n    let frame = requestAnimationFrame(() => {\n      frame = requestAnimationFrame(() => setGrown(structure));\n    });\n    const timer = window.setTimeout(\n      () => setIntro(false),\n      900 + bars.length * 9,\n    );\n    return () => {\n      cancelAnimationFrame(frame);\n      window.clearTimeout(timer);\n    };\n  }, [structure, reduced, bars.length]);\n  const isGrown = grown === structure;\n\n  /* --------------------------------------------------------- interaction */\n\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [brush, setBrush] = React.useState<LatencyRange | null>(null);\n  const drag = React.useRef<{\n    x: number;\n    value: number;\n    moved: boolean;\n  } | null>(null);\n  const anchor = React.useRef<number | null>(null);\n\n  const xToFraction = (clientX: number) => {\n    const rect = plotRef.current!.getBoundingClientRect();\n    return Math.min(1, Math.max(0, (clientX - rect.left) / (rect.width || 1)));\n  };\n  const barAt = (x: number) => {\n    for (let i = 0; i < bars.length; i++)\n      if (x >= bars[i].x0 && x <= bars[i].x1) return i;\n    // In a gap: the nearest bar.\n    let best = -1;\n    let distance = Infinity;\n    bars.forEach((b, i) => {\n      const dd = Math.min(Math.abs(x - b.x0), Math.abs(x - b.x1));\n      if (dd < distance) {\n        distance = dd;\n        best = i;\n      }\n    });\n    return best < 0 ? null : best;\n  };\n\n  const clampRange = (a: number, b: number): LatencyRange => [\n    Math.min(a, b),\n    Math.max(a, b),\n  ];\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0 || !bars.length) return;\n    const x = xToFraction(event.clientX);\n    drag.current = { x: event.clientX, value: inv(x), moved: false };\n    event.currentTarget.setPointerCapture(event.pointerId);\n  };\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const x = xToFraction(event.clientX);\n    const d = drag.current;\n    if (d) {\n      if (!d.moved && Math.abs(event.clientX - d.x) > 3) d.moved = true;\n      if (d.moved) {\n        setBrush(clampRange(d.value, inv(x)));\n        setHover(null);\n        return;\n      }\n    }\n    setHover(barAt(x));\n  };\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    drag.current = null;\n    if (!d) return;\n    if (d.moved) {\n      const next = clampRange(d.value, inv(xToFraction(event.clientX)));\n      setBrush(null);\n      setRange(next[1] - next[0] > 0 ? next : null);\n    } else if (range) setRange(null);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const current = active ?? -1;\n    const step = (delta: number) =>\n      Math.min(\n        bars.length - 1,\n        Math.max(\n          0,\n          current < 0 ? (delta > 0 ? 0 : bars.length - 1) : current + delta,\n        ),\n      );\n    let next: number | null = null;\n    if (event.key === \"ArrowRight\") next = step(1);\n    else if (event.key === \"ArrowLeft\") next = step(-1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = bars.length - 1;\n    else if (event.key === \"Enter\" && current >= 0) {\n      setRange([bars[current].start, bars[current].end]);\n      event.preventDefault();\n      return;\n    } else if (event.key === \"Escape\") {\n      if (range) setRange(null);\n      else setActive(null);\n      anchor.current = null;\n      event.preventDefault();\n      return;\n    }\n    if (next == null) return;\n    event.preventDefault();\n    if (event.shiftKey) {\n      if (anchor.current == null) anchor.current = current < 0 ? next : current;\n      const a = Math.min(anchor.current, next);\n      const b = Math.max(anchor.current, next);\n      setRange([bars[a].start, bars[b].end]);\n    } else anchor.current = null;\n    setActive(next);\n  };\n\n  const shownRange = brush ?? range;\n  const rangeCount = shownRange\n    ? countBetween(dist, shownRange[0], shownRange[1])\n    : 0;\n  const rangeShare = dist.total ? rangeCount / dist.total : 0;\n  const focusIndex = hover ?? active;\n  const focusBucket =\n    focusIndex != null && bars[focusIndex] ? bucketAt(focusIndex) : null;\n\n  /* -------------------------------------------------------------- render */\n\n  const describeBucket = (b: LatencyHistogramBucket) =>\n    `${b.overflow ? `${format(b.start)} and above` : `${format(b.start)} to ${format(b.end)}`}: ${whole.format(Math.round(b.count))} requests, ${percentLabel(b.share)}`;\n  const summaryText = [\n    `${whole.format(Math.round(dist.total))} requests.`,\n    marks\n      .map((mark) => `${percentileName(mark.p)} ${format(mark.value)}`)\n      .join(\", \") + \".\",\n    hasThreshold\n      ? `${percentLabel(overShare)} over the ${thresholdLabel} of ${format(threshold!)}.`\n      : \"\",\n  ]\n    .filter(Boolean)\n    .join(\" \");\n  const hasHeader =\n    title != null || description != null || actions != null || showScaleToggle;\n  const transition = intro\n    ? \"transform 760ms cubic-bezier(.16,1,.3,1)\"\n    : \"transform 520ms cubic-bezier(.16,1,.3,1)\";\n  const barFill = (color: string) =>\n    `color-mix(in oklab, ${color} 72%, var(--color-card))`;\n\n  // The comparison as one stepped path across the bars.\n  const comparePath = React.useMemo(() => {\n    if (!comparison || compareStyle !== \"step\") return null;\n    let path = \"\";\n    let previousEnd = -1;\n    bars.forEach((b, i) => {\n      const y = 100 - (comparison.scaled[i] / yMax) * 100;\n      const x0 = b.x0 * 1000;\n      const x1 = b.x1 * 1000;\n      if (Math.abs(x0 - previousEnd) > 0.5)\n        path += `${path ? \"V100\" : \"\"}M${x0.toFixed(2)} 100`;\n      path += `V${y.toFixed(2)}H${x1.toFixed(2)}`;\n      previousEnd = x1;\n    });\n    return path + \"V100\";\n  }, [comparison, compareStyle, bars, yMax]);\n\n  return (\n    <div\n      data-slot=\"latency-histogram\"\n      data-scale={scale}\n      data-brushing={brush ? true : undefined}\n      className={cn(\n        \"@container/histogram flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex items-start gap-3 px-4 pt-3.5\">\n          <div className=\"min-w-0 flex-1 space-y-1\">\n            {title != null && (\n              <h3 className=\"truncate text-sm leading-6 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            )}\n            {description != null && (\n              <p\n                id={`${id}-description`}\n                className=\"text-xs text-muted-foreground\"\n              >\n                {description}\n              </p>\n            )}\n          </div>\n          <div className=\"flex shrink-0 items-center gap-2\">\n            {actions}\n            {showScaleToggle && (\n              <div\n                role=\"group\"\n                aria-label=\"X axis scale\"\n                data-slot=\"histogram-scale-toggle\"\n                className=\"inline-flex h-7 items-center rounded-md border bg-muted/40 p-0.5\"\n              >\n                {([\"linear\", \"log\"] as const).map((option) => (\n                  <button\n                    key={option}\n                    type=\"button\"\n                    aria-pressed={scale === option}\n                    onClick={() => setScale(option)}\n                    className={cn(\n                      \"h-full rounded-[5px] px-2 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-xs motion-reduce:transition-none\",\n                      focusRing,\n                    )}\n                  >\n                    {option === \"linear\" ? \"Linear\" : \"Log\"}\n                  </button>\n                ))}\n              </div>\n            )}\n          </div>\n        </div>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        // Narrow cards trade the stat grid for one line, so the distribution stays in view.\n        <dl\n          data-slot=\"histogram-summary-compact\"\n          className={cn(\n            \"mx-4 flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs @md/histogram:hidden\",\n            hasHeader ? \"mt-1.5\" : \"mt-4\",\n          )}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div key={mark.p} className=\"flex items-baseline gap-1\">\n                <dt className=\"font-mono text-[11px] text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"font-semibold tabular-nums\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"font-mono text-[10px] tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"}\n                    {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"flex items-baseline gap-1\">\n              <dd\n                className={cn(\n                  \"font-semibold tabular-nums\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dt className=\"text-[11px] text-muted-foreground\">\n                over {thresholdLabel}\n              </dt>\n            </div>\n          )}\n        </dl>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        <dl\n          data-slot=\"histogram-summary\"\n          className={cn(\n            \"mx-4 hidden overflow-hidden rounded-lg bg-muted/50 @md/histogram:grid dark:bg-muted/30\",\n            hasHeader ? \"mt-3\" : \"mt-4\",\n          )}\n          style={{\n            gridTemplateColumns: `repeat(${marks.length + (hasThreshold ? 1 : 0)}, minmax(0, 1fr))`,\n          }}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div\n                key={mark.p}\n                className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\"\n              >\n                <dt className=\"font-mono text-[11px] leading-4 text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"truncate font-mono text-[11px] leading-4 whitespace-nowrap tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                    title={`${compareLabel}: ${format(previous!)}`}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"} {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\">\n              <dt className=\"truncate text-[11px] leading-4 text-muted-foreground\">\n                Over {thresholdLabel}\n              </dt>\n              <dd\n                className={cn(\n                  \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dd className=\"truncate font-mono text-[11px] leading-4 text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(over))}\n                <span className=\"hidden @sm/histogram:inline\">\n                  {\" \"}\n                  of {compact.format(dist.total).replace(\"K\", \"k\")}\n                </span>\n              </dd>\n            </div>\n          )}\n        </dl>\n      )}\n\n      <div className=\"mt-3 flex px-4 @md/histogram:mt-4\">\n        <div className=\"min-w-0 flex-1\">\n          <div\n            ref={plotRef}\n            data-slot=\"histogram-plot\"\n            role=\"group\"\n            aria-roledescription=\"histogram\"\n            aria-label={`${typeof title === \"string\" ? `${title}. ` : \"\"}${summaryText} Use the arrow keys to read buckets, Shift to select a range.`}\n            aria-describedby={\n              description != null ? `${id}-description` : undefined\n            }\n            tabIndex={0}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={() => {\n              drag.current = null;\n              setBrush(null);\n            }}\n            onPointerLeave={() => {\n              if (!drag.current) setHover(null);\n            }}\n            onKeyDown={onKeyDown}\n            onBlur={() => setActive(null)}\n            className={cn(\n              \"relative cursor-crosshair touch-pan-y rounded-sm select-none\",\n              \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\",\n            )}\n            style={{ height: H }}\n          >\n            {empty && (\n              <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\">\n                No requests to show.\n              </p>\n            )}\n\n            {/* Value grid */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {yTicks.map((tick) => (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute inset-x-0 h-px\",\n                    tick === 0 ? \"bg-border\" : \"bg-border/55\",\n                  )}\n                  style={{ bottom: `${(tick / yMax) * 100}%` }}\n                />\n              ))}\n            </div>\n\n            {/* SLO tail */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold-region\"\n                className=\"pointer-events-none absolute inset-y-0 right-0\"\n                style={{\n                  left: `${thresholdX * 100}%`,\n                  background: `linear-gradient(to bottom, color-mix(in oklab, ${colors.threshold} 9%, transparent), color-mix(in oklab, ${colors.threshold} 3%, transparent)), repeating-linear-gradient(-45deg, color-mix(in oklab, ${colors.threshold} 9%, transparent) 0 1px, transparent 1px 6px)`,\n                }}\n              />\n            )}\n\n            {/* Bars */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {comparison &&\n                compareStyle === \"outline\" &&\n                bars.map((b, i) => (\n                  <span\n                    key={`c-${structure}-${i}`}\n                    className=\"absolute bottom-0 origin-bottom rounded-t-[2px] border border-b-0 border-dashed\"\n                    style={{\n                      left: `calc(${b.x0 * 100}% + 1px)`,\n                      width: `calc(${(b.x1 - b.x0) * 100}% - 2px)`,\n                      height: `${(comparison.scaled[i] / yMax) * 100}%`,\n                      borderColor: `color-mix(in oklab, ${colors.compare} 70%, transparent)`,\n                      transform: `scaleY(${isGrown ? 1 : 0})`,\n                      transition: reduced ? undefined : transition,\n                    }}\n                  />\n                ))}\n              {bars.map((b, i) => {\n                const h = b.count / yMax;\n                const inRange = shownRange\n                  ? b.end > shownRange[0] && b.start < shownRange[1]\n                  : true;\n                const dim =\n                  (focusIndex != null && focusIndex !== i) || !inRange;\n                const split =\n                  hasThreshold && b.start < threshold! && b.end > threshold!;\n                const hot = hasThreshold && b.start >= threshold!;\n                const color = hot ? colors.threshold : colors.bar;\n                const cut = split\n                  ? ((thresholdX - b.x0) / (b.x1 - b.x0)) * 100\n                  : 0;\n                const fill = split\n                  ? `linear-gradient(to right, ${barFill(colors.bar)} ${cut}%, ${barFill(colors.threshold)} ${cut}%)`\n                  : barFill(color);\n                const cap = split\n                  ? `linear-gradient(to right, ${colors.bar} ${cut}%, ${colors.threshold} ${cut}%)`\n                  : color;\n                return (\n                  <span\n                    key={`${structure}-${i}`}\n                    data-slot=\"histogram-bar\"\n                    data-index={i}\n                    data-over={hot || undefined}\n                    data-overflow={b.overflow || undefined}\n                    className={cn(\n                      \"absolute inset-y-0 transition-opacity duration-200 motion-reduce:transition-none\",\n                      dim &&\n                        (shownRange && !inRange ? \"opacity-30\" : \"opacity-55\"),\n                    )}\n                    style={{\n                      left: `${b.x0 * 100}%`,\n                      width: `${(b.x1 - b.x0) * 100}%`,\n                    }}\n                  >\n                    <span\n                      className=\"absolute inset-x-px bottom-0 h-full origin-bottom @lg/histogram:inset-x-[1.5px]\"\n                      style={{\n                        transform: `scaleY(${isGrown ? h : 0})`,\n                        transition: reduced ? undefined : transition,\n                        transitionDelay:\n                          intro && !reduced ? `${i * 9}ms` : undefined,\n                      }}\n                    >\n                      <span\n                        className={cn(\n                          \"absolute inset-0 rounded-t-[2px]\",\n                          b.overflow &&\n                            \"[mask-image:repeating-linear-gradient(-45deg,#000_0_3px,rgb(0_0_0/0.55)_3px_5px)]\",\n                        )}\n                        style={{ background: fill }}\n                      />\n                    </span>\n                    {/* The cap is drawn unscaled so it stays a crisp line at any height. */}\n                    {b.count > 0 && (\n                      <span\n                        className=\"absolute inset-x-px h-[1.5px] rounded-full @lg/histogram:inset-x-[1.5px]\"\n                        style={{\n                          bottom: `calc(${(isGrown ? h : 0) * 100}% - 1px)`,\n                          background: cap,\n                          transition: reduced\n                            ? undefined\n                            : intro\n                              ? \"bottom 760ms cubic-bezier(.16,1,.3,1)\"\n                              : \"bottom 520ms cubic-bezier(.16,1,.3,1)\",\n                          transitionDelay:\n                            intro && !reduced ? `${i * 9}ms` : undefined,\n                        }}\n                      />\n                    )}\n                  </span>\n                );\n              })}\n              {comparePath && (\n                <svg\n                  data-slot=\"histogram-compare\"\n                  className=\"absolute inset-0 size-full origin-bottom overflow-visible\"\n                  viewBox=\"0 0 1000 100\"\n                  preserveAspectRatio=\"none\"\n                  style={{\n                    transform: `scaleY(${isGrown ? 1 : 0})`,\n                    transition: reduced ? undefined : transition,\n                  }}\n                >\n                  <path\n                    d={comparePath}\n                    fill=\"none\"\n                    stroke={colors.compare}\n                    strokeWidth={1.5}\n                    strokeDasharray=\"4 3\"\n                    strokeLinejoin=\"round\"\n                    vectorEffect=\"non-scaling-stroke\"\n                    opacity={0.85}\n                  />\n                </svg>\n              )}\n            </div>\n\n            {/* Selection */}\n            {shownRange && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-selection\"\n                className=\"pointer-events-none absolute inset-y-0\"\n                style={{\n                  left: `${pos(shownRange[0]) * 100}%`,\n                  width: `${Math.max(0, pos(shownRange[1]) - pos(shownRange[0])) * 100}%`,\n                  background: `color-mix(in oklab, ${colors.selection} 9%, transparent)`,\n                  boxShadow: `inset 1.5px 0 0 ${colors.selection}, inset -1.5px 0 0 ${colors.selection}`,\n                }}\n              >\n                <span\n                  className=\"absolute top-1/2 -left-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n                <span\n                  className=\"absolute top-1/2 -right-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n              </div>\n            )}\n\n            {/* Threshold line */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold\"\n                className=\"pointer-events-none absolute bottom-0\"\n                style={{ left: `${thresholdX * 100}%`, top: chipTop - 2 }}\n              >\n                <span\n                  className=\"absolute inset-y-0 w-0 border-l-[1.5px] border-dashed\"\n                  style={{ borderColor: colors.threshold }}\n                />\n                <span\n                  className=\"absolute top-1 left-1 rounded-sm bg-card/85 px-1 font-mono text-[10px] leading-4 font-medium whitespace-nowrap\"\n                  style={{ color: colors.threshold }}\n                >\n                  {thresholdLabel} {format(threshold!)}\n                </span>\n              </div>\n            )}\n\n            {/* Percentile markers */}\n            {chips.map((chip) => {\n              const hot = hasThreshold && chip.value > threshold!;\n              const color = hot ? colors.threshold : colors.marker;\n              return (\n                <div\n                  key={chip.p}\n                  data-slot=\"histogram-marker\"\n                  data-percentile={chip.p}\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none\"\n                >\n                  <span\n                    className=\"absolute bottom-0 w-0 border-l border-dashed opacity-55\"\n                    style={{\n                      left: chip.x,\n                      top: chip.lane * 20 + 18,\n                      borderColor: color,\n                    }}\n                  />\n                  <span\n                    className={cn(\n                      \"absolute flex h-[18px] items-center gap-1 rounded-[5px] border bg-card px-1.5 font-mono text-[10px] leading-none whitespace-nowrap shadow-xs tabular-nums\",\n                      intro &&\n                        !reduced &&\n                        \"motion-safe:animate-[histogram-rise_.5s_.35s_cubic-bezier(.16,1,.3,1)_both]\",\n                    )}\n                    style={{\n                      left: chip.left,\n                      top: chip.lane * 20,\n                      borderColor: `color-mix(in oklab, ${color} 28%, var(--color-border))`,\n                    }}\n                  >\n                    <span className=\"text-muted-foreground\">\n                      {percentileName(chip.p)}\n                    </span>\n                    {chip.withValue && (\n                      <span className=\"font-semibold\" style={{ color }}>\n                        {format(chip.value)}\n                      </span>\n                    )}\n                  </span>\n                </div>\n              );\n            })}\n\n            {/* Tooltip */}\n            {focusBucket && !brush && (\n              <div\n                data-slot=\"histogram-tooltip\"\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-popover px-2.5 py-2 text-xs text-popover-foreground shadow-md\"\n                style={{\n                  top: chipTop + 4,\n                  // Sit beside the bar, on the side with more room, so it never hides it.\n                  ...(bars[focusBucket.index].x0 + bars[focusBucket.index].x1 <\n                  1\n                    ? { left: bars[focusBucket.index].x1 * W + 8 }\n                    : { right: W - bars[focusBucket.index].x0 * W + 8 }),\n                }}\n              >\n                {renderTooltip ? (\n                  renderTooltip(focusBucket)\n                ) : (\n                  <>\n                    <p className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">\n                      {focusBucket.overflow\n                        ? `≥ ${format(focusBucket.start)}`\n                        : `${format(focusBucket.start)} – ${format(focusBucket.end)}`}\n                    </p>\n                    <p className=\"mt-0.5 flex items-baseline gap-1.5\">\n                      <span className=\"text-sm font-semibold tabular-nums\">\n                        {whole.format(Math.round(focusBucket.count))}\n                      </span>\n                      <span className=\"text-muted-foreground tabular-nums\">\n                        {percentLabel(focusBucket.share)}\n                      </span>\n                    </p>\n                    <p className=\"mt-1 text-[11px] text-muted-foreground tabular-nums\">\n                      {percentLabel(focusBucket.cumulative)} at or faster\n                    </p>\n                    {focusBucket.compare != null && comparison && (\n                      <p className=\"mt-1.5 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground tabular-nums\">\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"w-3 border-t-[1.5px] border-dashed\"\n                          style={{ borderColor: colors.compare }}\n                        />\n                        {compareLabel}\n                        <span className=\"ml-auto font-medium text-foreground\">\n                          {whole.format(Math.round(focusBucket.compare))}\n                        </span>\n                        <span>\n                          {percentLabel(focusBucket.compareShare ?? 0)}\n                        </span>\n                      </p>\n                    )}\n                  </>\n                )}\n              </div>\n            )}\n          </div>\n\n          {/* Latency axis */}\n          <div\n            aria-hidden=\"true\"\n            className=\"relative mt-1.5 h-4 font-mono text-[10px] leading-4 text-muted-foreground tabular-nums\"\n          >\n            {xTicks.map((tick, i) => {\n              const x = pos(tick);\n              if (x > layout.pos(layout.hi) + 1e-6) return null;\n              return (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute whitespace-nowrap\",\n                    i === 0 && x < 0.02\n                      ? \"\"\n                      : x > 0.97\n                        ? \"-translate-x-full\"\n                        : \"-translate-x-1/2\",\n                  )}\n                  style={{ left: `${x * 100}%` }}\n                >\n                  {formatTick(tick)}\n                </span>\n              );\n            })}\n            {bars[bars.length - 1]?.overflow && (\n              <span\n                className=\"absolute -translate-x-1/2 whitespace-nowrap\"\n                style={{\n                  left: `${((bars[bars.length - 1].x0 + 1) / 2) * 100}%`,\n                }}\n              >\n                +\n              </span>\n            )}\n          </div>\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"relative ml-2 w-8 shrink-0\"\n          style={{ height: H }}\n        >\n          {yTicks.map((tick) => (\n            <span\n              key={tick}\n              className=\"absolute right-0 translate-y-1/2 font-mono text-[10px] leading-none text-muted-foreground tabular-nums\"\n              style={{ bottom: `${(tick / yMax) * (barsHeight / H) * 100}%` }}\n            >\n              {tick === 0 ? \"0\" : compact.format(tick).replace(\"K\", \"k\")}\n            </span>\n          ))}\n        </div>\n      </div>\n\n      <div\n        data-slot=\"histogram-footer\"\n        className=\"mt-3 flex min-h-11 flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t px-4 py-2\"\n      >\n        <div\n          data-slot=\"histogram-status\"\n          className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs\"\n        >\n          {shownRange ? (\n            <>\n              <span\n                className=\"rounded-[4px] px-1.5 py-px font-mono text-[11px] tabular-nums\"\n                style={{\n                  background: `color-mix(in oklab, ${colors.selection} 10%, transparent)`,\n                  color: colors.selection,\n                }}\n              >\n                {format(shownRange[0])} – {format(shownRange[1])}\n              </span>\n              <span className=\"font-semibold tabular-nums\">\n                {percentLabel(rangeShare)}\n              </span>\n              <span className=\"text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(rangeCount))} of{\" \"}\n                {whole.format(Math.round(dist.total))} requests\n              </span>\n              {!brush && (\n                <button\n                  type=\"button\"\n                  onClick={() => setRange(null)}\n                  className={cn(\n                    \"inline-flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\",\n                    focusRing,\n                  )}\n                >\n                  <X className=\"size-3.5\" aria-hidden=\"true\" />\n                  <span className=\"sr-only\">Clear selection</span>\n                </button>\n              )}\n            </>\n          ) : (\n            <span className=\"text-muted-foreground tabular-nums\">\n              <span className=\"font-medium text-foreground\">\n                {whole.format(Math.round(dist.total))}\n              </span>{\" \"}\n              requests\n              <span aria-hidden=\"true\"> · </span>mean{\" \"}\n              <span className=\"font-medium text-foreground\">\n                {format(dist.mean)}\n              </span>\n              <span className=\"hidden @md/histogram:inline\">\n                <span aria-hidden=\"true\"> · </span>max{\" \"}\n                <span className=\"font-medium text-foreground\">\n                  {format(dist.max)}\n                </span>\n              </span>\n              <span className=\"hidden @lg/histogram:inline\">\n                {\" \"}\n                · drag to measure a range\n              </span>\n            </span>\n          )}\n        </div>\n        {comparison && (\n          <div\n            data-slot=\"histogram-legend\"\n            className=\"flex items-center gap-3 text-[11px] text-muted-foreground\"\n          >\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"size-2.5 rounded-[2px]\"\n                style={{\n                  background: barFill(colors.bar),\n                  boxShadow: `inset 0 1.5px 0 ${colors.bar}`,\n                }}\n              />\n              {seriesLabel}\n            </span>\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"w-3.5 border-t-[1.5px] border-dashed\"\n                style={{ borderColor: colors.compare }}\n              />\n              {compareLabel}\n            </span>\n          </div>\n        )}\n      </div>\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{summaryText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Latency</th>\n              <th scope=\"col\">Requests</th>\n              {comparison && <th scope=\"col\">{compareLabel}</th>}\n            </tr>\n          </thead>\n          <tbody>\n            {bars.map((b, i) =>\n              b.count > 0 || comparison?.counts[i] ? (\n                <tr key={i}>\n                  <th scope=\"row\">\n                    {b.overflow\n                      ? `${format(b.start)} and above`\n                      : `${format(b.start)} to ${format(b.end)}`}\n                  </th>\n                  <td>{whole.format(Math.round(b.count))}</td>\n                  {comparison && (\n                    <td>{whole.format(Math.round(comparison.counts[i]))}</td>\n                  )}\n                </tr>\n              ) : null,\n            )}\n          </tbody>\n        </table>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {active != null && bars[active]\n          ? describeBucket(bucketAt(active))\n          : range\n            ? `Selected ${format(range[0])} to ${format(range[1])}: ${percentLabel(dist.total ? countBetween(dist, range[0], range[1]) / dist.total : 0)} of requests.`\n            : \"\"}\n      </p>\n\n      <style href=\"overtrue-latency-histogram\" precedence=\"default\">\n        {`@keyframes histogram-rise{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}`}\n      </style>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/latency-histogram. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
