{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "line-chart",
  "title": "Line chart",
  "description": "Multi-series lines that draw in staggered, a legend that toggles series while the scale refits, a crosshair that reads every series at once, and a dashed forecast segment behind a divider.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/chart-legend.json",
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/charts/line-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\nimport { cn } from \"@/lib/utils\"\nimport { ChartLegend } from \"@/components/goodui/chart-legend\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\nexport type LineSeries = {\n  key: string\n  label: string\n  /** One value per category, in order. */\n  data: number[]\n  /** Any CSS color. Defaults to the theme chart colors in series order (--chart-1 … --chart-5). */\n  color?: string\n}\n\nexport type LineChartLabels = {\n  /** Screen reader summary; `name` is the title when it is a string. */\n  summary: (name: string, seriesCount: number, periodCount: number) => string\n  /** Announced while scrubbing: `parts` is \"Series: value, Series: value\". */\n  point: (period: string, parts: string) => string\n  /** Marks the dashed forecast segment. */\n  forecast: string\n  legend: string\n  /** First column header of the screen reader table. */\n  columnPeriod: string\n  noData: string\n}\nconst DEFAULT_LABELS: LineChartLabels = {\n  summary: (name, s, p) => `${name ? name + \": \" : \"\"}${s} series over ${p} periods`,\n  point: (period, parts) => `${period}: ${parts}`,\n  forecast: \"Forecast\",\n  legend: \"Series\",\n  columnPeriod: \"Period\",\n  noData: \"No data\",\n}\n\nexport type LineChartProps = Omit<React.ComponentProps<\"div\">, \"title\" | \"hidden\"> & {\n  series: LineSeries[]\n  /** X labels, one per data point. */\n  categories: string[]\n  /** Chart name for screen readers and the table caption. */\n  title?: React.ReactNode\n  /** Index from which the lines are drawn dashed (a projection); a divider labelled \"Forecast\" marks it. */\n  forecastFrom?: number\n  /** Keys of hidden series (controlled). */\n  hidden?: string[]\n  defaultHidden?: string[]\n  onHiddenChange?: (hidden: string[]) => void\n  /** Legend placement; a single series shows none. */\n  legend?: \"top\" | \"bottom\" | \"none\"\n  /** Plot height in px, axes included. The width follows the container. */\n  height?: number\n  curve?: \"smooth\" | \"linear\"\n  /** zero keeps 0 in view; auto zooms to the data. */\n  baseline?: \"zero\" | \"auto\"\n  grid?: boolean\n  axis?: boolean\n  axisWidth?: number\n  /** Ring dot on the last point of every line. */\n  endDots?: boolean\n  /** Intl.NumberFormat options for values and ticks. */\n  format?: Intl.NumberFormatOptions\n  locale?: string\n  formatValue?: (value: number) => string\n  formatTick?: (value: number) => string\n  /** Resampled points per line; constant, so lines morph when the data changes. */\n  samples?: number\n  /** Seconds one line takes to draw; lines stagger by 0.12 s. */\n  duration?: number\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<LineChartLabels>\n}\n\nfunction useReduce() {\n  const prefers = useReducedMotion()\n  const [mounted, setMounted] = React.useState(false)\n  React.useEffect(() => setMounted(true), [])\n  return mounted && !!prefers\n}\n\nfunction useInView(ref: React.RefObject<Element | null>, threshold = 0.2) {\n  const [inView, setInView] = React.useState(false)\n  React.useEffect(() => {\n    const el = ref.current\n    if (!el || inView) return\n    if (typeof IntersectionObserver === \"undefined\") {\n      setInView(true)\n      return\n    }\n    const io = new IntersectionObserver(\n      ([e]) => {\n        if (e?.isIntersecting) {\n          setInView(true)\n          io.disconnect()\n        }\n      },\n      { threshold },\n    )\n    io.observe(el)\n    return () => io.disconnect()\n  }, [ref, inView, threshold])\n  return inView\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState<number | null>(null)\n  React.useLayoutEffect(() => {\n    const el = ref.current\n    if (!el) return\n    // A hidden parent (display:none) measures 0: keep the last real width instead of collapsing the chart.\n    const measure = () => {\n      const w = Math.round(el.clientWidth)\n      if (w > 0) setWidth(Math.max(120, w))\n    }\n    measure()\n    const ro = new ResizeObserver(measure)\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [ref])\n  return width\n}\n\nfunction niceTicks(lo: number, hi: number, count = 4): number[] {\n  if (hi <= lo) hi = lo + 1\n  const raw = (hi - lo) / count\n  const mag = 10 ** Math.floor(Math.log10(raw))\n  const norm = raw / mag\n  const step = (norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 2.5 ? 2.5 : norm <= 5 ? 5 : 10) * mag\n  const start = Math.floor(lo / step) * step\n  const end = Math.ceil(hi / step) * step\n  const ticks: number[] = []\n  for (let v = start; v <= end + step / 2; v += step) ticks.push(Number(v.toFixed(10)))\n  return ticks\n}\n\n/** Monotone cubic (Fritsch–Carlson) or linear resampling at n evenly spaced positions. */\nfunction sampleCurve(values: number[], n: number, smooth: boolean): number[] {\n  const len = values.length\n  if (len === 0) return []\n  if (len === 1) return Array.from({ length: n }, () => values[0] ?? 0)\n  const d: number[] = []\n  for (let i = 0; i < len - 1; i++) d.push((values[i + 1] ?? 0) - (values[i] ?? 0))\n  const m: number[] = [d[0] ?? 0]\n  for (let i = 1; i < len - 1; i++) {\n    const a = d[i - 1] ?? 0\n    const b = d[i] ?? 0\n    m.push(a * b <= 0 ? 0 : (a + b) / 2)\n  }\n  m.push(d[len - 2] ?? 0)\n  for (let i = 0; i < len - 1; i++) {\n    const di = d[i] ?? 0\n    if (di === 0) {\n      m[i] = 0\n      m[i + 1] = 0\n      continue\n    }\n    const a = (m[i] ?? 0) / di\n    const b = (m[i + 1] ?? 0) / di\n    const s = a * a + b * b\n    if (s > 9) {\n      const k = 3 / Math.sqrt(s)\n      m[i] = k * a * di\n      m[i + 1] = k * b * di\n    }\n  }\n  const out: number[] = []\n  for (let i = 0; i < n; i++) {\n    const t = (i / (n - 1)) * (len - 1)\n    const k = Math.min(len - 2, Math.floor(t))\n    const u = t - k\n    const y0 = values[k] ?? 0\n    const y1 = values[k + 1] ?? 0\n    if (!smooth) {\n      out.push(y0 + (y1 - y0) * u)\n      continue\n    }\n    const u2 = u * u\n    const u3 = u2 * u\n    out.push((2 * u3 - 3 * u2 + 1) * y0 + (u3 - 2 * u2 + u) * (m[k] ?? 0) + (-2 * u3 + 3 * u2) * y1 + (u3 - u2) * (m[k + 1] ?? 0))\n  }\n  return out\n}\n\n/** Multi-series line chart: lines draw in on view, a legend toggles them, a crosshair reads every series, and a dashed segment marks the forecast. */\nexport function LineChart({\n  series,\n  categories,\n  title,\n  forecastFrom,\n  hidden: hiddenProp,\n  defaultHidden,\n  onHiddenChange,\n  legend = \"bottom\",\n  height = 240,\n  curve = \"smooth\",\n  baseline = \"zero\",\n  grid = true,\n  axis = true,\n  axisWidth = 44,\n  endDots = true,\n  format,\n  locale = \"en-US\",\n  formatValue,\n  formatTick,\n  samples = 160,\n  duration = 1.1,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: LineChartProps) {\n  const l = useLabels(\"line-chart\", DEFAULT_LABELS, labels)\n  const reduce = useReduce()\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const plotRef = React.useRef<HTMLDivElement>(null)\n  const inView = useInView(rootRef)\n  const width = useWidth(plotRef)\n  const [innerHidden, setInnerHidden] = React.useState<string[]>(defaultHidden ?? [])\n  const hidden = hiddenProp ?? innerHidden\n  const [hot, setHot] = React.useState<string | null>(null)\n  const [active, setActive] = React.useState<number | null>(null)\n\n  const n = categories.length\n  const colorOf = (s: LineSeries, i: number) => s.color ?? `var(--chart-${(i % 5) + 1})`\n  const visible = series.filter((s) => !hidden.includes(s.key))\n  const all = visible.flatMap((s) => s.data.slice(0, n))\n  const min = all.length ? Math.min(...all) : 0\n  const max = all.length ? Math.max(...all) : 0\n  const ticks = niceTicks(baseline === \"zero\" ? Math.min(0, min) : min, baseline === \"zero\" ? Math.max(0, max) : max, 4)\n  const bottom = ticks[0] ?? 0\n  const top = ticks[ticks.length - 1] ?? 1\n  const fmt = React.useMemo(() => formatValue ?? ((v: number) => new Intl.NumberFormat(locale, format).format(v)), [formatValue, locale, format])\n  const tick = React.useMemo(() => {\n    if (formatTick) return formatTick\n    const compact = Math.max(Math.abs(top), Math.abs(bottom)) >= 10000\n    const f = new Intl.NumberFormat(locale, compact ? { ...format, notation: \"compact\", maximumFractionDigits: Math.max(1, format?.minimumFractionDigits ?? 0) } : format)\n    return (v: number) => f.format(v)\n  }, [formatTick, locale, format, top, bottom])\n\n  const W = width ?? 0\n  const hasForecast = forecastFrom !== undefined && forecastFrom > 0 && forecastFrom < n\n  const padL = axis ? axisWidth : 6\n  const padR = 10\n  const padT = hasForecast ? 24 : 12\n  const padB = 24\n  const plotW = Math.max(10, W - padL - padR)\n  const plotH = Math.max(10, height - padT - padB)\n  const yOf = (v: number) => padT + (1 - (v - bottom) / (top - bottom || 1)) * plotH\n  const xOf = (i: number) => padL + (n > 1 ? (i / (n - 1)) * plotW : plotW / 2)\n  const sx = (i: number) => padL + (i / (samples - 1)) * plotW\n  const splitAt = hasForecast ? Math.round(((forecastFrom ?? 0) / (n - 1)) * (samples - 1)) : samples - 1\n  const structure = `${n}-${samples}-${splitAt}`\n\n  const xLabels: number[] = []\n  if (n > 0) {\n    const step = Math.max(1, Math.ceil(n / Math.max(2, Math.floor(plotW / 64))))\n    for (let i = 0; i < n; i += step) xLabels.push(i)\n    const lastShown = xLabels[xLabels.length - 1] ?? 0\n    if (n > 1 && lastShown !== n - 1) {\n      // The last label is always shown; it replaces the previous one when the two would touch.\n      if (((n - 1 - lastShown) * plotW) / (n - 1) >= 56) xLabels.push(n - 1)\n      else xLabels[xLabels.length - 1] = n - 1\n    }\n  }\n\n  const name = typeof title === \"string\" ? title : \"\"\n  const summary = ariaLabel ?? (n && series.length ? l.summary(name, series.length, n) : l.noData)\n  const setHidden = (next: string[]) => {\n    if (hiddenProp === undefined) setInnerHidden(next)\n    onHiddenChange?.(next)\n  }\n\n  const indexAt = (clientX: number) => {\n    const rect = plotRef.current?.getBoundingClientRect()\n    if (!rect || n === 0) return null\n    if (n === 1) return 0\n    return Math.min(n - 1, Math.max(0, Math.round((clientX - rect.left - padL) / (plotW / (n - 1)))))\n  }\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (n === 0) return\n    if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n      e.preventDefault()\n      const dir = e.key === \"ArrowLeft\" ? -1 : 1\n      setActive((i) => Math.min(n - 1, Math.max(0, (i ?? n - 1) + dir)))\n    } else if (e.key === \"Home\" || e.key === \"End\") {\n      e.preventDefault()\n      setActive(e.key === \"Home\" ? 0 : n - 1)\n    } else if (e.key === \"Escape\") setActive(null)\n  }\n\n  const ready = inView || reduce\n  // Once the entrance has played, labels that appear later (a resize) show without the stagger.\n  const [entered, setEntered] = React.useState(false)\n  React.useEffect(() => {\n    if (!inView) return\n    const id = window.setTimeout(() => setEntered(true), reduce ? 0 : duration * 1000 + series.length * 120 + 300)\n    return () => window.clearTimeout(id)\n  }, [inView, reduce, duration, series.length])\n  // A container resize reshapes the chart at once; only data changes morph.\n  const widthRef = React.useRef(W)\n  const resized = widthRef.current !== W\n  widthRef.current = W\n  const ease = [0.65, 0, 0.35, 1] as const\n  const morph = reduce || resized ? { duration: 0 } : spring.morph\n  const snap = reduce ? { duration: 0 } : spring.snap\n  const ax = active !== null ? xOf(active) : 0\n  const tipRight = ax > W * 0.55\n  const period = active !== null ? (categories[active] ?? \"\") : \"\"\n  const activeRows = active !== null ? visible.map((s) => ({ s, i: series.indexOf(s), v: s.data[active] })) : []\n  const announce = active !== null ? l.point(period, activeRows.map((r) => `${r.s.label}: ${r.v === undefined ? \"–\" : fmt(r.v)}`).join(\", \")) : \"\"\n\n  const legendNode =\n    legend !== \"none\" && series.length > 1 ? (\n      <ChartLegend\n        items={series.map((s, i) => ({ key: s.key, label: s.label, color: colorOf(s, i), shape: \"line\" }))}\n        hidden={hidden}\n        onHiddenChange={setHidden}\n        active={hot}\n        onActiveChange={setHot}\n        size=\"sm\"\n        labels={{ legend: l.legend }}\n      />\n    ) : null\n\n  return (\n    <div ref={rootRef} className={cn(\"pc-line-chart flex w-full min-w-0 flex-col gap-2\", className)} {...props}>\n      <GooduiTokens />\n      {legend === \"top\" && legendNode}\n      <div\n        ref={plotRef}\n        role=\"group\"\n        aria-roledescription=\"line chart\"\n        aria-label={summary}\n        tabIndex={0}\n        onPointerMove={(e) => setActive(indexAt(e.clientX))}\n        onPointerLeave={() => setActive(null)}\n        onFocus={() => setActive((i) => i ?? (n ? n - 1 : null))}\n        onBlur={() => setActive(null)}\n        onKeyDown={onKeyDown}\n        className=\"relative w-full touch-pan-y rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/50\"\n        style={{ height }}\n      >\n        {width !== null && n > 0 && (\n          <svg width={W} height={height} viewBox={`0 0 ${W} ${height}`} className=\"absolute inset-0 overflow-visible\" aria-hidden=\"true\">\n            <AnimatePresence initial={false}>\n              {ticks.map((t) => (\n                <motion.g key={t} initial={{ opacity: 0, y: yOf(t) }} animate={{ opacity: 1, y: yOf(t) }} exit={{ opacity: 0 }} transition={morph}>\n                  {grid && <line x1={padL} x2={padL + plotW} y1={0} y2={0} className=\"stroke-border\" strokeWidth={1} />}\n                  {axis && (\n                    <text x={padL - 8} y={0} dy=\".35em\" textAnchor=\"end\" className=\"fill-muted-foreground text-[11px] tabular-nums\">\n                      {tick(t)}\n                    </text>\n                  )}\n                </motion.g>\n              ))}\n            </AnimatePresence>\n            {!grid && <line x1={padL} x2={padL + plotW} y1={padT + plotH} y2={padT + plotH} className=\"stroke-border\" />}\n            {hasForecast && (\n              <motion.g initial={false} animate={{ opacity: ready ? 1 : 0 }} transition={reduce ? { duration: 0 } : { duration: 0.4, delay: duration }}>\n                <line x1={xOf(forecastFrom ?? 0)} x2={xOf(forecastFrom ?? 0)} y1={padT - 4} y2={padT + plotH} className=\"stroke-border\" strokeWidth={1} />\n                <text x={xOf(forecastFrom ?? 0) + 6} y={padT - 8} className=\"fill-muted-foreground text-[10px] font-medium tracking-wide uppercase\">\n                  {l.forecast}\n                </text>\n              </motion.g>\n            )}\n            {series.map((s, i) => {\n              const isHidden = hidden.includes(s.key)\n              const ys = sampleCurve(s.data.slice(0, n), samples, curve === \"smooth\")\n              const pts = ys.map((v, k) => `${sx(k).toFixed(1)},${yOf(v).toFixed(1)}`)\n              const solid = \"M\" + pts.slice(0, splitAt + 1).join(\"L\")\n              const dashed = hasForecast ? \"M\" + pts.slice(splitAt).join(\"L\") : \"\"\n              const color = colorOf(s, i)\n              const dim = hot !== null && hot !== s.key\n              const op = isHidden ? 0 : dim ? 0.25 : 1\n              const lastV = s.data[n - 1]\n              return (\n                <g key={s.key}>\n                  <motion.path\n                    key={`s${structure}`}\n                    d={solid}\n                    fill=\"none\"\n                    style={{ stroke: color }}\n                    strokeWidth={2}\n                    strokeLinecap=\"round\"\n                    strokeLinejoin=\"round\"\n                    initial={false}\n                    animate={{ d: solid, pathLength: ready ? 1 : 0, opacity: ready ? op : 0 }}\n                    transition={{ d: morph, pathLength: reduce ? { duration: 0 } : { duration: duration * (hasForecast ? splitAt / (samples - 1) : 1), delay: i * 0.12, ease }, opacity: { duration: reduce ? 0 : 0.25 } }}\n                  />\n                  {hasForecast && (\n                    <motion.path\n                      key={`f${structure}`}\n                      d={dashed}\n                      fill=\"none\"\n                      style={{ stroke: color }}\n                      strokeWidth={2}\n                      strokeDasharray=\"5 5\"\n                      strokeLinecap=\"round\"\n                      strokeLinejoin=\"round\"\n                      initial={false}\n                      animate={{ d: dashed, opacity: ready ? op : 0 }}\n                      transition={{ d: morph, opacity: reduce ? { duration: 0 } : { duration: 0.5, delay: duration * (splitAt / (samples - 1)) + i * 0.12 } }}\n                    />\n                  )}\n                  {endDots && lastV !== undefined && (\n                    <motion.g\n                      initial={false}\n                      animate={{ x: xOf(n - 1), y: yOf(lastV), scale: ready ? 1 : 0, opacity: ready ? op : 0 }}\n                      transition={{ x: morph, y: morph, scale: reduce ? { duration: 0 } : { ...spring.play, delay: duration * 0.9 + i * 0.12 }, opacity: { duration: 0.2 } }}\n                    >\n                      <circle r={4} style={{ fill: color }} className=\"stroke-background\" strokeWidth={2} />\n                    </motion.g>\n                  )}\n                </g>\n              )\n            })}\n            <g>\n              {xLabels.map((i) => (\n                <motion.text\n                  key={`${categories[i] ?? \"\"}-${i}`}\n                  x={xOf(i)}\n                  y={height - 6}\n                  textAnchor={i === 0 ? \"start\" : i === n - 1 ? \"end\" : \"middle\"}\n                  className=\"fill-muted-foreground text-[11px]\"\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: ready ? 1 : 0 }}\n                  transition={reduce ? { duration: 0 } : entered ? { duration: 0.2 } : { duration: 0.4, delay: 0.1 + (i / Math.max(1, n - 1)) * duration * 0.8 }}\n                >\n                  {categories[i]}\n                </motion.text>\n              ))}\n            </g>\n            {active !== null && (\n              <motion.g initial={false} animate={{ x: ax }} transition={snap}>\n                <line x1={0} x2={0} y1={padT} y2={padT + plotH} className=\"stroke-foreground/35\" strokeWidth={1} />\n                {activeRows.map((r) =>\n                  r.v === undefined ? null : (\n                    <motion.circle key={r.s.key} r={5} style={{ fill: colorOf(r.s, r.i) }} className=\"stroke-background\" strokeWidth={2} initial={false} animate={{ cy: yOf(r.v), opacity: hot !== null && hot !== r.s.key ? 0.25 : 1 }} transition={{ cy: snap, opacity: { duration: 0.2 } }} />\n                  ),\n                )}\n              </motion.g>\n            )}\n          </svg>\n        )}\n        {width !== null && (n === 0 || series.length === 0) && <div className=\"absolute inset-0 grid place-items-center text-sm text-muted-foreground\">{l.noData}</div>}\n        {active !== null && activeRows.length > 0 && (\n          <div\n            className=\"pointer-events-none absolute z-10 flex min-w-32 flex-col gap-1 rounded-md border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-[var(--pc-e2)]\"\n            style={{ left: ax, top: padT, transform: `translateX(${tipRight ? \"calc(-100% - 12px)\" : \"12px\"})` }}\n          >\n            <span className=\"text-muted-foreground\">\n              {period}\n              {hasForecast && active >= (forecastFrom ?? 0) ? ` · ${l.forecast}` : \"\"}\n            </span>\n            {activeRows.map((r) => (\n              <span key={r.s.key} className=\"flex items-center gap-2 whitespace-nowrap\">\n                <span className=\"inline-block h-0.5 w-3 shrink-0 rounded-full\" style={{ background: colorOf(r.s, r.i) }} />\n                <span className=\"flex-1 text-muted-foreground\">{r.s.label}</span>\n                <span className=\"font-semibold tabular-nums\">{r.v === undefined ? \"–\" : fmt(r.v)}</span>\n              </span>\n            ))}\n          </div>\n        )}\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {announce}\n        </span>\n      </div>\n      {legend === \"bottom\" && legendNode}\n      {n > 0 && series.length > 0 && (\n        <div className=\"sr-only\">\n          <table>\n          <caption>{summary}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">{l.columnPeriod}</th>\n              {series.map((s) => (\n                <th key={s.key} scope=\"col\">\n                  {s.label}\n                </th>\n              ))}\n            </tr>\n          </thead>\n          <tbody>\n            {categories.map((c, i) => (\n              <tr key={i}>\n                <th scope=\"row\">\n                  {c}\n                  {hasForecast && i >= (forecastFrom ?? 0) ? ` (${l.forecast})` : \"\"}\n                </th>\n                {series.map((s) => (\n                  <td key={s.key}>{s.data[i] === undefined ? \"\" : fmt(s.data[i] ?? 0)}</td>\n                ))}\n              </tr>\n            ))}\n          </tbody>\n        </table>\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/line-chart.tsx"
    }
  ],
  "categories": [
    "components",
    "charts"
  ],
  "type": "registry:component"
}
